repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
katsumeshi/PhotoInfo
|
refs/heads/master
|
PhotoInfo/Classes/PhotoCollectionViewCell.swift
|
mit
|
1
|
//
// PhotoCollectionViewCell.swift
// photomap
//
// Created by Yuki Matsushita on 5/6/15.
// Copyright (c) 2015 Yuki Matsushita. All rights reserved.
//
import UIKit
import ReactiveCocoa
import Result
class PhotoCollectionViewCell : UICollectionViewCell {
func bind(photo:Photo) {
photo.image.observeOn(UIScheduler()).startWithNext {
let imageView = UIImageView(image: $0)
let pinView = self.generatePinImageView()
pinView.hidden = !photo.hasLocation
imageView.addSubview(pinView)
self.backgroundView = imageView
}
}
private func generatePinImageView() -> UIImageView {
let pinImageView = UIImageView(image: UIImage(named: "pin"))
pinImageView.frame = getPinViewFrame()
return pinImageView
}
private func getPinViewFrame() ->CGRect {
let isIpad = (UIDevice.currentDevice().userInterfaceIdiom == .Pad)
let iconSize:CGFloat = isIpad ? 60 : 30
return CGRect(x: self.frame.size.width - iconSize,
y: self.frame.size.height - iconSize,
width: iconSize,
height: iconSize)
}
}
|
0d62c8e45ab7ce739300e547c0daf587
| 25.487805 | 70 | 0.689687 | false | false | false | false |
josve05a/wikipedia-ios
|
refs/heads/develop
|
Wikipedia/Code/InsertMediaSearchResultPreviewingViewController.swift
|
mit
|
3
|
import UIKit
final class InsertMediaSearchResultPreviewingViewController: UIViewController {
@IBOutlet private weak var imageView: UIImageView!
@IBOutlet private weak var imageInfoViewContainer: UIView!
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
private lazy var imageInfoView = InsertMediaImageInfoView.wmf_viewFromClassNib()!
var selectImageAction: (() -> Void)?
var moreInformationAction: ((URL) -> Void)?
private let searchResult: InsertMediaSearchResult
private let imageURL: URL
private var theme = Theme.standard
init(imageURL: URL, searchResult: InsertMediaSearchResult) {
self.imageURL = imageURL
self.searchResult = searchResult
super.init(nibName: "InsertMediaSearchResultPreviewingViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.accessibilityIgnoresInvertColors = true
imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: { _ in }) {
self.imageView.backgroundColor = self.view.backgroundColor
self.activityIndicator.stopAnimating()
}
imageInfoView.configure(with: searchResult, showLicenseName: false, showMoreInformationButton: false, theme: theme)
imageInfoView.apply(theme: theme)
imageInfoViewContainer.wmf_addSubviewWithConstraintsToEdges(imageInfoView)
apply(theme: theme)
}
override var previewActionItems: [UIPreviewActionItem] {
let selectImageAction = UIPreviewAction(title: WMFLocalizedString("insert-media-image-preview-select-image-action-title", value: "Select image", comment: "Title for preview action that results in image selection"), style: .default, handler: { [weak self] (_, _) in
self?.selectImageAction?()
})
let moreInformationAction = UIPreviewAction(title: WMFLocalizedString("insert-media-image-preview-more-information-action-title", value: "More information", comment: "Title for preview action that results in presenting more information"), style: .default, handler: { [weak self] (_, _) in
guard let url = self?.searchResult.imageInfo?.filePageURL else {
return
}
self?.moreInformationAction?(url)
})
let cancelAction = UIPreviewAction(title: CommonStrings.cancelActionTitle, style: .default) { (_, _) in }
return [selectImageAction, moreInformationAction, cancelAction]
}
}
extension InsertMediaSearchResultPreviewingViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
imageView.backgroundColor = view.backgroundColor
activityIndicator.style = theme.isDark ? .white : .gray
imageInfoView.apply(theme: theme)
}
}
|
353bff160c14752b3f4fe6f0eff1bb1e
| 45.257576 | 296 | 0.70357 | false | false | false | false |
HabitRPG/habitrpg-ios
|
refs/heads/develop
|
HabitRPG/Views/ClassSelectionOptionView.swift
|
gpl-3.0
|
1
|
//
// ClassSelectionOptionView.swift
// Habitica
//
// Created by Phillip Thelen on 26.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class ClassSelectionOptionView: UIView {
private let avatarView: AvatarView = {
let avatarView = AvatarView()
avatarView.showBackground = false
avatarView.showPet = false
avatarView.showMount = false
avatarView.size = .compact
return avatarView
}()
private let labelWrapper: UIView = {
let labelWrapper = UIView()
labelWrapper.backgroundColor = UIColor.gray700
labelWrapper.layer.cornerRadius = 4
return labelWrapper
}()
private let iconView = UIImageView()
private let label: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
return label
}()
private var onSelected: (() -> Void)?
var isSelected = false {
didSet {
let newWidth = self.isSelected ? 2 : 0
let widthAnimation = CABasicAnimation(keyPath: "borderWidth")
widthAnimation.fromValue = self.labelWrapper.layer.borderWidth
widthAnimation.toValue = newWidth
widthAnimation.duration = 0.2
self.labelWrapper.layer.borderWidth = CGFloat(newWidth)
self.labelWrapper.layer.add(widthAnimation, forKey: "border width")
}
}
override var tintColor: UIColor! {
didSet {
labelWrapper.layer.borderColor = tintColor.cgColor
label.textColor = tintColor
}
}
var userStyle: UserStyleProtocol? {
didSet {
if let userStyle = self.userStyle {
avatarView.avatar = AvatarViewModel(avatar: userStyle)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
addSubview(avatarView)
addSubview(labelWrapper)
labelWrapper.addSubview(iconView)
labelWrapper.addSubview(label)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTapped)))
isUserInteractionEnabled = true
backgroundColor = .clear
}
override func layoutSubviews() {
super.layoutSubviews()
avatarView.pin.width(76).height(60).top((bounds.size.height-103)/2).hCenter()
labelWrapper.pin.width(116).height(43).hCenter().below(of: avatarView).marginTop(10)
iconView.pin.size(32).vCenter()
label.pin.vertically().sizeToFit(.height)
let labelContentWidth = 32 + 4 + label.bounds.size.width
iconView.pin.left((labelWrapper.bounds.size.width-labelContentWidth)/2)
label.pin.right(of: iconView).marginLeft(4)
}
func configure(habiticaClass: HabiticaClass, onSelected: @escaping (() -> Void)) {
self.onSelected = onSelected
switch habiticaClass {
case .warrior:
iconView.image = HabiticaIcons.imageOfWarriorLightBg
label.text = L10n.Classes.warrior
tintColor = UIColor.red10
case .mage:
iconView.image = HabiticaIcons.imageOfMageLightBg
label.text = L10n.Classes.mage
tintColor = UIColor.blue10
case .healer:
iconView.image = HabiticaIcons.imageOfHealerLightBg
label.text = L10n.Classes.healer
tintColor = UIColor.yellow10
case .rogue:
iconView.image = HabiticaIcons.imageOfRogueLightBg
label.text = L10n.Classes.rogue
tintColor = UIColor.purple300
}
}
@objc
private func onTapped() {
if let action = onSelected {
action()
}
}
}
|
990bcc59072570bcebbb1c60457dc4c1
| 31.186992 | 95 | 0.615307 | false | false | false | false |
CoderXiaoming/Ronaldo
|
refs/heads/master
|
SaleManager/SaleManager/Tools/SAMNetWorker.swift
|
apache-2.0
|
1
|
//
// SAMNetWorker.swift
// SaleManager
//
// Created by apple on 16/11/13.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
import AFNetworking
class SAMNetWorker: AFHTTPSessionManager {
///全局使用的netWorker单例
fileprivate static var netWorker: SAMNetWorker?
//MARK: - 对外提供全局使用的单例的类方法
class func sharedNetWorker() -> SAMNetWorker {
return netWorker!
}
//MARK: - 创建全局使用单例的类方法
class func globalNetWorker(_ baseURLStr: String) -> SAMNetWorker{
if netWorker != nil {
return netWorker!
}else {
let URLStr = String(format: "http://%@", baseURLStr)
let URL = Foundation.URL(string: URLStr)
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 5.0
configuration.timeoutIntervalForRequest = 5.0
netWorker = SAMNetWorker(baseURL: URL!, sessionConfiguration: configuration)
return netWorker!
}
}
///登录界面用的netWorker
fileprivate static var loginNetWorker: SAMNetWorker = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 5.0
configuration.timeoutIntervalForRequest = 5.0
return SAMNetWorker(sessionConfiguration: configuration)
}()
//MARK: - 对外提供登录netWorker单例的类方法
class func sharedLoginNetWorker() -> SAMNetWorker {
return loginNetWorker
}
///全局使用的上传图片netWorker单例
fileprivate static var unloadImageNetWorker: SAMNetWorker?
//MARK: - 对外提供全局使用的上传图片netWorker单例的类方法
class func sharedUnloadImageNetWorker() -> SAMNetWorker {
return unloadImageNetWorker!
}
//MARK: - 创建全局使用上传图片netWorker单例的类方法
class func globalUnloadImageNetWorker(_ baseURLStr: String) -> SAMNetWorker{
if unloadImageNetWorker != nil {
return unloadImageNetWorker!
}else {
let URLStr = String(format: "http://%@", baseURLStr)
let URL = Foundation.URL(string: URLStr)
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 10.0
configuration.timeoutIntervalForRequest = 10.0
unloadImageNetWorker = SAMNetWorker(baseURL: URL!, sessionConfiguration: configuration)
return unloadImageNetWorker!
}
}
}
|
079cc59cd69e32b2bc467f5fbcbfd680
| 32.597222 | 99 | 0.659363 | false | true | false | false |
ben-ng/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/00579-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift
|
apache-2.0
|
1
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func compose<U -> T! {
class A {
}
let d<c: Int {
}
return [B<H : d {
extension NSSet {
}
}
self.c = c() {
}
struct e where H) -> T where g<D> {
class B) {
}
let d.b = c> {
e = {
}
return self.E == b<T> String {
}
}
}
protocol P {
}
struct S {
self.a(f, b in x in x }
func g: AnyObject, f("""
}()
class A : A"
|
32fb01ac0c15607b9d1af1e523639ff1
| 18.666667 | 79 | 0.65113 | false | false | false | false |
codefellows/sea-c47-iOS
|
refs/heads/master
|
Sample Code/ClassRoster/ClassRoster/Person.swift
|
mit
|
1
|
//
// Person.swift
// ClassRoster
//
// Created by Bradley Johnson on 10/1/15.
// Copyright © 2015 Code Fellows. All rights reserved.
//
import UIKit
class Person : NSObject, NSCoding {
var firstName : String
var lastName = "Doe"
var image : UIImage?
init (fName : String, lName : String) {
firstName = fName
lastName = lName
}
required init?(coder aDecoder: NSCoder) {
if let firstName = aDecoder.decodeObjectForKey("firstName") as? String {
self.firstName = firstName
} else {
self.firstName = "NA"
}
if let lastName = aDecoder.decodeObjectForKey("lastName") as? String {
self.lastName = lastName
}
if let image = aDecoder.decodeObjectForKey("image") as? UIImage {
self.image = image
}
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(firstName, forKey: "firstName")
aCoder.encodeObject(lastName, forKey: "lastName")
aCoder.encodeObject(image, forKey: "image")
}
}
|
d1430284028895271acfc948e23b5b9e
| 23.625 | 76 | 0.657868 | false | false | false | false |
rahul-apple/XMPP-Zom_iOS
|
refs/heads/master
|
Zom/Zom/Classes/ZomShareController.swift
|
mpl-2.0
|
1
|
//
// ZomShareController.swift
// Zom
//
// Created by N-Pex on 2016-05-19.
//
//
extension ShareControllerURLSource {
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
// make sure this isn't a subclass
if self !== ShareControllerURLSource.self {
return
}
dispatch_once(&Static.token) {
let originalSelector = #selector(ShareControllerURLSource.activityViewController(_:subjectForActivityType:))
let swizzledSelector = #selector(ShareControllerURLSource.zom_activityViewController(_:subjectForActivityType:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
public func zom_activityViewController(activityViewController: UIActivityViewController, subjectForActivityType activityType: String?) -> String {
let text = NSLocalizedString("Let's Zom!", comment: "String for sharing VROChat link")
return text
}
}
|
2e61bad454033f0667445a7d3d66add7
| 38.390244 | 152 | 0.657585 | false | false | false | false |
NoryCao/zhuishushenqi
|
refs/heads/master
|
zhuishushenqi/Root/ViewModel/ZSDiscussViewModel.swift
|
mit
|
1
|
//
// ZSDiscussViewModel.swift
// zhuishushenqi
//
// Created by caony on 2018/8/21.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
import RxSwift
import MJRefresh
protocol ZSDiscussViewModelProtocol {
var models:[AnyObject] { get set }
var refreshStatus:Variable<ZSRefreshStatus>{ get }
var start:Int { get set }
var limit:Int { get set }
var selectSectionIndexs:[Int] { get set }
func updateSelectSectionIndexs(indexs:[Int])
func fetchDiscuss(_ handler:ZSBaseCallback<Void>?)
func fetchMoreDiscuss(_ handler:ZSBaseCallback<Void>?)
}
extension ZSDiscussViewModelProtocol {
func autoSetRefreshHeaderStatus(header:MJRefreshHeader?,footer:MJRefreshFooter?) -> Disposable{
return refreshStatus.asObservable().subscribe(onNext: { (status) in
switch status {
case .headerRefreshing:
header?.beginRefreshing()
case .headerRefreshEnd:
header?.endRefreshing()
case .footerRefreshing:
footer?.beginRefreshing()
case .footerRefreshEnd:
footer?.endRefreshing()
case .noMoreData:
footer?.endRefreshingWithNoMoreData()
default:
break
}
})
}
}
class ZSDiscussBaseViewModel: NSObject, ZSRefreshProtocol, ZSDiscussViewModelProtocol {
var start: Int = 0
var limit: Int = 20
var selectSectionIndexs: [Int] = []
var block:String = "girl"
internal var refreshStatus: Variable<ZSRefreshStatus> = Variable(.none)
var models: [AnyObject] = []
var webService = ZSDiscussWebService()
func updateSelectSectionIndexs(indexs: [Int]) {
selectSectionIndexs = indexs
}
func fetchDiscuss(_ handler: ZSBaseCallback<Void>?) {
start = 0
let url = getURLString(selectIndexs: selectSectionIndexs)
webService.fetchDiscuss(url: url) { (comments) in
if let cModels = comments {
self.models = cModels
}
self.refreshStatus.value = .headerRefreshEnd
handler?(nil)
}
}
func fetchMoreDiscuss(_ handler: ZSBaseCallback<Void>?) {
start += 20
let url = getURLString(selectIndexs: selectSectionIndexs)
webService.fetchDiscuss(url: url) { (comments) in
if let cModels = comments {
self.models.append(contentsOf: cModels)
}
self.refreshStatus.value = .footerRefreshEnd
handler?(nil)
}
}
func getURLString(selectIndexs:[Int])->String{
// local list
//all ,默认排序
// http://api.zhuishushenqi.com/post/by-block?block=ramble&duration=all&sort=updated&start=0&limit=20
// all,最新发布
// http://api.zhuishushenqi.com/post/by-block?block=ramble&duration=all&sort=created&start=0&limit=20
// all,最多评论
// http://api.zhuishushenqi.com/post/by-block?block=ramble&duration=all&sort=comment-count&start=0&limit=20
// 精品,默认
// http://api.zhuishushenqi.com/post/by-block?block=ramble&distillate=true&duration=all&sort=updated&start=0&limit=20
// 精品,最新发布
// http://api.zhuishushenqi.com/post/by-block?block=ramble&distillate=true&duration=all&sort=created&start=0&limit=20
// 精品,最多评论
// http://api.zhuishushenqi.com/post/by-block?block=ramble&distillate=true&duration=all&sort=comment-count&start=0&limit=20
let durations = ["duration=all","duration=all&distillate=true"]
let sort = ["sort=updated","sort=created","sort=comment-count"]
let urlString = "\(BASEURL)/post/by-block?block=\(block)&\(durations[selectIndexs[0]])&\(sort[selectIndexs[1]])&start=\(start)&limit=\(limit)"
return urlString
}
}
class ZSDiscussViewModel: NSObject,ZSRefreshProtocol {
internal var refreshStatus: Variable<ZSRefreshStatus> = Variable(.none)
var webService = ZSDiscussWebService()
var block:String = "girl"
var models:[BookComment] = []
var start = 0
var limit = 20
func fetchDiscuss(selectIndexs:[Int],completion:@escaping ZSBaseCallback<[BookComment]>){
start = 0
let url = getURLString(selectIndexs: selectIndexs)
webService.fetchDiscuss(url: url) { (comments) in
if let cModels = comments {
self.models = cModels
}
self.refreshStatus.value = .headerRefreshEnd
completion(comments)
}
}
func fetchMore(selectIndexs:[Int],completion:@escaping ZSBaseCallback<[BookComment]>) {
start += 20
let url = getURLString(selectIndexs: selectIndexs)
webService.fetchDiscuss(url: url) { (comments) in
if let cModels = comments {
self.models.append(contentsOf: cModels)
}
self.refreshStatus.value = .footerRefreshEnd
completion(comments)
}
}
func getURLString(selectIndexs:[Int])->String{
// local list
//all ,默认排序
// http://api.zhuishushenqi.com/post/by-block?block=ramble&duration=all&sort=updated&start=0&limit=20
// all,最新发布
// http://api.zhuishushenqi.com/post/by-block?block=ramble&duration=all&sort=created&start=0&limit=20
// all,最多评论
// http://api.zhuishushenqi.com/post/by-block?block=ramble&duration=all&sort=comment-count&start=0&limit=20
// 精品,默认
// http://api.zhuishushenqi.com/post/by-block?block=ramble&distillate=true&duration=all&sort=updated&start=0&limit=20
// 精品,最新发布
// http://api.zhuishushenqi.com/post/by-block?block=ramble&distillate=true&duration=all&sort=created&start=0&limit=20
// 精品,最多评论
// http://api.zhuishushenqi.com/post/by-block?block=ramble&distillate=true&duration=all&sort=comment-count&start=0&limit=20
let durations = ["duration=all","duration=all&distillate=true"]
let sort = ["sort=updated","sort=created","sort=comment-count"]
let urlString = "\(BASEURL)/post/by-block?block=\(block)&\(durations[selectIndexs[0]])&\(sort[selectIndexs[1]])&start=\(start)&limit=\(limit)"
return urlString
}
}
|
68325ebd272e0e40a71912a5c6d79189
| 34.686813 | 150 | 0.609546 | false | false | false | false |
imsz5460/DouYu
|
refs/heads/master
|
DYZB/DYZB/Classes/Main/Model/AnchorGroup.swift
|
mit
|
1
|
//
// AnchorGroup.swift
// DYZB
//
// Created by shizhi on 17/2/28.
// Copyright © 2017年 shizhi. All rights reserved.
//
import UIKit
class AnchorGroup: NSObject {
var room_list: [[String: NSObject]]? {
didSet {
guard let room_list = room_list else {return}
for dict in room_list {
anchors.append(AnchorModel(dict: dict))
}
}
}
/// 组显示的标题
var tag_name: String = ""
/// 组显示的图标
var icon_name: String = "home_header_normal"
/// 游戏对应的图标
var icon_url : String = ""
var anchors: [AnchorModel] = [AnchorModel]()
override init() {
}
init(dict: [String: NSObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
|
68977eeae3d769e822b0f9a0e27f6336
| 20.047619 | 76 | 0.541855 | false | false | false | false |
google/JacquardSDKiOS
|
refs/heads/main
|
JacquardSDK/Classes/Internal/Connection/AdvertisedTagModel.swift
|
apache-2.0
|
1
|
// Copyright 2021 Google LLC
//
// 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 CoreBluetooth
struct AdvertisedTagModel: AdvertisedTag, TagPeripheralAccess {
var pairingSerialNumber: String
var rssi: Float
var peripheral: Peripheral
var identifier: UUID {
return peripheral.identifier
}
init?(peripheral: Peripheral, advertisementData: [String: Any], rssi rssiValue: Float) {
guard let pairingSerialNumber = AdvertisedTagModel.decodeSerialNumber(advertisementData) else {
return nil
}
self.peripheral = peripheral
self.pairingSerialNumber = pairingSerialNumber
self.rssi = rssiValue
}
}
// MARK: Serial number decoding
extension AdvertisedTagModel {
private static func decodeSerialNumber(_ advertisementData: [String: Any]) -> String? {
guard let manufacturerData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data
else {
return nil
}
// New style, it's all serial number all the time, but 6-bit encoding
// First two bytes are the MFG 0xE000 followed by the 6bit encoded ascii string
let sixBitData = manufacturerData.subdata(in: 2..<manufacturerData.count)
return decodeSerialNumber(sixBitData)
}
/// Decode a 6bit encoded serial number.
private static func decodeSerialNumber(_ data: Data) -> String {
// SERIAL NUMBER DECODING
//
// The serial number is encoded using a 6-bit encoding:
// '0'-'9' = 0-9
// 'A'-'Z' = 10-35
// 'a'-'z' = 36-61
// '-' = 62
// (end) = 63
//
// Example encoding of "0GWPw9eQus":
// "0" = 0 = b'000000'
// "G" = 16 = b'010000'
// "W" = 32 = b'100000'
// "P" = 25 = b'011001'
// "w" = 58 = b'111010'
// "9" = 9 = b'001001'
// "e" = 40 = b'101000'
// "Q" = 26 = b'011010'
// "u" = 56 = b'111000'
// "s" = 54 = b'110110'
//
// The bits are then packed into bytes 8 bits at a time. So the first byte has all 6
// bits of the first character (LSB aligned), plus the least significant 2 bits of the
// next character. The second byte has the remaining 4 bits of the 2nd character plus
// the least significant 4 bits of the next.
// Get the raw bytes as type safe UInt8 array
let bytes = [UInt8](data)
let nbytes = data.count
var accumulator: UInt32 = 0 // Accumulator to aggregate multiple bytes' worth of bits.
var bitsLeft = 0 // How many bits of valid data are in the LSB of the accumulator.
var bytesUsed = 0 // How many bytes from the input data have been shifted into
// the accumulator.
let nchars = nbytes * 8 / 6 // It's a 6-bit encoding, so this is how many
// output characters are encoded
var decodedSerialNumber = String()
for _ in 0..<nchars {
//Check if we need to load more bits into the accumulator
if bitsLeft < 6 {
if bytesUsed == nbytes { // Used all the bytes from the input! Finished!
break
}
//Load the next byte in, shifted to the left to avoid bits already in the accumulator
accumulator += UInt32(bytes[bytesUsed]) << bitsLeft
bytesUsed += 1 //Mark one more byte used
bitsLeft += 8 //Mark 8 bits available
}
// 0b00111111 = 0x3F
// Take the lowest 6 bits of the accumulator
var sixBitCode: UInt8 = UInt8(accumulator & 0x3F)
//Decode the encoded character into [0-9A-Za-z-]
if sixBitCode <= 9 {
sixBitCode += 48
} // 0
else if sixBitCode <= 35 {
sixBitCode += 65 - 10
} // A
else if sixBitCode <= 61 {
sixBitCode += 97 - 36
} // a
else if sixBitCode == 62 {
sixBitCode = 45
} // -
else if sixBitCode == 63 {
break
} //End-of-string character
else {
continue
} //Invalid characters are skipped
accumulator >>= 6 //Chop the bits out of the accumulator
bitsLeft -= 6 //Mark those bits as used
//Add it to the output string
decodedSerialNumber.append(String(UnicodeScalar(sixBitCode)))
}
return decodedSerialNumber
}
}
|
27ecdb8a3917c5999d4f0d6f56bde252
| 32.729927 | 99 | 0.640554 | false | false | false | false |
dsmelov/simsim
|
refs/heads/master
|
SimSim/Menus.swift
|
mit
|
1
|
//
// Menus.swift
// SimSim
//
// Created by Daniil Smelov on 13/04/2018.
// Copyright © 2018 Daniil Smelov. All rights reserved.
//
import Foundation
import Cocoa
//============================================================================
class Menus: NSObject
{
private static var realm = Realm()
//----------------------------------------------------------------------------
class func addAction(_ title: String, toSubmenu submenu: NSMenu,
forPath path: String, withIcon iconPath: String,
andHotkey hotkey: NSNumber,
does selector: Selector) -> NSNumber
{
let item = NSMenuItem(title: title, action: selector, keyEquivalent: hotkey.stringValue)
item.target = Actions.self
item.representedObject = path
item.image = NSWorkspace.shared.icon(forFile: iconPath)
item.image?.size = NSMakeSize(CGFloat(Constants.iconSize), CGFloat(Constants.iconSize))
submenu.addItem(item)
return NSNumber(value: hotkey.intValue + 1)
}
//----------------------------------------------------------------------------
class func addAction(_ title: String, toSubmenu submenu: NSMenu,
forPath path: String, withHotkey hotkey: NSNumber,
does selector: Selector) -> NSNumber
{
let item = NSMenuItem(title: title, action: selector, keyEquivalent: hotkey.stringValue)
item.target = Actions.self
item.representedObject = path
submenu.addItem(item)
return NSNumber(value: hotkey.intValue + 1)
}
//----------------------------------------------------------------------------
class func realmModule() -> Realm
{
return realm
}
//----------------------------------------------------------------------------
class func addActionForRealm(to menu: NSMenu, forPath path: String,
withHotkey hotkey: NSNumber) -> NSNumber
{
guard Realm.isRealmAvailable(forPath: path) else
{
return hotkey
}
let icon = NSWorkspace.shared.icon(forFile: Realm.applicationPath())
icon.size = NSMakeSize(CGFloat(Constants.iconSize), CGFloat(Constants.iconSize))
Realm.generateRealmMenu(forPath: path, for: menu, withHotKey: hotkey, icon: icon)
return NSNumber(value: hotkey.intValue + 1)
}
//----------------------------------------------------------------------------
class func addActionForiTerm(to menu: NSMenu, forPath path: String, withHotkey hotkey: NSNumber) -> NSNumber
{
let iTermAppURLs = LSCopyApplicationURLsForBundleIdentifier(Constants.Other.iTermBundle as CFString, nil)
guard iTermAppURLs != nil else {
return hotkey
}
let newkey = addAction(Constants.Actions.iTerm, toSubmenu: menu, forPath: path, withIcon: Constants.Paths.iTermApp,
andHotkey: hotkey, does: #selector(Actions.openIniTerm(_:)))
return NSNumber(value: newkey.intValue + 1)
}
//----------------------------------------------------------------------------
class func addSubMenus(to item: NSMenuItem, usingPath path: String)
{
let subMenu = NSMenu()
var hotkey = NSNumber(value: 1)
hotkey = addAction(Constants.Actions.finder, toSubmenu: subMenu, forPath: path, withIcon: Constants.Paths.finderApp, andHotkey: hotkey, does: #selector(Actions.open(inFinder:)))
hotkey = addAction(Constants.Actions.terminal, toSubmenu: subMenu, forPath: path, withIcon: Constants.Paths.terminalApp, andHotkey: hotkey, does: #selector(Actions.open(inTerminal:)))
hotkey = addActionForRealm(to: subMenu, forPath: path, withHotkey: hotkey)
hotkey = addActionForiTerm(to: subMenu, forPath: path, withHotkey: hotkey)
if Tools.commanderOneAvailable()
{
hotkey = addAction(Constants.Actions.commanderOne, toSubmenu: subMenu, forPath: path, withIcon: Constants.Paths.commanderOneApp, andHotkey: hotkey, does: #selector(Actions.open(inCommanderOne:)))
}
subMenu.addItem(NSMenuItem.separator())
hotkey = addAction(Constants.Actions.clipboard, toSubmenu: subMenu, forPath: path, withHotkey: hotkey, does: #selector(Actions.copy(toPasteboard:)))
hotkey = addAction(Constants.Actions.reset, toSubmenu: subMenu, forPath: path, withHotkey: hotkey, does: #selector(Actions.resetApplication(_:)))
item.submenu = subMenu
}
//----------------------------------------------------------------------------
class func add(_ application: Application, to menu: NSMenu)
{
let title = "\(application.bundleName ?? "nil") \(application.version ?? "nil")"
// This path will be opened on click
let applicationContentPath = application.contentPath
let item = NSMenuItem(title: title, action: #selector(Actions.openIn(withModifier:)), keyEquivalent: "\0")
item.target = Actions.self
item.representedObject = applicationContentPath
item.image = application.icon
self.addSubMenus(to: item, usingPath: applicationContentPath)
menu.addItem(item)
}
//----------------------------------------------------------------------------
class func add(_ applications: [Application], to menu: NSMenu)
{
for application in applications
{
add(application, to: menu)
}
}
//----------------------------------------------------------------------------
class func add(appGroup: AppGroup, to menu: NSMenu)
{
let item = NSMenuItem(title: appGroup.identifier, action: #selector(Actions.openIn(withModifier:)), keyEquivalent: "\0")
item.target = Actions.self
item.representedObject = appGroup.path
self.addSubMenus(to: item, usingPath: appGroup.path)
menu.addItem(item)
}
//----------------------------------------------------------------------------
class func add(appExtension: AppExtension, to menu: NSMenu)
{
let item = NSMenuItem(title: appExtension.identifier, action: #selector(Actions.openIn(withModifier:)), keyEquivalent: "\0")
item.target = Actions.self
item.representedObject = appExtension.path
self.addSubMenus(to: item, usingPath: appExtension.path)
menu.addItem(item)
}
//----------------------------------------------------------------------------
class func addServiceItems(to menu: NSMenu)
{
let startAtLogin = NSMenuItem(title: Constants.Actions.login, action: #selector(Actions.handleStart(atLogin:)), keyEquivalent: "")
startAtLogin.target = Actions.self
let isStartAtLoginEnabled = Settings.isStartAtLoginEnabled
startAtLogin.state = isStartAtLoginEnabled ? .on : .off
startAtLogin.representedObject = isStartAtLoginEnabled
menu.addItem(startAtLogin)
let appVersion = "About \(NSRunningApplication.current.localizedName ?? "") \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "")"
let about = NSMenuItem(title: appVersion, action: #selector(Actions.aboutApp(_:)), keyEquivalent: "I")
about.target = Actions.self
menu.addItem(about)
let quit = NSMenuItem(title: Constants.Actions.quit, action: #selector(Actions.exitApp(_:)), keyEquivalent: "Q")
quit.target = Actions.self
menu.addItem(quit)
}
//----------------------------------------------------------------------------
class func updateApplicationMenu(_ menu: NSMenu, at statusItem: NSStatusItem) -> Void
{
menu.removeAllItems()
let simulators = Tools.activeSimulators()
if simulators.isEmpty
{
let noSimulatorsItem = NSMenuItem(title: "No Simulators", action: nil, keyEquivalent: "")
noSimulatorsItem.isEnabled = false
menu.addItem(noSimulatorsItem)
}
let recentSimulators = simulators
.sorted { $0.date > $1.date }
.prefix(Constants.maxRecentSimulators)
for simulator in recentSimulators
{
let installedApplications = Tools.installedApps(on: simulator)
let sharedAppGroups = Tools.sharedAppGroups(on: simulator)
let appExtensions = Tools.appExtensions(on: simulator)
guard installedApplications.count != 0 else
{
continue
}
let simulatorTitle = simulator.name + " " + simulator.os
let simulatorMenuItem = NSMenuItem(title: simulatorTitle, action: nil, keyEquivalent: "")
simulatorMenuItem.isEnabled = false
menu.addItem(simulatorMenuItem)
add(installedApplications, to: menu)
sharedAppGroups.forEach { add(appGroup: $0, to: menu) }
appExtensions.forEach { add(appExtension: $0, to: menu) }
}
menu.addItem(NSMenuItem.separator())
addServiceItems(to: menu)
}
}
|
dfa8f0fc99b6fc45257d0a87897c10c1
| 36.98374 | 207 | 0.56036 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS
|
refs/heads/master
|
UberGoCore/UberGoCore/MapService.swift
|
mit
|
1
|
//
// Map.swift
// UberGoCore
//
// Created by Nghia Tran on 6/4/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Foundation
import MapKit
import RxCocoa
import RxSwift
protocol MapServiceViewModel {
var input: MapServiceInput { get }
var output: MapServiceOutput { get }
}
protocol MapServiceInput {
}
protocol MapServiceOutput {
var currentLocationVar: Variable<CLLocation?> { get }
var currentPlaceObs: Observable<PlaceObj> { get }
var authorizedDriver: Driver<Bool>! { get }
}
// MARK: - MapService
public final class MapService: NSObject, MapServiceViewModel, MapServiceInput, MapServiceOutput {
// MARK: - Input Output
var input: MapServiceInput { return self }
var output: MapServiceOutput { return self }
// MARK: - Output
public var currentLocationVar = Variable<CLLocation?>(nil)
public var currentPlaceObs: Observable<PlaceObj>
public var authorizedDriver: Driver<Bool>!
// Private
fileprivate lazy var locationManager: CLLocationManager = self.lazyLocationManager()
// MARK: - Init
public override init() {
// Current Place
self.currentPlaceObs = self.currentLocationVar
.asObservable()
.filterNil()
.take(1)
.throttle(5.0, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.flatMapLatest({ MapService.currentPlaceObverser($0) })
super.init()
// Authorize
self.authorizedDriver = Observable
.deferred { [weak self] in
let status = CLLocationManager.authorizationStatus()
guard let `self` = self else { return Observable.empty() }
return self.locationManager
.rx.didChangeAuthorizationStatus
.startWith(status)
}
.asDriver(onErrorJustReturn: CLAuthorizationStatus.notDetermined)
.map {
switch $0 {
case .authorizedAlways:
return true
default:
return false
}
}
}
// MARK: - Public
public func startUpdatingLocation() {
self.locationManager.startUpdatingLocation()
}
public func stopUpdatingLocation() {
self.locationManager.stopUpdatingLocation()
}
fileprivate class func currentPlaceObverser(_ location: CLLocation) -> Observable<PlaceObj> {
let param = PlaceSearchRequestParam(location: location.coordinate)
return PlaceSearchRequest(param)
.toObservable()
.map({ return $0.first })
.filterNil()
}
}
extension MapService {
fileprivate func lazyLocationManager() -> CLLocationManager {
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
return locationManager
}
}
// MARK: - CLLocationManagerDelegate
extension MapService: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
Logger.info("Error \(error)")
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
Logger.info("didChangeAuthorization \(status)")
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let lastLocation = locations.last else { return }
// Notify
self.currentLocationVar.value = lastLocation
}
}
|
dddddf881c085850f59522d83a09f604
| 28.76 | 117 | 0.649194 | false | false | false | false |
josve05a/wikipedia-ios
|
refs/heads/develop
|
Wikipedia/Code/WMFWelcomeIntroductionViewController.swift
|
mit
|
2
|
class WMFWelcomeIntroductionViewController: ThemeableViewController {
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
learnMoreButton.setTitleColor(theme.colors.link, for: .normal)
}
@IBOutlet private var descriptionLabel:UILabel!
@IBOutlet private var learnMoreButton:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
descriptionLabel.text = WMFLocalizedString("welcome-intro-free-encyclopedia-description", value:"Wikipedia is written collaboratively by volunteers and consists of more than 40 million articles in nearly 300 languages.", comment:"Description for introductory welcome screen")
learnMoreButton.setTitle(WMFLocalizedString("welcome-intro-free-encyclopedia-more", value:"Learn more about Wikipedia", comment:"Text for link for learning more about Wikipedia on introductory welcome screen"), for: .normal)
updateFonts()
view.wmf_configureSubviewsForDynamicType()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
learnMoreButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
}
@IBAction func showLearnMoreAlert(withSender sender: AnyObject) {
let alert = UIAlertController(
title:WMFLocalizedString("welcome-intro-free-encyclopedia-more-about", value:"About Wikipedia", comment:"Title for more information about Wikipedia"),
message:"\(WMFLocalizedString("welcome-intro-free-encyclopedia-more-description", value:"Wikipedia is a global project to build free encyclopedias in all languages of the world. Virtually anyone with Internet access is free to participate by contributing neutral, cited information.", comment:"An explanation of how works"))",
preferredStyle:.alert)
alert.addAction(UIAlertAction(title: CommonStrings.gotItButtonTitle, style:.cancel, handler:nil))
present(alert, animated:true, completion:nil)
}
}
|
fec412652734f8a0ce92df07a33ce232
| 52.093023 | 338 | 0.731932 | false | false | false | false |
iOSWizards/AwesomeData
|
refs/heads/master
|
AwesomeData/Classes/Fetcher/AwesomeRequester.swift
|
mit
|
1
|
//
// AwesomeFetcher.swift
// AwesomeData
//
// Created by Evandro Harrison Hoffmann on 6/2/16.
// Copyright © 2016 It's Day Off. All rights reserved.
//
import UIKit
public enum URLMethod: String {
case GET = "GET"
case POST = "POST"
case DELETE = "DELETE"
case PUT = "PUT"
}
open class AwesomeRequester: NSObject {
// MARK:- Where the magic happens
/*
* Fetch data from URL with NSUrlSession
* @param urlString: Url to fetch data form
* @param method: URL method to fetch data using URLMethod enum
* @param headerValues: Any header values to complete the request
* @param shouldCache: Cache fetched data, if on, it will check first for data in cache, then fetch if not found
* @param completion: Returns fetched NSData in a block
*/
open static func performRequest(_ urlString: String?, method: URLMethod? = .GET, bodyData: Data? = nil, headerValues: [[String]]? = nil, shouldCache: Bool = false, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask?{
guard let urlString = urlString else {
completion(nil)
return nil
}
if urlString == "Optional(<null>)" {
completion(nil)
return nil
}
guard let url = URL(string: urlString) else{
completion(nil)
return nil
}
let urlRequest = NSMutableURLRequest(url: url)
//urlRequest.cachePolicy = .ReturnCacheDataElseLoad
// check if file been cached already
if shouldCache {
if let data = AwesomeCacheManager.getCachedObject(urlRequest as URLRequest) {
completion(data)
return nil
}
}
// Continue to URL request
if let method = method {
urlRequest.httpMethod = method.rawValue
}
if let bodyData = bodyData {
urlRequest.httpBody = bodyData
}
if let headerValues = headerValues {
for headerValue in headerValues {
urlRequest.addValue(headerValue[0], forHTTPHeaderField: headerValue[1])
}
}
if timeout > 0 {
urlRequest.timeoutInterval = timeout
}
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { (data, response, error) in
DispatchQueue.main.async(execute: {
if let error = error{
print("There was an error \(error)")
let urlError = error as NSError
if urlError.code == NSURLErrorTimedOut {
onTimeout?()
}else{
completion(nil)
}
}else{
if shouldCache {
AwesomeCacheManager.cacheObject(urlRequest as URLRequest, response: response, data: data)
}
completion(data)
}
})
}
task.resume()
return task
}
}
// MARK: - Custom Calls
extension AwesomeRequester {
/*
* Fetch data from URL with NSUrlSession
* @param urlString: Url to fetch data form
* @param body: adds body to request, can be of any kind
* @param completion: Returns fetched NSData in a block
*/
public static func performRequest(_ urlString: String?, body: String?, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask?{
if let body = body {
return performRequest(urlString, method: nil, bodyData: body.data(using: String.Encoding.utf8), headerValues: nil, shouldCache: false, completion: completion, timeoutAfter: timeout, onTimeout: onTimeout)
}
return performRequest(urlString, method: nil, bodyData: nil, headerValues: nil, shouldCache: false, completion: completion, timeoutAfter: timeout, onTimeout: onTimeout)
}
/*
* Fetch data from URL with NSUrlSession
* @param urlString: Url to fetch data form
* @param method: URL method to fetch data using URLMethod enum
* @param jsonBody: adds json (Dictionary) body to request
* @param completion: Returns fetched NSData in a block
*/
public static func performRequest(_ urlString: String?, method: URLMethod?, jsonBody: [String: AnyObject]?, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask? {
var data: Data?
var headerValues = [[String]]()
if let jsonBody = jsonBody {
do {
try data = JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted)
headerValues.append(["application/json", "Content-Type"])
headerValues.append(["application/json", "Accept"])
} catch{
NSLog("Error unwraping json object")
}
}
return performRequest(urlString, method: method, bodyData: data, headerValues: headerValues, shouldCache: false, completion: completion, timeoutAfter: timeout, onTimeout: onTimeout)
}
/*
* Fetch data from URL with NSUrlSession
* @param urlString: Url to fetch data form
* @param method: URL method to fetch data using URLMethod enum
* @param jsonBody: adds json (Dictionary) body to request
* @param authorization: adds request Authorization token to header
* @param completion: Returns fetched NSData in a block
*/
public static func performRequest(_ urlString: String?, method: URLMethod? = .GET, jsonBody: [String: AnyObject]? = nil, authorization: String, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask? {
return performRequest(
urlString,
method: method,
jsonBody: jsonBody,
headers: ["Authorization": authorization],
completion: completion,
timeoutAfter: timeout,
onTimeout: onTimeout
)
}
/*
* Fetch data from URL with NSUrlSession
* @param urlString: Url to fetch data form
* @param method: URL method to fetch data using URLMethod enum
* @param jsonBody: adds json (Dictionary) body to request
* @param headers: adds headers to the request
* @param timeout: adds the request timeout
* @param completion: Returns fetched NSData in a block
*/
public static func performRequest(_ urlString: String?, method: URLMethod? = .GET, jsonBody: [String: AnyObject]? = nil, headers: [String: String], completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask? {
var data: Data?
var headerValues = [[String]]()
if let jsonBody = jsonBody {
do {
try data = JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted)
headerValues.append(["application/json", "Content-Type"])
headerValues.append(["application/json", "Accept"])
} catch{
NSLog("Error unwraping json object")
}
}
for (key, value) in headers {
headerValues.append([value, key])
}
return performRequest(
urlString,
method: method,
bodyData: data,
headerValues: headerValues,
shouldCache: false,
completion: completion,
timeoutAfter: timeout,
onTimeout: onTimeout
)
}
}
|
092842774277164ab304043aba41ca2a
| 38.487685 | 307 | 0.584955 | false | false | false | false |
borglab/SwiftFusion
|
refs/heads/main
|
Sources/SwiftFusion/Core/DataTypes.swift
|
apache-2.0
|
1
|
import _Differentiation
extension Vector5: ManifoldCoordinate {
/// The local coordinate type of the manifold.
///
/// This is the `TangentVector` of the `Manifold` wrapper type.
///
/// Note that this is not the same type as `Self.TangentVector`.
public typealias LocalCoordinate = Self
/// Diffeomorphism between a neigborhood of `LocalCoordinate.zero` and `Self`.
///
/// Satisfies the following properties:
/// - `retract(LocalCoordinate.zero) == self`
/// - There exists an open set `B` around `LocalCoordinate.zero` such that
/// `localCoordinate(retract(b)) == b` for all `b \in B`.
@differentiable(wrt: local)
public func retract(_ local: LocalCoordinate) -> Self {
self + local
}
/// Inverse of `retract`.
///
/// Satisfies the following properties:
/// - `localCoordinate(self) == LocalCoordinate.zero`
/// - There exists an open set `B` around `self` such that `localCoordinate(retract(b)) == b` for all
/// `b \in B`.
@differentiable(wrt: global)
public func localCoordinate(_ global: Self) -> LocalCoordinate {
global - self
}
}
extension Vector5: Manifold {
/// The manifold's global coordinate system.
public typealias Coordinate = Self
/// The coordinate of `self`.
///
/// Note: The distinction between `coordinateStorage` and `coordinate` is a workaround until we
/// can define default derivatives for protocol requirements (TF-982). Until then, implementers
/// of this protocol must define `coordinateStorage`, and clients of this protocol must access
/// coordinate`. This allows us to define default derivatives for `coordinate` that translate
/// between the `ManifoldCoordinate` tangent space and the `Manifold` tangent space.
public var coordinateStorage: Coordinate {
get {
self
}
set {
self = newValue
}
}
/// Creates a manifold point with coordinate `coordinateStorage`.
///
/// Note: The distinction between `init(coordinateStorage:)` and `init(coordinate:)` is a workaround until we
/// can define default derivatives for protocol requirements (TF-982). Until then, implementers
/// of this protocol must define `init(coordinateStorage:)`, and clients of this protocol must access
/// init(coordinate:)`. This allows us to define default derivatives for `init(coordinate:)` that translate
/// between the `ManifoldCoordinate` tangent space and the `Manifold` tangent space.
public init(coordinateStorage: Coordinate) {
self = coordinateStorage
}
}
extension Vector5: LieGroupCoordinate {
/// Creates the group identity.
public init() {
self = Self.zero
}
/// Returns the group inverse.
@differentiable(wrt: self)
public func inverse() -> Self {
-self
}
@differentiable(wrt: v)
public func Adjoint(_ v: LocalCoordinate) -> LocalCoordinate {
defaultAdjoint(v)
}
/// The group operation.
@differentiable(wrt: (lhs, rhs))
public static func * (_ lhs: Self, _ rhs: Self) -> Self {
lhs + rhs
}
public func AdjointTranspose(_ v: LocalCoordinate) -> LocalCoordinate {
return defaultAdjointTranspose(v)
}
}
extension Vector5: LieGroup {}
extension Vector7: ManifoldCoordinate {
public typealias LocalCoordinate = Self
@differentiable(wrt: local)
public func retract(_ local: LocalCoordinate) -> Self {
self + local
}
@differentiable(wrt: global)
public func localCoordinate(_ global: Self) -> LocalCoordinate {
global - self
}
}
extension Vector7: Manifold {
/// The manifold's global coordinate system.
public typealias Coordinate = Self
public var coordinateStorage: Coordinate {
get {
self
}
set {
self = newValue
}
}
/// Creates a manifold point with coordinate `coordinateStorage`.
public init(coordinateStorage: Coordinate) {
self = coordinateStorage
}
}
extension Vector7: LieGroupCoordinate {
/// Creates the group identity.
public init() {
self = Self.zero
}
/// Returns the group inverse.
@differentiable
public func inverse() -> Self {
-self
}
/// The group operation.
@differentiable
public static func * (_ lhs: Self, _ rhs: Self) -> Self {
lhs + rhs
}
public func AdjointTranspose(_ v: LocalCoordinate) -> LocalCoordinate {
return defaultAdjointTranspose(v)
}
}
extension Vector7: LieGroup {}
// -------------------------------------------------------------
/// MARK: Vector10
extension Vector10: ManifoldCoordinate {
public typealias LocalCoordinate = Self
@differentiable(wrt: local)
public func retract(_ local: LocalCoordinate) -> Self {
self + local
}
@differentiable(wrt: global)
public func localCoordinate(_ global: Self) -> LocalCoordinate {
global - self
}
}
extension Vector10: Manifold {
/// The manifold's global coordinate system.
public typealias Coordinate = Self
public var coordinateStorage: Coordinate {
get {
self
}
set {
self = newValue
}
}
/// Creates a manifold point with coordinate `coordinateStorage`.
public init(coordinateStorage: Coordinate) {
self = coordinateStorage
}
}
extension Vector10: LieGroupCoordinate {
/// Creates the group identity.
public init() {
self = Self.zero
}
/// Returns the group inverse.
@differentiable
public func inverse() -> Self {
-self
}
/// The group operation.
@differentiable
public static func * (_ lhs: Self, _ rhs: Self) -> Self {
lhs + rhs
}
public func AdjointTranspose(_ v: LocalCoordinate) -> LocalCoordinate {
return defaultAdjointTranspose(v)
}
}
extension Vector10: LieGroup {}
|
f23f5b9d9a0c3565b2047856fbf36752
| 25.055556 | 111 | 0.675373 | false | true | false | false |
CosmicMind/Samples
|
refs/heads/development
|
Projects/Programmatic/TabBar/TabBar/ViewController.swift
|
bsd-3-clause
|
1
|
/*
* 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
class ViewController: UIViewController {
fileprivate var buttons = [TabItem]()
fileprivate var tabBar: TabBar!
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
prepareButtons()
prepareTabBar()
}
}
extension ViewController {
fileprivate func prepareButtons() {
let btn1 = TabItem(title: "Library", titleColor: Color.blueGrey.base)
btn1.pulseAnimation = .none
buttons.append(btn1)
let btn2 = TabItem(title: "Photo", titleColor: Color.blueGrey.base)
btn2.pulseAnimation = .none
buttons.append(btn2)
let btn3 = TabItem(title: "Video", titleColor: Color.blueGrey.base)
btn3.pulseAnimation = .none
buttons.append(btn3)
}
fileprivate func prepareTabBar() {
tabBar = TabBar()
tabBar.delegate = self
tabBar.dividerColor = Color.grey.lighten2
tabBar.dividerAlignment = .top
tabBar.lineColor = Color.blue.base
tabBar.lineAlignment = .top
tabBar.backgroundColor = Color.grey.lighten5
tabBar.tabItems = buttons
view.layout(tabBar).horizontally().bottom()
}
}
extension ViewController: TabBarDelegate {
@objc
func tabBar(tabBar: TabBar, willSelect tabItem: TabItem) {
print("will select")
}
@objc
func tabBar(tabBar: TabBar, didSelect tabItem: TabItem) {
print("did select")
}
}
|
76ba95e058f648fcd2deae0923a959b4
| 34.244444 | 88 | 0.692308 | false | false | false | false |
zqqf16/SYM
|
refs/heads/master
|
SYM/MdfindWrapper.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2017 - present zqqf16
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
protocol MdfindWrapperDelegate: AnyObject {
func mdfindWrapper(_ wrapper: MdfindWrapper, didFindResult result: [NSMetadataItem]?)
}
class MdfindWrapper {
let query = NSMetadataQuery()
weak var delegate: MdfindWrapperDelegate?
init() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(handleResult(_:)), name: .NSMetadataQueryDidFinishGathering, object: nil)
nc.addObserver(self, selector: #selector(handleResult(_:)), name: .NSMetadataQueryDidUpdate, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func start(withCondition condition: String) {
stop()
query.predicate = NSPredicate(fromMetadataQueryString: condition)
query.start()
}
func stop() {
query.stop()
}
@objc func handleResult(_ notification: NSNotification) {
if let query = notification.object as? NSMetadataQuery, query == self.query {
delegate?.mdfindWrapper(self, didFindResult: query.results as? [NSMetadataItem])
}
}
}
|
12e24ff6562c80ff60ddc377addacd37
| 37.186441 | 122 | 0.719929 | false | false | false | false |
dcunited001/SpectraNu
|
refs/heads/master
|
Spectra/SpectraXML/XSD.swift
|
mit
|
1
|
//
// XSD.swift
//
//
// Created by David Conner on 3/9/16.
//
//
import Foundation
import Fuzi
import Swinject
public class SpectraEnum {
let name: String
var values: [String: UInt]
public init(elem: XMLElement) {
values = [:]
name = elem.attributes["name"]!
let valuesSelector = "xs:restriction > xs:enumeration"
for child in elem.css(valuesSelector) {
let val = child.attributes["id"]!
let key = child.attributes["value"]!
self.values[key] = UInt(val)
}
}
public func getValue(id: String) -> UInt {
return values[id]!
}
}
// TODO: is there struct value that makes sense here?
// - so, like a single struct value that can be used in case statements
// - but also carries a bit of info about the params of each type?
public enum SpectraVertexAttrType: String {
// raw values for enums must be literals,
// - so i can't use the MDLVertexAttribute string values
case Anisotropy = "anisotropy"
case Binormal = "binormal"
case Bitangent = "bitangent"
case Color = "color"
case EdgeCrease = "edgeCrease"
case JointIndices = "jointIndices"
case JointWeights = "jointWeights"
case Normal = "normal"
case OcclusionValue = "occlusionValue"
case Position = "position"
case ShadingBasisU = "shadingBasisU"
case ShadingBasisV = "shadingBasisV"
case SubdivisionStencil = "subdivisionStencil"
case Tangent = "tangent"
case TextureCoordinate = "textureCoordinate"
// can't add this to the SpectraEnums.xsd schema,
// - at least not directly, since it's not an enum
}
public class SpectraXSD {
public class func readXSD(filename: String) -> XMLDocument? {
let bundle = NSBundle(forClass: MetalXSD.self)
let path = bundle.pathForResource(filename, ofType: "xsd")
let data = NSData(contentsOfFile: path!)
do {
return try XMLDocument(data: data!)
} catch let err as XMLError {
switch err {
case .ParserFailure, .InvalidData: print(err)
case .LibXMLError(let code, let message): print("libxml error code: \(code), message: \(message)")
default: break
}
} catch let err {
print("error: \(err)")
}
return nil
}
public func parseXSD(xsd: XMLDocument, container: Container = Container()) -> Container {
let enumTypesSelector = "xs:simpleType[mtl-enum=true]"
for enumChild in xsd.css(enumTypesSelector) {
let enumType = SpectraEnum(elem: enumChild)
container.register(SpectraEnum.self, name: enumType.name) { _ in
return enumType
}
}
return container
}
}
|
708c9eaabbce36533df181dff009fdbf
| 29.703297 | 110 | 0.619048 | false | false | false | false |
lojals/semanasanta
|
refs/heads/master
|
Semana Santa/Semana Santa/Classes/Gradient.swift
|
gpl-2.0
|
1
|
//
// Shadow.swift
// Yo Intervengo
//
// Created by Jorge Raul Ovalle Zuleta on 1/18/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import Foundation
import UIKit
class Gradient: UIView{
let colorTop = UIColor.whiteColor().colorWithAlphaComponent(0.7).CGColor
let colorBottom = UIColor.whiteColor().colorWithAlphaComponent(0).CGColor
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(frame: CGRect, type: String = "Top") {
super.init(frame: frame)
let mapGrad = CAGradientLayer()
mapGrad.colors = ((type == "Top") ? [colorTop,colorBottom] : [colorBottom,colorTop])
mapGrad.locations = [0,1]
switch type{
case "Left":
mapGrad.colors = [colorTop,colorBottom]
mapGrad.startPoint = CGPointMake(0.0, 0.5)
mapGrad.endPoint = CGPointMake(1.0, 0.5)
case "Right":
mapGrad.colors = [colorBottom,colorTop]
mapGrad.startPoint = CGPointMake(0.0, 0.5)
mapGrad.endPoint = CGPointMake(1.0, 0.5)
default:
mapGrad.colors = ((type == "Top") ? [colorTop,colorBottom] : [colorBottom,colorTop])
}
mapGrad.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
self.layer.insertSublayer(mapGrad, atIndex: 0)
self.userInteractionEnabled = false
}
}
|
a5d2fec5d12e87fb7114e76bed3d2c2e
| 31.733333 | 100 | 0.598505 | false | false | false | false |
edx/edx-app-ios
|
refs/heads/master
|
Source/Deep Linking/DeepLink.swift
|
apache-2.0
|
1
|
//
// DeepLink.swift
// edX
//
// Created by Salman on 02/10/2018.
// Copyright © 2018 edX. All rights reserved.
//
import UIKit
enum DeepLinkType: String {
case courseDashboard = "course_dashboard"
case courseVideos = "course_videos"
case discussions = "course_discussion"
case courseDates = "course_dates"
case courseHandout = "course_handout"
case courseComponent = "course_component"
case courseAnnouncement = "course_announcement"
case discussionTopic = "discussion_topic"
case discussionPost = "discussion_post"
case discussionComment = "discussion_comment"
case courseDiscovery = "course_discovery"
case programDiscovery = "program_discovery"
case programDiscoveryDetail = "program_discovery_detail"
case degreeDiscovery = "degree_discovery"
case degreeDiscoveryDetail = "degree_discovery_detail"
case courseDetail = "course_detail"
case program = "program"
case programDetail = "program_detail"
case userProfile = "user_profile"
case profile = "profile"
case none = "none"
}
enum DeepLinkKeys: String, RawStringExtractable {
case courseId = "course_id"
case pathID = "path_id"
case screenName = "screen_name"
case topicID = "topic_id"
case threadID = "thread_id"
case commentID = "comment_id"
case componentID = "component_id"
}
class DeepLink: NSObject {
let courseId: String?
let screenName: String?
let pathID: String?
let topicID: String?
let threadID: String?
let commentID: String?
let componentID: String?
var type: DeepLinkType {
let type = DeepLinkType(rawValue: screenName ?? DeepLinkType.none.rawValue) ?? .none
if type == .courseDiscovery && courseId != nil {
return .courseDetail
}
else if type == .programDiscovery && pathID != nil {
return .programDiscoveryDetail
}
else if type == .program && pathID != nil {
return .programDetail
}
else if type == .degreeDiscovery && pathID != nil {
return .degreeDiscoveryDetail
}
return type
}
init(dictionary: [String : Any]) {
courseId = dictionary[DeepLinkKeys.courseId] as? String
screenName = dictionary[DeepLinkKeys.screenName] as? String
pathID = dictionary[DeepLinkKeys.pathID] as? String
topicID = dictionary[DeepLinkKeys.topicID] as? String
threadID = dictionary[DeepLinkKeys.threadID] as? String
commentID = dictionary[DeepLinkKeys.commentID] as? String
componentID = dictionary[DeepLinkKeys.componentID] as? String
}
}
|
cdc7e319c96593329b15dfab72f0ba4c
| 32.125 | 92 | 0.663774 | false | false | false | false |
tylow/surftranslate
|
refs/heads/master
|
SURF_Translate/Card.swift
|
agpl-3.0
|
1
|
//
// Card.swift
// SURF_Translate
//
// Created by Legeng Liu on 6/1/16.
// Copyright © 2016 SURF. All rights reserved.
//
import UIKit
class Card/* :NSObject, NSCoding*/{
//MARK: properties
//phrases, recordings, languages etc.
var firstPhrase: String
var secondPhrase: String
//For the Most Used sorting function. Increment every time user taps the Sound Button
var numTimesUsed: Int
/*
//persistent data
struct PropertyKey{
static let firstPhraseKey = "first"
static let secondPhraseKey = "second"
static let numUsedKey = "numTimes"
}
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("cards")
*/
//Init
init?(firstPhrase:String, secondPhrase:String, numTimesUsed:Int){
self.firstPhrase = firstPhrase
self.secondPhrase = secondPhrase
self.numTimesUsed = numTimesUsed
//super.init()
if firstPhrase.isEmpty && secondPhrase.isEmpty{
return nil
}
}
/*
//MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(firstPhrase, forKey: PropertyKey.firstPhraseKey)
aCoder.encodeObject(secondPhrase, forKey: PropertyKey.secondPhraseKey)
aCoder.encodeInteger(numTimesUsed, forKey: PropertyKey.numUsedKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let firstPhrase = aDecoder.decodeObjectForKey(PropertyKey.firstPhraseKey) as! String
let secondPhrase = aDecoder.decodeObjectForKey(PropertyKey.secondPhraseKey) as! String
let numTimesUsed = aDecoder.decodeIntegerForKey(PropertyKey.numUsedKey)
// Must call designated initializer.
self.init(firstPhrase: firstPhrase, secondPhrase: secondPhrase, numTimesUsed: numTimesUsed)
}
*/
}
|
3e84ca2d86e14150742ba57680efb675
| 28.73913 | 123 | 0.669103 | false | false | false | false |
Weswit/Lightstreamer-example-StockList-client-ios
|
refs/heads/master
|
Shared/Constants.swift
|
apache-2.0
|
1
|
// Converted to Swift 5.4 by Swiftify v5.4.24488 - https://swiftify.com/
/*
* Constants.swift
* StockList Demo for iOS
*
* Copyright (c) Lightstreamer Srl
*
* 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
#if DEBUG
// Configuration for local installation
let PUSH_SERVER_URL = "http://localhost:8080/"
let ADAPTER_SET = "STOCKLISTDEMO"
let DATA_ADAPTER = "STOCKLIST_ADAPTER"
// Configuration for online demo server
//let PUSH_SERVER_URL = "https://push.lightstreamer.com"
//let ADAPTER_SET = "DEMO"
//let DATA_ADAPTER = "QUOTE_ADAPTER"
#else
let PUSH_SERVER_URL = "https://push.lightstreamer.com"
let ADAPTER_SET = "DEMO"
let DATA_ADAPTER = "QUOTE_ADAPTER"
#endif
#if os(iOS)
let DEVICE_IPAD = UIDevice.current.userInterfaceIdiom == .pad
func DEVICE_XIB(_ xib: String) -> String {
DEVICE_IPAD ? xib + "_iPad" : xib + "_iPhone"
}
#endif
let NUMBER_OF_ITEMS = 30
let NUMBER_OF_LIST_FIELDS = 4
let NUMBER_OF_DETAIL_FIELDS = 11
let TABLE_ITEMS = ["item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10", "item11", "item12", "item13", "item14", "item15", "item16", "item17", "item18", "item19", "item20", "item21", "item22", "item23", "item24", "item25", "item26", "item27", "item28", "item29", "item30"]
let LIST_FIELDS = ["last_price", "time", "pct_change", "stock_name"]
let DETAIL_FIELDS = ["last_price", "time", "pct_change", "bid_quantity", "bid", "ask", "ask_quantity", "min", "max", "open_price", "stock_name"]
let NOTIFICATION_CONN_STATUS = NSNotification.Name("LSConnectionStatusChanged")
let NOTIFICATION_CONN_ENDED = NSNotification.Name("LSConnectionEnded")
let ALERT_DELAY = 0.250
let FLASH_DURATION = 0.150
let GREEN_COLOR = UIColor(red: 0.5647, green: 0.9294, blue: 0.5373, alpha: 1.0)
let ORANGE_COLOR = UIColor(red: 0.9843, green: 0.7216, blue: 0.4510, alpha: 1.0)
let DARK_GREEN_COLOR = UIColor(red: 0.0000, green: 0.6000, blue: 0.2000, alpha: 1.0)
let RED_COLOR = UIColor(red: 1.0000, green: 0.0706, blue: 0.0000, alpha: 1.0)
let LIGHT_ROW_COLOR = UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0)
let DARK_ROW_COLOR = UIColor(red: 0.8667, green: 0.8667, blue: 0.9373, alpha: 1.0)
let SELECTED_ROW_COLOR = UIColor(red: 0.0000, green: 0.0000, blue: 1.0000, alpha: 1.0)
let DEFAULT_TEXT_COLOR = UIColor(red: 0.0000, green: 0.0000, blue: 0.0000, alpha: 1.0)
let SELECTED_TEXT_COLOR = UIColor(red: 1.0000, green: 1.0000, blue: 1.0000, alpha: 1.0)
let COLORED_LABEL_TAG = 456
let FLIP_DURATION = 0.3
let INFO_IPAD_WIDTH = 600.0
let INFO_IPAD_HEIGHT = 400.0
let STATUS_IPAD_WIDTH = 400.0
let STATUS_IPAD_HEIGHT = 230.0
|
5b02858c97b59b35f128997971049e8a
| 36.190476 | 309 | 0.695903 | false | false | false | false |
google/open-location-code-swift
|
refs/heads/master
|
Tests/OpenLocationCodeTests/OpenLocationCodeCoreTests.swift
|
apache-2.0
|
1
|
//===-- OpenLocationCodeTests.swift - Tests for OpenLocationCode.swift ----===//
//
// Copyright 2017 Google 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.
//
//===----------------------------------------------------------------------===//
//
// Unit tests for core functionality using the official CSV test data.
//
// Authored by William Denniss. Ported from openlocationcode_test.py.
//
//===----------------------------------------------------------------------===//
import XCTest
import Foundation
@testable import OpenLocationCode
/// OLC Test helpers.
class OLCTestHelper {
/// Loads CSV data from the test bundle and parses into an Array of
/// Dictionaries using the given keys.
///
/// - Parameter filename: the filename of the CSV file with no path or
/// extension component
/// - Parameter keys: the keys used to build the dictionary.
/// - Returns: An array of each line of data represented as a dictionary
/// with the given keys.
static func loadData(filename: String,
keys: Array<String>)
-> Array<Dictionary<String, String>>? {
var testData:Array<Dictionary<String, String>> = []
var csvData: String?
// Tries to load CSV data from bundle.
#if !os(Linux)
let testBundle = Bundle(for: OLCTestHelper.self)
if let path = testBundle.path(forResource: filename, ofType: "csv") {
csvData = try? String(contentsOfFile: path)
}
#endif
// Falls back to loading directly from the file.
if csvData == nil {
csvData = try? String(contentsOfFile: "test_data/\(filename).csv",
encoding: .utf8)
}
// Parses data.
guard let csv = csvData else {
print("Unable to read \(filename).csv")
XCTAssert(false)
return nil
}
// Iterates each line.
for(line) in csv.components(separatedBy: CharacterSet.newlines) {
if line.hasPrefix("#") || line.count == 0 {
continue
}
// Parses as a comma separated array.
let lineData =
line.components(separatedBy: CharacterSet.init(charactersIn: ","))
// Converts to dict.
var lineDict:Dictionary<String, String> = [:]
for i in 0 ..< keys.count {
lineDict[keys[i]] = lineData[i]
}
testData += [lineDict]
}
return testData
}
}
/// Tests the validity methods.
class ValidityTests: XCTestCase {
var testData:Array<Dictionary<String, String>> = []
override func setUp() {
super.setUp()
let keys = ["code","isValid","isShort","isFull"]
testData = OLCTestHelper.loadData(filename: "validityTests", keys: keys)!
XCTAssertNotNil(testData)
XCTAssert(testData.count > 0)
}
/// Tests OpenLocationCode.isValid
func testValidCodes() {
for(td) in testData {
XCTAssertEqual(OpenLocationCode.isValid(code: td["code"]!),
Bool(td["isValid"]!)!)
}
}
/// Tests OpenLocationCode.isFull
func testFullCodes() {
for(td) in testData {
XCTAssertEqual(OpenLocationCode.isFull(code: td["code"]!),
Bool(td["isFull"]!)!)
}
}
/// Tests OpenLocationCode.isShort
func testShortCodes() {
for(td) in testData {
XCTAssertEqual(OpenLocationCode.isShort(code: td["code"]!),
Bool(td["isShort"]!)!)
}
}
static var allTests = [
("testValidCodes", testValidCodes),
("testFullCodes", testFullCodes),
("testShortCodes", testShortCodes),
]
}
/// Tests the code shortening methods.
class ShortenTests: XCTestCase {
var testData:Array<Dictionary<String, String>> = []
override func setUp() {
super.setUp()
let keys = ["code","lat","lng","shortcode", "testtype"]
testData = OLCTestHelper.loadData(filename: "shortCodeTests", keys: keys)!
XCTAssertNotNil(testData)
XCTAssert(testData.count > 0)
}
/// Tests OpenLocationCode.shorten
func testFullToShort() {
for(td) in testData {
if td["testtype"] == "B" || td["testtype"] == "S" {
let shortened = OpenLocationCode.shorten(code: td["code"]!,
latitude: Double(td["lat"]!)!,
longitude: Double(td["lng"]!)!,
maximumTruncation: 8)!
XCTAssertEqual(shortened, td["shortcode"]!)
}
if td["testtype"] == "B" || td["testtype"] == "R" {
let recovered =
OpenLocationCode.recoverNearest(shortcode: td["shortcode"]!,
referenceLatitude: Double(td["lat"]!)!,
referenceLongitude: Double(td["lng"]!)!)
XCTAssertEqual(recovered, td["code"]!)
}
}
}
static var allTests = [
("testFullToShort", testFullToShort),
]
}
/// Tests encoding.
class EncodingTests: XCTestCase {
var testData:Array<Dictionary<String, String>> = []
override func setUp() {
super.setUp()
let keys = ["lat","lng","length","code"]
testData = OLCTestHelper.loadData(filename: "encoding", keys: keys)!
XCTAssertNotNil(testData)
XCTAssert(testData.count > 0)
}
/// Tests OpenLocationCode.encode
func testEncoding() {
for(td) in testData {
let encoded = OpenLocationCode.encode(latitude: Double(td["lat"]!)!,
longitude: Double(td["lng"]!)!,
codeLength: Int(td["length"]!)!)
let code = td["code"]!
XCTAssertEqual(encoded, code)
}
}
static var allTests = [
("testEncoding", testEncoding),
]
}
/// Tests decoding.
class DecodingTests: XCTestCase {
var testData:Array<Dictionary<String, String>> = []
override func setUp() {
super.setUp()
let keys = ["code","length","latLo","lngLo","latHi","lngHi"]
testData = OLCTestHelper.loadData(filename: "decoding", keys: keys)!
XCTAssertNotNil(testData)
XCTAssert(testData.count > 0)
}
/// Tests OpenLocationCode.decode
func testDecoding() {
let precision = pow(10.0,10.0)
for(td) in testData {
let decoded: OpenLocationCodeArea =
OpenLocationCode.decode(td["code"]!)!
XCTAssertEqual((decoded.latitudeLo * precision).rounded(),
(Double(td["latLo"]!)! * precision).rounded(),
"Failure with " + td["code"]!)
XCTAssertEqual((decoded.longitudeLo * precision).rounded(),
(Double(td["lngLo"]!)! * precision).rounded(),
"Failure with " + td["code"]!)
XCTAssertEqual((decoded.latitudeHi * precision).rounded(),
(Double(td["latHi"]!)! * precision).rounded(),
"Failure with " + td["code"]!)
XCTAssertEqual((decoded.longitudeHi * precision).rounded(),
(Double(td["lngHi"]!)! * precision).rounded(),
"Failure with " + td["code"]!)
}
}
static var allTests = [
("testDecoding", testDecoding),
]
}
|
e03ad18a1bdf16ec5adbf3bd9497a15a
| 32.026432 | 80 | 0.589114 | false | true | false | false |
FreddyZeng/Charts
|
refs/heads/master
|
Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift
|
apache-2.0
|
1
|
//
// BarChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet
{
private func initialize()
{
self.highlightColor = NSUIColor.black
self.calcStackSize(entries: values as! [BarChartDataEntry])
self.calcEntryCountIncludingStacks(entries: values as! [BarChartDataEntry])
}
public required init()
{
super.init()
initialize()
}
public override init(values: [ChartDataEntry]?, label: String?)
{
super.init(values: values, label: label)
initialize()
}
// MARK: - Data functions and accessors
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(entries: [BarChartDataEntry])
{
_entryCountStacks = 0
for i in 0 ..< entries.count
{
if let vals = entries[i].yValues
{
_entryCountStacks += vals.count
}
else
{
_entryCountStacks += 1
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(entries: [BarChartDataEntry])
{
for i in 0 ..< entries.count
{
if let vals = entries[i].yValues
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
open override func calcMinMax(entry e: ChartDataEntry)
{
guard let e = e as? BarChartDataEntry
else { return }
if !e.y.isNaN
{
if e.yValues == nil
{
if e.y < _yMin
{
_yMin = e.y
}
if e.y > _yMax
{
_yMax = e.y
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
calcMinMaxX(entry: e)
}
}
/// - returns: The maximum number of bars that can be stacked upon another in this DataSet.
open var stackSize: Int
{
return _stackSize
}
/// - returns: `true` if this DataSet is stacked (stacksize > 1) or not.
open var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// - returns: The overall entry count, including counting each stack-value individually
@objc open var entryCountStacks: Int
{
return _entryCountStacks
}
/// array of labels used to describe the different values of the stacked bars
open var stackLabels: [String] = ["Stack"]
/// 柱状图圆角类型
public var barCornerType:IBarChartType = .square
// MARK: - Styling functions and accessors
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// 柱状图背景是否圆角
public var barShadowType: IBarChartShadowType = .square
/// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn.
open var barBorderWidth : CGFloat = 0.0
/// the color drawing borders around the bars.
open var barBorderColor = NSUIColor.black
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
open var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BarChartDataSet
copy._stackSize = _stackSize
copy._entryCountStacks = _entryCountStacks
copy.stackLabels = stackLabels
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
|
5da47798245b1a5ca0295e19052a42a0
| 28.040936 | 148 | 0.566251 | false | false | false | false |
WickedColdfront/Slide-iOS
|
refs/heads/master
|
Slide for Reddit/LeftTransition.swift
|
apache-2.0
|
1
|
//
// LeftTransition.swift
// Slide for Reddit
//
// Created by Carlos Crane on 8/3/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
// Code based on https://stackoverflow.com/a/33960412/3697225
import UIKit
class LeftTransition: NSObject ,UIViewControllerAnimatedTransitioning {
var dismiss = false
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
// Get the two view controllers
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let containerView = transitionContext.containerView
var originRect = containerView.bounds
originRect.origin = CGPoint.init(x: (originRect).width, y:0)
containerView.addSubview(fromVC.view)
containerView.addSubview(toVC.view)
if dismiss{
containerView.bringSubview(toFront: fromVC.view)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
fromVC.view.frame = originRect
}, completion: { (_ ) -> Void in
fromVC.view.removeFromSuperview()
transitionContext.completeTransition(true )
})
}else{
toVC.view.frame = originRect
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: { () -> Void in
toVC.view.center = containerView.center
}) { (_) -> Void in
fromVC.view.removeFromSuperview()
transitionContext.completeTransition(true )
}
}
}
}
|
d143409e9a7e86bb8dc9a209995c072f
| 37.019231 | 114 | 0.632777 | false | false | false | false |
rahulsend89/MemoryGame
|
refs/heads/master
|
MemoryGameTests/MockHelper.swift
|
mit
|
1
|
//
// RuntimeHelper.swift
// HealthConnect
//
// Created by Rahul Malik on 16/01/16.
// Copyright © 2016 citiustech. All rights reserved.
//
import Foundation
import ObjectiveC.runtime
typealias closureAny = () -> Any?
typealias closureVoid = () -> Void
protocol TestableClass: class {
func ifOverride<T: Any>(_ functionName: String, funcCall: () -> T) -> T
}
extension TestableClass {
func callFunction(_ functionName: String = #function, funcCall: closureVoid)->Any? {
let returnVal: (Bool, Any?) = MockHelper.functionIsGettingCalled(functionName)
if !returnVal.0 {
funcCall()
}
return returnVal.1
}
func ifOverride<T: Any>(_ functionName: String = #function, funcCall: () -> T) -> T {
var parentReturnValue: T?
if let overrideReturnVal = (callFunction(functionName) { _ in
parentReturnValue = funcCall()
}) as? T {
return overrideReturnVal
}
return parentReturnValue!
}
}
open class MockActionable {
var actions = [closureAny]()
init(_ funcBlock: @escaping closureAny) {
addAction(funcBlock)
}
func andDo(_ closure: @escaping closureVoid) -> MockActionable {
addAction({ closure() })
return self
}
func addAction(_ action: @escaping closureAny) {
actions.append(action)
}
func performActions() -> Any? {
var returnValue: Any?
for (i, action) in actions.enumerated() {
if i == 0 {
returnValue = action()
} else {
action()
}
}
return returnValue
}
}
class MockHelper: NSObject {
var calledFunction: [String] = [String]()
var verifyCalledFunction: [String] = [String]()
var stubFunctions: [(String, MockActionable, Bool)] = [(String, MockActionable, Bool)]()
static let sharedInstance = MockHelper()
class func appendMethodByblock(_ aClass: AnyClass, sel: Selector, usingBlock aBlock: @convention(block)() -> Void) {
let objBlock = unsafeBitCast(aBlock, to: AnyObject.self)
let myIMP = imp_implementationWithBlock(objBlock)
let method = class_getInstanceMethod(aClass, sel)
method_setImplementation(method, myIMP)
}
class func appendMethodByblockInClass(_ aClass: AnyClass, newSelectorString: String, usingBlock aBlock: @convention(block)() -> Void) {
let objBlock = unsafeBitCast(aBlock, to: AnyObject.self)
let selNew = sel_registerName(newSelectorString)
let myIMP = imp_implementationWithBlock(objBlock)
class_addMethod(aClass, selNew, myIMP, "v@:")
}
func appendMethodByMoreBlock(_ obj: NSObject, sel: Selector) {
let aClass: AnyClass = type(of: obj)
let newSelectorString = "_\(sel)"
let aBlock: @convention(block)() -> Void = {
self.calledFunction.append("\(sel)")
obj.perform(Selector("\(sel)"))
}
let objBlock = unsafeBitCast(aBlock, to: AnyObject.self)
let myIMP = imp_implementationWithBlock(objBlock)
let selNew = sel_registerName(newSelectorString)
let method = class_getInstanceMethod(aClass, sel)
class_addMethod(aClass, selNew, myIMP, method_getTypeEncoding(method))
let replaceMethod = class_getInstanceMethod(aClass, Selector(newSelectorString))
// method_setImplementation(replaceMethod, myIMP)
// method_exchangeImplementations(method, replaceMethod)
class_replaceMethod(aClass, sel, method_getImplementation(method), method_getTypeEncoding(replaceMethod))
}
func appendMethodByMoreBlock(_ obj: NSObject, sel: Selector, appendM: Method) {
let aClass: AnyClass = type(of: obj)
//let method = class_getInstanceMethod(aClass, sel)
let selNew = sel_registerName("calledFunction:")
class_addMethod(aClass, selNew, method_getImplementation(appendM), method_getTypeEncoding(appendM))
//let replaceMethod = class_getInstanceMethod(aClass, sel.description)
//class_replaceMethod(aClass, sel , method_getImplementation(method), method_getTypeEncoding(replaceMethod))
let originalMethod = class_getInstanceMethod(aClass, sel)
let swizzledMethod = class_getInstanceMethod(aClass, Selector(("calledFunction:")))
method_exchangeImplementations(originalMethod, swizzledMethod)
}
class func verify() -> Bool {
var returnValue = false
for (_, ele) in MockHelper.sharedInstance.verifyCalledFunction.enumerated() {
if MockHelper.sharedInstance.verify(ele) {
returnValue = true
} else {
returnValue = false
return returnValue
}
}
MockHelper.sharedInstance.removeAllCalls()
return returnValue
}
class func functionIsGettingCalled(_ functionName: String) -> (Bool, Any?) {
let funcName = replaceFunctionName(functionName)
MockHelper.sharedInstance.calledFunction.append(funcName)
var returnValue: Any?
for stubFunction: (String, MockActionable, Bool) in MockHelper.sharedInstance.stubFunctions {
if stubFunction.0 == funcName {
returnValue = stubFunction.1.performActions()
return (stubFunction.2, returnValue)
}
}
return (false, nil)
}
class func expectCall(_ functionName: String) {
MockHelper.sharedInstance.verifyCalledFunction.append(functionName)
}
class func stub(_ functionName: String, _ overrideFunction: Bool = false, funcBlock: @escaping closureAny) -> MockActionable {
let mockActions = MockActionable(funcBlock)
MockHelper.sharedInstance.stubFunctions += [(functionName, mockActions, overrideFunction)]
return mockActions
}
class func replaceFunctionName(_ functionName: String) -> String {
var functionReturnName = functionName
if let funcNameReplace = functionName.getPatternString("\\(.+") {
functionReturnName = functionName.replacingOccurrences(of: funcNameReplace, with: "")
}
return functionReturnName
}
class func mockMyObject<O: AnyObject, C: TestableClass>(_ currentObject: O, _ mockType: C.Type) {
if mockType is O.Type {
object_setClass(currentObject, mockType)
}
}
func verify(_ str: String) -> Bool {
let itemExists = calledFunction.contains(str)
return itemExists
}
func removeAllCalls() {
verifyCalledFunction.removeAll(keepingCapacity: false)
calledFunction.removeAll(keepingCapacity: false)
stubFunctions.removeAll(keepingCapacity: false)
}
}
extension String {
func getPatternString(_ pattern: String) -> String? {
if let inputRange = self.range(of: pattern, options: .regularExpression) {
return self.substring(with: inputRange)
} else {
return nil
}
}
}
//class func enumerateMethodsInClass(_ aClass: AnyClass, usingBlock aBlock: (_ cls: AnyClass, _ sel: Selector) -> Void) {
// var mc: CUnsignedInt = 0
// var mlist: UnsafeMutablePointer<Method> = class_copyMethodList(aClass, &mc)
// for i: CUnsignedInt in 0 ..< mc {
// let sel: Selector = method_getName(mlist.pointee)
// mlist = mlist.successor()
// aBlock(aClass, sel)
// }
//}
//@objc class mirrorClassObj: NSObject{
// var aClass: NSObject!
// func callFunction(functionName: String = __FUNCTION__,lineNo: Int = __LINE__){
// print("functionName : \(functionName) : \(lineNo)")
// }
// convenience required init(_ aClass_: NSObject.Type){
// self.init()
// aClass = aClass_.init()
// MockHelper.enumerateMethodsInClass(aClass_) { (cls, sel) -> Void in
// if sel.description != ".cxx_destruct"{
// MockHelper.sharedInstance.appendMethodByMoreBlock(self.aClass, sel: sel,appendM: class_getClassMethod(mirrorClassObj.self, Selector("callFunction")))
// }
// }
//
// }
//}
|
a03257f7e95c281b9d2bd4edfd35dc64
| 37.619048 | 167 | 0.64365 | false | false | false | false |
k-ori/algorithm-playground
|
refs/heads/master
|
src/Queue.swift
|
mit
|
1
|
//
// Queue.swift
//
//
// Created by kori on 8/13/16.
//
//
import Foundation
/////////////////////////////////
/*
https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X
Q 3.5
enqueue 1, 2, 3, 4
q: [1, 2, 3, 4]
enS: [1, 2, 3, 4]
deS: []
dequeue
q: [2, 3, 4]
enS: []
deS: [4, 3, 2, 1] -> [4, 3, 2]
dequeue
enS: []
deS: [4, 3]
enqueue 5
enS: [3, 4, 5]
deS: []
*/
class QueueByStacks {
private var enqueStack: [Int] = []
private var dequeStack: [Int] = []
func enque(v: Int) {
move(from: &dequeStack, to: &enqueStack)
enqueStack.append(v)
}
func deque() -> Int? {
move(from: &enqueStack, to: &dequeStack)
guard let last = dequeStack.last else { return nil }
dequeStack.removeLast()
return last
}
private func move(inout from from: [Int], inout to: [Int]) {
guard from.count > 0 else { return }
while let last = from.last {
from.removeLast()
to.append(last)
}
}
}
let queueByStacks = QueueByStacks()
queueByStacks.enque(1)
queueByStacks.enque(2)
queueByStacks.enque(3)
assert(queueByStacks.deque()!==1)
/*
https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X
Q 3.6
[5, 2, 3, 0]
[4,9]
[5, 2, 3, 9, 4]
[0]
[5,2] 3
[0,4,9]
[5,2,9,4]
[0,3]
[5,2]
[0,3,4,9]
*/
|
7d3cb83e4d1b7ef0eb24a352f17d389b
| 13.606383 | 85 | 0.557902 | false | false | false | false |
jonatascb/Smashtag
|
refs/heads/master
|
Smashtag/Twitter/Tweet.swift
|
mit
|
1
|
//
// Tweet.swift
// Twitter
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import Foundation
// a simple container class which just holds the data in a Tweet
// IndexedKeywords are substrings of the Tweet's text
// for example, a hashtag or other user or url that is mentioned in the Tweet
// note carefully the comments on the two range properties in an IndexedKeyword
// Tweet instances re created by fetching from Twitter using a TwitterRequest
public class Tweet : Printable
{
public var text: String
public var user: User
public var created: NSDate
public var id: String?
public var media = [MediaItem]()
public var hashtags = [IndexedKeyword]()
public var urls = [IndexedKeyword]()
public var userMentions = [IndexedKeyword]()
public struct IndexedKeyword: Printable
{
public var keyword: String // will include # or @ or http:// prefix
public var range: Range<String.Index> // index into the Tweet's text property only
public var nsrange: NSRange = NSMakeRange (0,0) // index into an NS[Attributed]String made from the Tweet's text
public init?(data: NSDictionary?, inText: String, prefix: String?) {
let indices = data?.valueForKeyPath(TwitterKey.Entities.Indices) as? NSArray
if let startIndex = (indices?.firstObject as? NSNumber)?.integerValue {
if let endIndex = (indices?.lastObject as? NSNumber)?.integerValue {
let length = count(inText)
if length > 0 {
let start = max(min(startIndex, length-1), 0)
let end = max(min(endIndex, length), 0)
if end > start {
range = advance(inText.startIndex, start)...advance(inText.startIndex, end-1)
keyword = inText.substringWithRange(range)
if prefix != nil && !keyword.hasPrefix(prefix!) && start > 0 {
range = advance(inText.startIndex, start-1)...advance(inText.startIndex, end-2)
keyword = inText.substringWithRange(range)
}
if prefix == nil || keyword.hasPrefix(prefix!) {
nsrange = inText.rangeOfString(keyword, nearRange: NSMakeRange(startIndex, endIndex-startIndex))
if nsrange.location != NSNotFound {
return
}
}
}
}
}
}
return nil
}
public var description: String { get { return "\(keyword) (\(nsrange.location), \(nsrange.location+nsrange.length-1))" } }
}
public var description: String { return "\(user) - \(created)\n\(text)\nhashtags: \(hashtags)\nurls: \(urls)\nuser_mentions: \(userMentions)" + (id == nil ? "" : "\nid: \(id!)") }
// MARK: - Private Implementation
init?(data: NSDictionary?) {
if let user = User(data: data?.valueForKeyPath(TwitterKey.User) as? NSDictionary) {
self.user = user
if let text = data?.valueForKeyPath(TwitterKey.Text) as? String {
self.text = text
if let created = (data?.valueForKeyPath(TwitterKey.Created) as? String)?.asTwitterDate {
self.created = created
id = data?.valueForKeyPath(TwitterKey.ID) as? String
if let mediaEntities = data?.valueForKeyPath(TwitterKey.Media) as? NSArray {
for mediaData in mediaEntities {
if let mediaItem = MediaItem(data: mediaData as? NSDictionary) {
media.append(mediaItem)
}
}
}
let hashtagMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.Hashtags) as? NSArray
hashtags = getIndexedKeywords(hashtagMentionsArray, inText: text, prefix: "#")
let urlMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.URLs) as? NSArray
urls = getIndexedKeywords(urlMentionsArray, inText: text, prefix: "h")
let userMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.UserMentions) as? NSArray
userMentions = getIndexedKeywords(userMentionsArray, inText: text, prefix: "@")
return
}
}
}
// we've failed
// but compiler won't let us out of here with non-optional values unset
// so set them to anything just to able to return nil
// we could make these implicitly-unwrapped optionals, but they should never be nil, ever
self.text = ""
self.user = User()
self.created = NSDate()
return nil
}
private func getIndexedKeywords(dictionary: NSArray?, inText: String, prefix: String? = nil) -> [IndexedKeyword] {
var results = [IndexedKeyword]()
if let indexedKeywords = dictionary {
for indexedKeywordData in indexedKeywords {
if let indexedKeyword = IndexedKeyword(data: indexedKeywordData as? NSDictionary, inText: inText, prefix: prefix) {
results.append(indexedKeyword)
}
}
}
return results
}
struct TwitterKey {
static let User = "user"
static let Text = "text"
static let Created = "created_at"
static let ID = "id_str"
static let Media = "entities.media"
struct Entities {
static let Hashtags = "entities.hashtags"
static let URLs = "entities.urls"
static let UserMentions = "entities.user_mentions"
static let Indices = "indices"
}
}
}
private extension NSString {
func rangeOfString(substring: NSString, nearRange: NSRange) -> NSRange {
var start = max(min(nearRange.location, length-1), 0)
var end = max(min(nearRange.location + nearRange.length, length), 0)
var done = false
while !done {
let range = rangeOfString(substring as String, options: NSStringCompareOptions.allZeros, range: NSMakeRange(start, end-start))
if range.location != NSNotFound {
return range
}
done = true
if start > 0 { start-- ; done = false }
if end < length { end++ ; done = false }
}
return NSMakeRange(NSNotFound, 0)
}
}
private extension String {
var asTwitterDate: NSDate? {
get {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
return dateFormatter.dateFromString(self)
}
}
}
|
cebb35f6762eb04c55e50c26359270ad
| 43.605096 | 183 | 0.567471 | false | false | false | false |
LoopKit/LoopKit
|
refs/heads/dev
|
MockKitUI/View Controllers/MeasurementFrequencyTableViewController.swift
|
mit
|
1
|
//
// MeasurementFrequencyTableViewController.swift
// MockKitUI
//
// Created by Nathaniel Hamming on 2020-06-22.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import UIKit
import LoopKit
import LoopKitUI
import MockKit
protocol MeasurementFrequencyTableViewControllerDelegate: AnyObject {
func measurementFrequencyTableViewControllerDidChangeFrequency(_ controller: MeasurementFrequencyTableViewController)
}
final class MeasurementFrequencyTableViewController: RadioSelectionTableViewController {
var measurementFrequency: MeasurementFrequency? {
get {
if let selectedIndex = selectedIndex {
return MeasurementFrequency.allCases[selectedIndex]
} else {
return nil
}
}
set {
if let newValue = newValue {
selectedIndex = MeasurementFrequency.allCases.firstIndex(of: newValue)
} else {
selectedIndex = nil
}
}
}
weak var measurementFrequencyDelegate: MeasurementFrequencyTableViewControllerDelegate?
convenience init() {
self.init(style: .grouped)
options = MeasurementFrequency.allCases.map { frequency in
"\(frequency.localizedDescription)"
}
delegate = self
}
}
extension MeasurementFrequencyTableViewController: RadioSelectionTableViewControllerDelegate {
func radioSelectionTableViewControllerDidChangeSelectedIndex(_ controller: RadioSelectionTableViewController) {
measurementFrequencyDelegate?.measurementFrequencyTableViewControllerDidChangeFrequency(self)
}
}
|
aea1921854d0e101df8889938e1d71f5
| 30.692308 | 121 | 0.709345 | false | false | false | false |
SwiftFMI/iOS_2017_2018
|
refs/heads/master
|
Lectures/code/05.01.2018/LocationDemo/LocationDemo/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// LocationDemo
//
// Created by Emil Atanasov on 5.01.18.
// Copyright © 2018 SwiftFMI. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{
//добре е да е е член променлива, за да се пази в паметта
let manager = CLLocationManager()
//UIRequiredDeviceCapabilities в Info.plist се използва за да се определи дали дадено устройство има съответния хардуер и дали приложението ще работи location-services или gps
//Ако приложението може да работи и без тези изисквания, тогава не е нужно да добавяте
//тези изсквания, понеже броя на поддържаните устройства ще е по-малък.
//Когато искаме да изпозлваме различни функций на устройството iOS
//запитва потребителя за неговото разрешение. Добре е да прилагаме
//следните правила:
// * Винаги да питаме в последния възможен момент. Т.е. когато приложението трябва да използва лоацията на потребителя да го пита за разрешение не при първото стартиране на приложението, преди потребителя да знае какво прави приложението, а при първия необходим момент, при възможност след действие от страна на потребителя.
// * Да подготвим потребителя с правилнито съобщение. В случая с локацията - ключът NSLocationWhenInUseUsageDescription трябва да бъде добавен в Info.plist
// * Ако нямаме контрол върху текстовете (текста за достъп до notifications/нотификациите не може да се променя) е правилно да покажем предварителен текст и чак тогава да пристъпим към следващата стъпка.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
checkLocationService()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func checkLocationService() {
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
print("неопределено")
manager.delegate = self
manager.requestWhenInUseAuthorization()
case .authorizedWhenInUse:
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.distanceFilter = 100
manager.startUpdatingLocation()
break
default:
//
print("Нямаме достъп. Може ли да работи приложението?")
break
}
//изпозлва се, ако ще трябва да ползваме Location през
//по време на използване на приложението, но дори и в
//background - пример Maps, Google Maps
// manager.requestAlwaysAuthorization()
} else {
//Възможни са различни причини за да няма достъп до location услугата
//Примерно: малко батерия
//потребителя е забранил достъпа и др.
print("Няма достъп до location услугата.")
}
}
//MARK : CLLocationManagerDelegate
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("New locations were sent!")
print("Locations: \(locations)")
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse:
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.distanceFilter = 100
manager.startUpdatingLocation()
case .notDetermined:
print("неопределено")
default:
//
print("Нямаме достъп. Може ли да работи приложението?")
break
}
}
}
|
1b1bf599d915646e9155811b1060d35c
| 41.09375 | 328 | 0.648602 | false | false | false | false |
sonsongithub/spbuilder
|
refs/heads/master
|
main.swift
|
mit
|
1
|
//
// main.swift
// spbuilder
//
// Created by sonson on 2016/06/22.
// Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
extension NSError {
class func error(description: String) -> NSError {
return NSError(domain:"com.sonson.spbuilder", code: 0, userInfo:["description":description])
}
}
struct Book {
let name: String
let version: String
let contentIdentifier: String
let contentVersion: String
var imageReference: String?
let deploymentTarget: String
var chapters: [Chapter]
init(name aName: String, version aVersion: String, contentIdentifier aContentIdentifier: String, contentVersion aContentVersion: String, imageReference anImageReference: String? = nil, deploymentTarget aDeploymentTarget: String, chapters arrayChapters: [String] = []) {
name = aName
version = aVersion
contentIdentifier = aContentVersion
contentVersion = aContentVersion
imageReference = anImageReference
deploymentTarget = aDeploymentTarget
chapters = arrayChapters.map({ (name) -> Chapter in
let title = name.replacingOccurrences(of: ".playgroundchapter", with: "")
print("\(name) => \(title)")
return Chapter(name: title)
})
}
func getChapter(name: String) throws -> Chapter {
for i in 0..<chapters.count {
if chapters[i].name == name {
return chapters[i]
}
}
throw NSError.error(description: "Not found")
}
mutating func add(chapter: Chapter) throws {
if chapters.map({$0.name}).index(of: chapter.name) != nil {
throw NSError.error(description: "Already page has been added.")
}
chapters.append(chapter)
do {
try writeManifest()
} catch {
throw error
}
}
func manifest() -> [String:AnyObject] {
var dict: [String:AnyObject] = [
"Name" : name,
"Version" : version,
"ContentIdentifier" : contentIdentifier,
"ContentVersion" : contentVersion,
"DeploymentTarget" : deploymentTarget,
"Chapters" : chapters.map({ $0.name + ".playgroundchapter" }) as [String]
]
if let imageReference = imageReference {
dict["ImageReference"] = imageReference
}
return dict
}
func writeManifest(at: String = "./Contents/Manifest.plist") throws {
let nsdictionary = manifest() as NSDictionary
if !nsdictionary.write(toFile: at, atomically: false) {
throw NSError.error(description: "Can not write plist.")
}
}
func parepareDefaultFiles() throws {
let path = "./\(name).playgroundbook"
let sourcesPath = "./\(path)/Contents/Sources"
let resourcesPath = "./\(path)/Contents/Resources"
do {
try FileManager.default().createDirectory(atPath: sourcesPath, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: resourcesPath, withIntermediateDirectories: true, attributes: nil)
} catch {
throw error
}
}
func create() throws {
// create book
do {
let path = "./\(name).playgroundbook"
let contentsPath = "./\(path)/Contents"
try FileManager.default().createDirectory(atPath: contentsPath, withIntermediateDirectories: true, attributes: nil)
try writeManifest(at: "./\(path)/Contents/Manifest.plist")
try parepareDefaultFiles()
} catch {
throw error
}
}
}
struct Chapter {
let name: String
var pages: [Page]
let version: String
init(name aName: String, version aVersion: String = "1.0") {
print("Chapter name = \(aName)")
name = aName
version = aVersion
pages = []
let at = "./Contents/Chapters/\(name).playgroundchapter"
let chapterManifestPath = "\(at)/Manifest.plist"
if FileManager.default().isReadableFile(atPath: chapterManifestPath) {
if let dict = NSDictionary(contentsOfFile: chapterManifestPath) {
if let name = dict["Name"] as? String,
version = dict["Version"] as? String {
let pageNames = dict["Pages"] as? [String] ?? [] as [String]
pages = pageNames.map({ (name) -> Page in
let title = name.replacingOccurrences(of: ".playgroundpage", with: "")
return Page(name: title, chapterName: name)
})
}
}
}
}
func manifest() -> [String:AnyObject] {
let dict: [String:AnyObject] = [
"Name" : name,
"Version" : version,
"Pages" : pages.map({ $0.name + ".playgroundpage" }) as [String]
]
return dict
}
mutating func add(page: Page) throws {
if pages.map({$0.name}).index(of: page.name) != nil {
throw NSError.error(description: "Already page has been added.")
}
pages.append(page)
do {
try writeManifest()
} catch {
throw error
}
}
func writeManifest() throws {
let at = "./Contents/Chapters/\(name).playgroundchapter"
let sourcesPath = "./\(at)/Sources"
let resourcesPath = "./\(at)/Resources"
do {
try FileManager.default().createDirectory(atPath: at, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: sourcesPath, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: resourcesPath, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
let nsdictionary = manifest() as NSDictionary
print(nsdictionary)
print(at)
if !nsdictionary.write(toFile: at + "/Manifest.plist", atomically: false) {
throw NSError.error(description: "Chapter: Can not write plist.")
}
}
}
struct Page {
let name: String
let version: String
let chapterName: String
init(name aName: String, version aVersion: String = "1.0", chapterName aChapterName: String) {
name = aName
version = aVersion
chapterName = aChapterName
}
func manifest() -> [String:AnyObject] {
let dict: [String:AnyObject] = [
"Name" : name,
"Version" : version,
"LiveViewMode" : "HiddenByDefault"
]
return dict
}
func parepareDefaultFiles() throws {
let liveViewPath = "./Contents/Chapters/\(chapterName).playgroundchapter/Pages/\(name).playgroundpage/LiveView.swift"
let contentsPath = "./Contents/Chapters/\(chapterName).playgroundchapter/Pages/\(name).playgroundpage/Contents.swift"
let liveViewTemplate = "// LiveView.swift"
let contentsTemplate = "// Contents.swift"
do {
try liveViewTemplate.write(toFile: liveViewPath, atomically: false, encoding: .utf8)
try contentsTemplate.write(toFile: contentsPath, atomically: false, encoding: .utf8)
} catch {
throw error
}
}
func writeManifest() throws {
let at = "./Contents/Chapters/\(chapterName).playgroundchapter/Pages/\(name).playgroundpage/"
do {
try FileManager.default().createDirectory(atPath: at, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
let nsdictionary = manifest() as NSDictionary
if !nsdictionary.write(toFile: at + "/Manifest.plist", atomically: false) {
throw NSError.error(description: "Page : Can not write plist.")
}
}
}
func bookExists(bookName: String) -> Bool {
return FileManager.default().fileExists(atPath: "./\(bookName).playgroundbook")
}
func loadBook() throws -> Book {
let bookManifestPath = "./Contents/Manifest.plist"
if FileManager.default().isReadableFile(atPath: bookManifestPath) {
// open
guard let dict = NSDictionary(contentsOfFile: bookManifestPath) else { throw NSError.error(description: "Can not parse Manifest.plist.") }
if let name = dict["Name"] as? String,
version = dict["Version"] as? String,
contentIdentifier = dict["ContentIdentifier"] as? String,
contentVersion = dict["ContentVersion"] as? String,
deploymentTarget = dict["DeploymentTarget"] as? String {
let imageReference = dict["ImageReference"] as? String
let chapters = dict["Chapters"] as? [String] ?? [] as [String]
return Book(name: name, version: version, contentIdentifier: contentIdentifier, contentVersion: contentVersion, imageReference: imageReference, deploymentTarget: deploymentTarget, chapters: chapters)
} else {
throw NSError.error(description: "Manifest.plist is malformed.")
}
} else {
throw NSError.error(description: "Can not find Manifest.plist. Moved inside playgroundbook's directory.")
}
}
func createBook(argc: Int, arguments: [String]) throws {
if argc == 3 {
if bookExists(bookName: arguments[1]) {
throw NSError.error(description: "Book already exsits.")
} else {
do {
try Book(name: arguments[1], version: "1.0", contentIdentifier: arguments[2], contentVersion: "1.0", deploymentTarget: "ios10.10").create()
} catch {
throw error
}
}
} else {
throw NSError.error(description: "Arguments is less.")
}
}
func addChapter(argc: Int, arguments: [String]) throws {
if argc == 2 {
do {
var book = try loadBook()
let chapter = Chapter(name: arguments[1])
try book.add(chapter: chapter)
try book.writeManifest()
try chapter.writeManifest()
} catch {
throw error
}
} else {
throw NSError.error(description: "Arguments is less.")
}
}
func addPage(argc: Int, arguments: [String]) throws {
if argc == 3 {
do {
let book = try loadBook()
var chapter = try book.getChapter(name: arguments[1])
let page = Page(name: arguments[2], chapterName: chapter.name)
try chapter.add(page: page)
try page.writeManifest()
try page.parepareDefaultFiles()
} catch {
throw error
}
} else {
throw NSError.error(description: "Arguments is less.")
}
}
func parseArguments() throws {
var arguments :[String] = ProcessInfo.processInfo().arguments
print(arguments.first)
let argc = arguments.count - 1
if argc >= 1 {
arguments.removeFirst() // remove own path
switch arguments[0] {
case "create":
do { try createBook(argc: argc, arguments: arguments) } catch { throw error }
case "chapter":
do { try addChapter(argc: argc, arguments: arguments) } catch { throw error }
case "page":
do { try addPage(argc: argc, arguments: arguments) } catch { throw error }
case "rm":
print(argc)
default:
print(argc)
}
} else {
throw NSError.error(description: "Arguments are less.")
}
}
func main() {
do {
try parseArguments()
} catch {
print(error)
}
}
main()
|
03f1bec4b2f9239cdbc8aba0de1c2e8a
| 34.20597 | 273 | 0.585806 | false | false | false | false |
HassanEskandari/Eureka
|
refs/heads/master
|
Pods/Eureka/Source/Core/SelectableSection.swift
|
apache-2.0
|
5
|
// SelectableSection.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: SelectableSection
/**
Defines how the selection works in a SelectableSection
- MultipleSelection: Multiple options can be selected at once
- SingleSelection: Only one selection at a time. Can additionally specify if deselection is enabled or not.
*/
public enum SelectionType {
/**
* Multiple options can be selected at once
*/
case multipleSelection
/**
* Only one selection at a time. Can additionally specify if deselection is enabled or not.
*/
case singleSelection(enableDeselection: Bool)
}
/**
* Protocol to be implemented by selectable sections types. Enables easier customization
*/
public protocol SelectableSectionType: Collection {
associatedtype SelectableRow: BaseRow, SelectableRowType
/// Defines how the selection works (single / multiple selection)
var selectionType: SelectionType { get set }
/// A closure called when a row of this section is selected.
var onSelectSelectableRow: ((SelectableRow.Cell, SelectableRow) -> Void)? { get set }
func selectedRow() -> SelectableRow?
func selectedRows() -> [SelectableRow]
}
extension SelectableSectionType where Self: Section {
/**
Returns the selected row of this section. Should be used if selectionType is SingleSelection
*/
public func selectedRow() -> SelectableRow? {
return selectedRows().first
}
/**
Returns the selected rows of this section. Should be used if selectionType is MultipleSelection
*/
public func selectedRows() -> [SelectableRow] {
let selectedRows: [BaseRow] = self.filter { $0 is SelectableRow && $0.baseValue != nil }
return selectedRows.map { $0 as! SelectableRow }
}
/**
Internal function used to set up a collection of rows before they are added to the section
*/
func prepare(selectableRows rows: [BaseRow]) {
for row in rows {
if let row = row as? SelectableRow {
row.onCellSelection { [weak self] cell, row in
guard let s = self, !row.isDisabled else { return }
switch s.selectionType {
case .multipleSelection:
row.value = row.value == nil ? row.selectableValue : nil
case let .singleSelection(enableDeselection):
s.forEach {
guard $0.baseValue != nil && $0 != row else { return }
$0.baseValue = nil
$0.updateCell()
}
// Check if row is not already selected
if row.value == nil {
row.value = row.selectableValue
} else if enableDeselection {
row.value = nil
}
}
row.updateCell()
s.onSelectSelectableRow?(cell, row)
}
}
}
}
}
/// A subclass of Section that serves to create a section with a list of selectable options.
open class SelectableSection<Row>: Section, SelectableSectionType where Row: SelectableRowType, Row: BaseRow {
public typealias SelectableRow = Row
/// Defines how the selection works (single / multiple selection)
public var selectionType = SelectionType.singleSelection(enableDeselection: true)
/// A closure called when a row of this section is selected.
public var onSelectSelectableRow: ((Row.Cell, Row) -> Void)?
public override init(_ initializer: (SelectableSection<Row>) -> Void) {
super.init({ _ in })
initializer(self)
}
public init(_ header: String, selectionType: SelectionType, _ initializer: (SelectableSection<Row>) -> Void = { _ in }) {
self.selectionType = selectionType
super.init(header, { _ in })
initializer(self)
}
public init(header: String, footer: String, selectionType: SelectionType, _ initializer: (SelectableSection<Row>) -> Void = { _ in }) {
self.selectionType = selectionType
super.init(header: header, footer: footer, { _ in })
initializer(self)
}
public required init() {
super.init()
}
open override func rowsHaveBeenAdded(_ rows: [BaseRow], at: IndexSet) {
prepare(selectableRows: rows)
}
}
|
735fe9d473961e80a7829329521c60a0
| 37.060811 | 139 | 0.641221 | false | false | false | false |
dbsystel/DBNetworkStack
|
refs/heads/develop
|
Tests/ModifyRequestNetworkService.swift
|
mit
|
1
|
//
// Copyright (C) 2017 DB Systel GmbH.
// DB Systel GmbH; Jürgen-Ponto-Platz 1; D-60329 Frankfurt am Main; Germany; http://www.dbsystel.de/
//
// 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 XCTest
import Foundation
@testable import DBNetworkStack
class ModifyRequestNetworkServiceTest: XCTestCase {
var networkServiceMock: NetworkServiceMock!
override func setUp() {
super.setUp()
networkServiceMock = NetworkServiceMock()
}
func testRequest_withModifedRequest() {
//Given
let modification: [(URLRequest) -> URLRequest] = [ { request in
return request.appending(queryParameters: ["key": "1"])
} ]
let networkService: NetworkService = ModifyRequestNetworkService(networkService: networkServiceMock, requestModifications: modification)
let request = URLRequest(path: "/trains", baseURL: .defaultMock)
let resource = Resource<Int>(request: request, parse: { _ in return 1 })
//When
networkService.request(resource, onCompletion: { _ in }, onError: { _ in })
//Then
XCTAssert(networkServiceMock.lastRequest?.url?.absoluteString.contains("key=1") ?? false)
}
func testAddHTTPHeaderToRequest() {
//Given
let request = URLRequest(url: .defaultMock)
let header = ["header": "head"]
//When
let newRequest = request.added(HTTPHeaderFields: header)
//Then
XCTAssertEqual(newRequest.allHTTPHeaderFields?["header"], "head")
}
func testAddDuplicatedQueryToRequest() {
//Given
let url = URL(staticString: "bahn.de?test=test&bool=true")
let request = URLRequest(url: url)
let parameters = ["test": "test2"]
//When
let newRequest = request.appending(queryParameters: parameters)
//Then
let newURL: URL! = newRequest.url
let query = URLComponents(url: newURL, resolvingAgainstBaseURL: true)?.queryItems
XCTAssertEqual(query?.count, 2)
XCTAssert(query?.contains(where: { $0.name == "test" && $0.value == "test2" }) ?? false)
XCTAssert(query?.contains(where: { $0.name == "bool" && $0.value == "true" }) ?? false)
}
func testReplaceAllQueryItemsFromRequest() {
//Given
let url = URL(staticString: "bahn.de?test=test&bool=true")
let request = URLRequest(url: url)
let parameters = ["test5": "test2"]
//When
let newRequest = request.replacingAllQueryItems(with: parameters)
//Then
let newURL: URL! = newRequest.url
let query = URLComponents(url: newURL, resolvingAgainstBaseURL: true)?.queryItems
XCTAssertEqual(query?.count, 1)
XCTAssert(query?.contains(where: { $0.name == "test5" && $0.value == "test2" }) ?? false)
}
}
|
518975248c570fb32a12dd9627f69bda
| 39.131313 | 144 | 0.65039 | false | true | false | false |
kotdark/tetrisUsingSwift
|
refs/heads/master
|
Tetris/Tetris/GameScene.swift
|
mit
|
1
|
//
// GameScene.swift
// Tetris
//
// Created by TranDuy on 10/20/15.
// Copyright (c) 2015 KDStudio. All rights reserved.
//
import SpriteKit
let blockSize:CGFloat = 20.0
let tickLengthLevelOne = NSTimeInterval(600)
class GameScene: SKScene {
let gameLayer = SKScene()
let shapeLayer = SKScene()
let layerPosition = CGPoint(x: 6, y: -6)
var tick:(() -> ())?
var tickLengthMillis = tickLengthLevelOne
var lastTick:NSDate?
var textureCache = Dictionary<String, SKTexture>()
required init(coder aDecoder: NSCoder) {
fatalError("NSCoder not support!")
}
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0, y: 1.0)
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: 0, y: 0)
background.anchorPoint = CGPoint(x: 0, y: 1.0)
addChild(background)
addChild(gameLayer)
let gameBoardTexture = SKTexture(imageNamed: "gameboard")
let gameBoard = SKSpriteNode(texture: gameBoardTexture, size: CGSizeMake(blockSize * CGFloat(numColumns), blockSize * CGFloat(numRows)))
gameBoard.anchorPoint = CGPoint(x:0, y:1.0)
gameBoard.position = layerPosition
shapeLayer.position = layerPosition
shapeLayer.addChild(gameBoard)
gameLayer.addChild(shapeLayer)
runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true)))
}
func playSound(sound:String) {
runAction(SKAction.playSoundFileNamed(sound, waitForCompletion: false))
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if lastTick == nil {
return
}
let timePassed = lastTick!.timeIntervalSinceNow * -1000.0
if timePassed > tickLengthMillis {
lastTick = NSDate()
tick?()
}
}
func startTicking() {
lastTick = NSDate()
}
func stopTicking() {
lastTick = nil
}
func pointForColumn(column: Int, row: Int) -> CGPoint {
let x = layerPosition.x + (CGFloat(column) * blockSize) + (blockSize / 2)
let y = layerPosition.y - (CGFloat(row) * blockSize) + (blockSize / 2)
return CGPointMake(x, y)
}
func addPreviewShapeToScene(shape:Shape, completion:()->()) {
for (_, block) in shape.blocks.enumerate() {
var texture = textureCache[block.spriteName]
if texture == nil {
texture = SKTexture(imageNamed: block.spriteName)
textureCache[block.spriteName] = texture
}
let sprite = SKSpriteNode(texture: texture)
sprite.position = pointForColumn(block.column, row: block.row)
shapeLayer.addChild(sprite)
block.sprite = sprite
// Animation
sprite.alpha = 0
let moveAction = SKAction.moveTo(pointForColumn(block.column, row: block.row), duration: NSTimeInterval(0.2))
moveAction.timingMode = .EaseOut
let fadeInAction = SKAction.fadeAlphaTo(0.7, duration: 0.4)
fadeInAction.timingMode = .EaseOut
sprite.runAction(SKAction.group([moveAction, fadeInAction]))
}
runAction(SKAction.waitForDuration(0.4), completion: completion)
}
func movePreviewShape(shape:Shape, completion:() -> ()) {
for (_, block) in shape.blocks.enumerate() {
let sprite = block.sprite!
let moveTo = pointForColumn(block.column, row:block.row)
let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.2)
moveToAction.timingMode = .EaseOut
sprite.runAction(
SKAction.group([moveToAction, SKAction.fadeAlphaTo(1.0, duration: 0.2)]))
}
runAction(SKAction.waitForDuration(0.2), completion: completion)
}
func redrawShape(shape:Shape, completion:() -> ()) {
for (_, block) in shape.blocks.enumerate() {
let sprite = block.sprite!
let moveTo = pointForColumn(block.column, row:block.row)
let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.05)
moveToAction.timingMode = .EaseOut
sprite.runAction(moveToAction)
}
runAction(SKAction.waitForDuration(0.05), completion: completion)
}
func animateCollapsingLines(linesToRemove: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>, completion:() -> ()) {
var longestDuration: NSTimeInterval = 0
// #2
for (columnIdx, column) in fallenBlocks.enumerate() {
for (blockIdx, block) in column.enumerate() {
let newPosition = pointForColumn(block.column, row: block.row)
let sprite = block.sprite!
// #3
let delay = (NSTimeInterval(columnIdx) * 0.05) + (NSTimeInterval(blockIdx) * 0.05)
let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / blockSize) * 0.1)
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
sprite.runAction(
SKAction.sequence([
SKAction.waitForDuration(delay),
moveAction]))
longestDuration = max(longestDuration, duration + delay)
}
}
for (_, row) in linesToRemove.enumerate() {
for (_, block) in row.enumerate() {
// #4
let randomRadius = CGFloat(UInt(arc4random_uniform(400) + 100))
let goLeft = arc4random_uniform(100) % 2 == 0
var point = pointForColumn(block.column, row: block.row)
point = CGPointMake(point.x + (goLeft ? -randomRadius : randomRadius), point.y)
let randomDuration = NSTimeInterval(arc4random_uniform(2)) + 0.5
// #5
var startAngle = CGFloat(M_PI)
var endAngle = startAngle * 2
if goLeft {
endAngle = startAngle
startAngle = 0
}
let archPath = UIBezierPath(arcCenter: point, radius: randomRadius, startAngle: startAngle, endAngle: endAngle, clockwise: goLeft)
let archAction = SKAction.followPath(archPath.CGPath, asOffset: false, orientToPath: true, duration: randomDuration)
archAction.timingMode = .EaseIn
let sprite = block.sprite!
// #6
sprite.zPosition = 100
sprite.runAction(
SKAction.sequence(
[SKAction.group([archAction, SKAction.fadeOutWithDuration(NSTimeInterval(randomDuration))]),
SKAction.removeFromParent()]))
}
}
// #7
runAction(SKAction.waitForDuration(longestDuration), completion:completion)
}
}
|
6bfaa84fb8872e9027b2048d689b2e2e
| 38.25 | 146 | 0.580033 | false | false | false | false |
JLCdeSwift/DangTangDemo
|
refs/heads/master
|
DanTangdemo/Classes/Main/Controller/LCNavigationController.swift
|
mit
|
1
|
//
// LCNavigationController.swift
// DanTangdemo
//
// Created by 冀柳冲 on 2017/7/5.
// Copyright © 2017年 sunny冲哥. All rights reserved.
//
import UIKit
import SVProgressHUD
class LCNavigationController: UINavigationController {
override class func initialize(){
super.initialize()
let navBar = UINavigationBar.appearance()
navBar.barTintColor = LCGlobalRedColor()
navBar.tintColor = UIColor.white
navBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 20)]
}
/// 统一定制左上角返回按钮
///
/// - Parameters:
/// - viewController: 即将入栈的控制器
/// - animated: 是否显示动画
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
/// 这时push进来的控制器viewController,不是第一个子控制器(不是根控制器)
if viewControllers.count > 0 {
// push 后隐藏 tabbar
viewController.hidesBottomBarWhenPushed = true
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "checkUserType_backward_9x15_"), style: .plain, target: self, action: #selector(navigationBackClick))
}
super.pushViewController(viewController, animated: animated)
}
/// 返回按钮
func navigationBackClick() {
if SVProgressHUD.isVisible() {
SVProgressHUD.dismiss()
}
//isNetworkActivityIndicatorVisible 指示器的联网动画(状态栏左侧转动的)
if UIApplication.shared.isNetworkActivityIndicatorVisible {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
popViewController(animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
bb61588de0edc4aa5572394a176ab0d3
| 31.746479 | 201 | 0.674839 | false | false | false | false |
eburns1148/CareKit
|
refs/heads/master
|
Sample/OCKSampleWatch Extension/EventRow.swift
|
bsd-3-clause
|
2
|
/*
Copyright (c) 2016, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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 OWNER 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 WatchKit
class EventRow : NSObject {
// MARK: Properties
var activityIdentifier : String?
var tintColor : UIColor?
var rowIndex : Int?
var buttons : [WKInterfaceButton] = []
var displayCompleted = [false, false, false]
var parentInterfaceController : InterfaceController?
@IBOutlet var leftButton: WKInterfaceButton!
@IBOutlet var centerButton: WKInterfaceButton!
@IBOutlet var rightButton: WKInterfaceButton!
// MARK: Rendering
func load(fromActivity activity: WCKActivity, withRowIndex rowIndex: Int, parent: InterfaceController) {
self.activityIdentifier = activity.identifier
self.tintColor = activity.tintColor
self.rowIndex = rowIndex
self.buttons = [leftButton, centerButton, rightButton]
self.parentInterfaceController = parent
for columnIndex in 0..<3 {
if 3 * rowIndex + columnIndex < activity.eventsForToday.count {
buttons[columnIndex].setHidden(false)
buttons[columnIndex].setBackgroundColor(tintColor)
displayCompleted[columnIndex] = (activity.eventsForToday[3 * rowIndex + columnIndex]!.state == .completed)
buttons[columnIndex].setBackgroundImageNamed(displayCompleted[columnIndex] ? "bubble-fill" : "bubble-empty")
} else {
buttons[columnIndex].setHidden(true)
}
}
}
func updateButton(withColumnIndex columnIndex: Int, toState state : WCKEventState) {
let completed = (state == .completed)
buttons[columnIndex].setBackgroundImageNamed(completed ? "bubble-fill" : "bubble-empty")
displayCompleted[columnIndex] = completed
}
func updateButton(withEventIndex eventIndex : Int, toState state : WCKEventState) {
updateButton(withColumnIndex: eventIndex - 3 * rowIndex!, toState: state)
}
// MARK: Handle user inputs
func didSelectButton(withColumnIndex columnIndex : Int) {
updateButton(withColumnIndex: columnIndex, toState: displayCompleted[columnIndex] ? .notCompleted : .completed)
parentInterfaceController?.updateDataStoreEvent(withActivityIdentifier: activityIdentifier!, atIndex: 3 * rowIndex! + columnIndex, toCompletedState: displayCompleted[columnIndex])
}
@IBAction func leftButtonPressed() {
didSelectButton(withColumnIndex: 0)
}
@IBAction func centerButtonPressed() {
didSelectButton(withColumnIndex: 1)
}
@IBAction func rightButtonPressed() {
didSelectButton(withColumnIndex: 2)
}
}
|
5f169146e3b534d8f3ca510af7b398df
| 41.762376 | 187 | 0.714286 | false | false | false | false |
alexph9/CalenduleAPP
|
refs/heads/master
|
Pods/JTAppleCalendar/Sources/UserInteractionFunctions.swift
|
mit
|
1
|
//
// UserInteractionFunctions.swift
// Pods
//
// Created by JayT on 2016-05-12.
//
//
extension JTAppleCalendarView {
/// Returns the cellStatus of a date that is visible on the screen.
/// If the row and column for the date cannot be found,
/// then nil is returned
/// - Paramater row: Int row of the date to find
/// - Paramater column: Int column of the date to find
/// - returns:
/// - CellState: The state of the found cell
public func cellStatusForDate(at row: Int, column: Int) -> CellState? {
guard let section = currentSection() else {
return nil
}
let convertedRow = (row * maxNumberOfDaysInWeek) + column
let indexPathToFind = IndexPath(item: convertedRow, section: section)
if let date = dateOwnerInfoFromPath(indexPathToFind) {
let stateOfCell = cellStateFromIndexPath(indexPathToFind, withDateInfo: date)
return stateOfCell
}
return nil
}
/// Returns the cell status for a given date
/// - Parameter: date Date of the cell you want to find
/// - returns:
/// - CellState: The state of the found cell
public func cellStatus(for date: Date) -> CellState? {
// validate the path
let paths = pathsFromDates([date])
// Jt101 change this function to also return
// information like the dateInfoFromPath function
if paths.isEmpty { return nil }
let cell = cellForItem(at: paths[0]) as? JTAppleCell
let stateOfCell = cellStateFromIndexPath(paths[0], cell: cell)
return stateOfCell
}
/// Returns the cell status for a given point
/// - Parameter: point of the cell you want to find
/// - returns:
/// - CellState: The state of the found cell
public func cellStatus(at point: CGPoint) -> CellState? {
if let indexPath = indexPathForItem(at: point) {
let cell = cellForItem(at: indexPath) as? JTAppleCell
return cellStateFromIndexPath(indexPath, cell: cell)
}
return nil
}
/// Deselect all selected dates
/// - Parameter: this funciton triggers a delegate call by default. Set this to false if you do not want this
public func deselectAllDates(triggerSelectionDelegate: Bool = true) {
deselect(dates: selectedDates, triggerSelectionDelegate: triggerSelectionDelegate)
}
func deselect(dates: [Date], triggerSelectionDelegate: Bool = true) {
if allowsMultipleSelection {
selectDates(dates, triggerSelectionDelegate: triggerSelectionDelegate)
} else {
guard let path = pathsFromDates(dates).first else { return }
collectionView(self, didDeselectItemAt: path)
}
}
/// Generates a range of dates from from a startDate to an
/// endDate you provide
/// Parameter startDate: Start date to generate dates from
/// Parameter endDate: End date to generate dates to
/// returns:
/// - An array of the successfully generated dates
public func generateDateRange(from startDate: Date, to endDate: Date) -> [Date] {
if startDate > endDate {
return []
}
var returnDates: [Date] = []
var currentDate = startDate
repeat {
returnDates.append(currentDate)
currentDate = calendar.startOfDay(for: calendar.date(
byAdding: .day, value: 1, to: currentDate)!)
} while currentDate <= endDate
return returnDates
}
/// Registers a class for use in creating supplementary views for the collection view.
/// For now, the calendar only supports: 'UICollectionElementKindSectionHeader' for the forSupplementaryViewOfKind(parameter)
open override func register(_ viewClass: AnyClass?, forSupplementaryViewOfKind elementKind: String, withReuseIdentifier identifier: String) {
super.register(viewClass, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: identifier)
}
/// Registers a class for use in creating supplementary views for the collection view.
/// For now, the calendar only supports: 'UICollectionElementKindSectionHeader' for the forSupplementaryViewOfKind(parameter)
open override func register(_ nib: UINib?, forSupplementaryViewOfKind kind: String, withReuseIdentifier identifier: String) {
super.register(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: identifier)
}
/// Dequeues re-usable calendar cells
public func dequeueReusableJTAppleSupplementaryView(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> JTAppleCollectionReusableView {
guard let headerView = dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: identifier,
for: indexPath) as? JTAppleCollectionReusableView else {
developerError(string: "Error initializing Header View with identifier: '\(identifier)'")
return JTAppleCollectionReusableView()
}
return headerView
}
/// Registers a nib for use in creating Decoration views for the collection view.
public func registerDecorationView(nib: UINib?) {
calendarViewLayout.register(nib, forDecorationViewOfKind: decorationViewID)
}
/// Registers a class for use in creating Decoration views for the collection view.
public func register(viewClass className: AnyClass?, forDecorationViewOfKind kind: String) {
calendarViewLayout.register(className, forDecorationViewOfKind: decorationViewID)
}
/// Dequeues a reuable calendar cell
public func dequeueReusableJTAppleCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> JTAppleCell {
guard let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? JTAppleCell else {
developerError(string: "Error initializing Cell View with identifier: '\(identifier)'")
return JTAppleCell()
}
return cell
}
/// Reloads the data on the calendar view. Scroll delegates are not
// triggered with this function.
/// - Parameter date: An anchordate that the calendar will
/// scroll to after reload completes
/// - Parameter animation: Scroll is animated if this is set to true
/// - Parameter completionHandler: This closure will run after
/// the reload is complete
public func reloadData(with anchorDate: Date? = nil, animation: Bool = false, completionHandler: (() -> Void)? = nil) {
if isScrollInProgress || isReloadDataInProgress {
delayedExecutionClosure.append {[unowned self] in
self.reloadData(with: anchorDate, animation: animation, completionHandler: completionHandler)
}
return
}
let selectedDates = self.selectedDates
let layoutNeedsUpdating = reloadDelegateDataSource()
if layoutNeedsUpdating {
calendarViewLayout.invalidateLayout()
setupMonthInfoAndMap()
self.theSelectedIndexPaths = []
self.theSelectedDates = []
}
// Restore the selected index paths
let restoreAfterReload = {
if !selectedDates.isEmpty { // If layoutNeedsUpdating was false, layoutData would remain and re-selection wouldnt be needed
self.selectDates(selectedDates, triggerSelectionDelegate: false, keepSelectionIfMultiSelectionAllowed: true)
}
}
if let validAnchorDate = anchorDate {
// If we have a valid anchor date, this means we want to
// scroll
// This scroll should happen after the reload above
delayedExecutionClosure.append{[unowned self] in
if self.calendarViewLayout.thereAreHeaders {
self.scrollToHeaderForDate(
validAnchorDate,
triggerScrollToDateDelegate: false,
withAnimation: animation,
completionHandler: completionHandler)
} else {
self.scrollToDate(validAnchorDate,
triggerScrollToDateDelegate: false,
animateScroll: animation,
completionHandler: completionHandler)
}
if !selectedDates.isEmpty { restoreAfterReload() }
}
} else {
if !selectedDates.isEmpty { delayedExecutionClosure.append(restoreAfterReload) }
if let validCompletionHandler = completionHandler {
delayedExecutionClosure.append(validCompletionHandler)
}
}
isReloadDataInProgress = true
if !layoutNeedsUpdating { calendarViewLayout.shouldClearCacheOnInvalidate = false }
super.reloadData()
isReloadDataInProgress = false
if !delayedExecutionClosure.isEmpty {
executeDelayedTasks()
}
}
/// Reload the date of specified date-cells on the calendar-view
/// - Parameter dates: Date-cells with these specified
/// dates will be reloaded
public func reloadDates(_ dates: [Date]) {
var paths = [IndexPath]()
for date in dates {
let aPath = pathsFromDates([date])
if !aPath.isEmpty && !paths.contains(aPath[0]) {
paths.append(aPath[0])
let cellState = cellStateFromIndexPath(aPath[0])
if let validCounterPartCell = indexPathOfdateCellCounterPath(date,dateOwner: cellState.dateBelongsTo) {
paths.append(validCounterPartCell)
}
}
}
// Before reloading, set the proposal path,
// so that in the event targetContentOffset gets called. We know the path
calendarViewLayout.setMinVisibleDate()
batchReloadIndexPaths(paths)
}
/// Select a date-cell range
/// - Parameter startDate: Date to start the selection from
/// - Parameter endDate: Date to end the selection from
/// - Parameter triggerDidSelectDelegate: Triggers the delegate
/// function only if the value is set to true.
/// Sometimes it is necessary to setup some dates without triggereing
/// the delegate e.g. For instance, when youre initally setting up data
/// in your viewDidLoad
/// - Parameter keepSelectionIfMultiSelectionAllowed: This is only
/// applicable in allowedMultiSelection = true.
/// This overrides the default toggle behavior of selection.
/// If true, selected cells will remain selected.
public func selectDates(from startDate: Date, to endDate: Date, triggerSelectionDelegate: Bool = true, keepSelectionIfMultiSelectionAllowed: Bool = false) {
selectDates(generateDateRange(from: startDate, to: endDate),
triggerSelectionDelegate: triggerSelectionDelegate,
keepSelectionIfMultiSelectionAllowed: keepSelectionIfMultiSelectionAllowed)
}
/// Deselect all selected dates within a range
public func deselectDates(from start: Date, to end: Date? = nil, triggerSelectionDelegate: Bool = true) {
if selectedDates.isEmpty { return }
let end = end ?? selectedDates.last!
let dates = selectedDates.filter { $0 >= start && $0 <= end }
deselect(dates: dates, triggerSelectionDelegate: triggerSelectionDelegate)
}
/// Select a date-cells
/// - Parameter date: The date-cell with this date will be selected
/// - Parameter triggerDidSelectDelegate: Triggers the delegate function
/// only if the value is set to true.
/// Sometimes it is necessary to setup some dates without triggereing
/// the delegate e.g. For instance, when youre initally setting up data
/// in your viewDidLoad
public func selectDates(_ dates: [Date], triggerSelectionDelegate: Bool = true, keepSelectionIfMultiSelectionAllowed: Bool = false) {
if dates.isEmpty { return }
if functionIsUnsafeSafeToRun {
// If the calendar is not yet fully loaded.
// Add the task to the delayed queue
delayedExecutionClosure.append {[unowned self] in
self.selectDates(dates,
triggerSelectionDelegate: triggerSelectionDelegate,
keepSelectionIfMultiSelectionAllowed: keepSelectionIfMultiSelectionAllowed)
}
return
}
var allIndexPathsToReload: Set<IndexPath> = []
var validDatesToSelect = dates
// If user is trying to select multiple dates with
// multiselection disabled, then only select the last object
if !allowsMultipleSelection, let dateToSelect = dates.last {
validDatesToSelect = [dateToSelect]
}
for date in validDatesToSelect {
let date = calendar.startOfDay(for: date)
let components = calendar.dateComponents([.year, .month, .day], from: date)
let firstDayOfDate = calendar.date(from: components)!
// If the date is not within valid boundaries, then exit
if !(firstDayOfDate >= startOfMonthCache! && firstDayOfDate <= endOfMonthCache!) {
continue
}
let pathFromDates = self.pathsFromDates([date])
// If the date path youre searching for, doesnt exist, return
if pathFromDates.isEmpty { continue }
let sectionIndexPath = pathFromDates[0]
// Remove old selections
if self.allowsMultipleSelection == false {
// If single selection is ON
let selectedIndexPaths = self.theSelectedIndexPaths
// made a copy because the array is about to be mutated
for indexPath in selectedIndexPaths {
if indexPath != sectionIndexPath {
let pathsToReload = deselectDate(oldIndexPath: indexPath, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
}
}
// Add new selections Must be added here. If added in delegate didSelectItemAtIndexPath
let pathsToReload = selectDate(indexPath: sectionIndexPath, date: date, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
} else {
// If multiple selection is on. Multiple selection behaves differently to singleselection.
// It behaves like a toggle. unless keepSelectionIfMultiSelectionAllowed is true.
// If user wants to force selection if multiselection is enabled, then removed the selected dates from generated dates
if keepSelectionIfMultiSelectionAllowed, selectedDates.contains(date) {
// Just add it to be reloaded
allIndexPathsToReload.insert(sectionIndexPath)
} else {
if self.theSelectedIndexPaths.contains(sectionIndexPath) {
// If this cell is already selected, then deselect it
let pathsToReload = self.deselectDate(oldIndexPath: sectionIndexPath, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
} else {
// Add new selections
// Must be added here. If added in delegate didSelectItemAtIndexPath
let pathsToReload = self.selectDate(indexPath: sectionIndexPath, date: date, shouldTriggerSelecteionDelegate: triggerSelectionDelegate)
allIndexPathsToReload.formUnion(pathsToReload)
}
}
}
}
// If triggering was false, although the selectDelegates weren't
// called, we do want the cell refreshed.
// Reload to call itemAtIndexPath
if !triggerSelectionDelegate && !allIndexPathsToReload.isEmpty {
self.batchReloadIndexPaths(Array(allIndexPathsToReload))
}
}
/// Scrolls the calendar view to the next section view. It will execute a completion handler at the end of scroll animation if provided.
/// - Paramater direction: Indicates a direction to scroll
/// - Paramater animateScroll: Bool indicating if animation should be enabled
/// - Parameter triggerScrollToDateDelegate: trigger delegate if set to true
/// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation
public func scrollToSegment(_ destination: SegmentDestination,
triggerScrollToDateDelegate: Bool = true,
animateScroll: Bool = true,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)? = nil) {
if functionIsUnsafeSafeToRun {
delayedExecutionClosure.append {[unowned self] in
self.scrollToSegment(destination,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
animateScroll: animateScroll,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
}
var xOffset: CGFloat = 0
var yOffset: CGFloat = 0
let fixedScrollSize: CGFloat
if scrollDirection == .horizontal {
if calendarViewLayout.thereAreHeaders || cachedConfiguration.generateOutDates == .tillEndOfGrid {
fixedScrollSize = calendarViewLayout.sizeOfContentForSection(0)
} else {
fixedScrollSize = frame.width
}
let section = CGFloat(Int(contentOffset.x / fixedScrollSize))
xOffset = (fixedScrollSize * section)
switch destination {
case .next:
xOffset += fixedScrollSize
case .previous:
xOffset -= fixedScrollSize
case .end:
xOffset = contentSize.width - frame.width
case .start:
xOffset = 0
}
if xOffset <= 0 {
xOffset = 0
} else if xOffset >= contentSize.width - frame.width {
xOffset = contentSize.width - frame.width
}
} else {
if calendarViewLayout.thereAreHeaders {
guard let section = currentSection() else {
return
}
if (destination == .next && section + 1 >= numberOfSections(in: self)) ||
destination == .previous && section - 1 < 0 ||
numberOfSections(in: self) < 0 {
return
}
switch destination {
case .next:
scrollToHeaderInSection(section + 1, extraAddedOffset: extraAddedOffset)
case .previous:
scrollToHeaderInSection(section - 1, extraAddedOffset: extraAddedOffset)
case .start:
scrollToHeaderInSection(0, extraAddedOffset: extraAddedOffset)
case .end:
scrollToHeaderInSection(numberOfSections(in: self) - 1, extraAddedOffset: extraAddedOffset)
}
return
} else {
fixedScrollSize = frame.height
let section = CGFloat(Int(contentOffset.y / fixedScrollSize))
yOffset = (fixedScrollSize * section) + fixedScrollSize
}
if yOffset <= 0 {
yOffset = 0
} else if yOffset >= contentSize.height - frame.height {
yOffset = contentSize.height - frame.height
}
}
let rect = CGRect(x: xOffset, y: yOffset, width: frame.width, height: frame.height)
scrollTo(rect: rect,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: true,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
/// Scrolls the calendar view to the start of a section view containing a specified date.
/// - Paramater date: The calendar view will scroll to a date-cell containing this date if it exists
/// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true
/// - Paramater animateScroll: Bool indicating if animation should be enabled
/// - Paramater preferredScrollPositionIndex: Integer indicating the end scroll position on the screen.
/// This value indicates column number for Horizontal scrolling and row number for a vertical scrolling calendar
/// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation
public func scrollToDate(_ date: Date,
triggerScrollToDateDelegate: Bool = true,
animateScroll: Bool = true,
preferredScrollPosition: UICollectionViewScrollPosition? = nil,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)? = nil) {
// Ensure scrolling to date is safe to run
if functionIsUnsafeSafeToRun {
delayedExecutionClosure.append {[unowned self] in
self.scrollToDate(date,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
animateScroll: animateScroll,
preferredScrollPosition: preferredScrollPosition,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
return
}
// Set triggereing of delegate on scroll
self.triggerScrollToDateDelegate = triggerScrollToDateDelegate
// Ensure date is within valid boundary
let components = calendar.dateComponents([.year, .month, .day], from: date)
let firstDayOfDate = calendar.date(from: components)!
if !((firstDayOfDate >= self.startOfMonthCache!) && (firstDayOfDate <= self.endOfMonthCache!)) { return }
// Get valid indexPath of date to scroll to
let retrievedPathsFromDates = self.pathsFromDates([date])
if retrievedPathsFromDates.isEmpty { return }
let sectionIndexPath = self.pathsFromDates([date])[0]
// Ensure valid scroll position is set
var position: UICollectionViewScrollPosition = self.scrollDirection == .horizontal ? .left : .top
if !self.scrollingMode.pagingIsEnabled() {
if let validPosition = preferredScrollPosition {
if self.scrollDirection == .horizontal {
if validPosition == .left || validPosition == .right || validPosition == .centeredHorizontally {
position = validPosition
}
} else {
if validPosition == .top || validPosition == .bottom || validPosition == .centeredVertically {
position = validPosition
}
}
}
}
var point: CGPoint?
switch self.scrollingMode {
case .stopAtEach, .stopAtEachSection, .stopAtEachCalendarFrameWidth:
if self.scrollDirection == .horizontal || (scrollDirection == .vertical && !calendarViewLayout.thereAreHeaders) {
point = self.targetPointForItemAt(indexPath: sectionIndexPath)
}
default:
break
}
handleScroll(point: point,
indexPath: sectionIndexPath,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
isAnimationEnabled: animateScroll,
position: position,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler)
}
/// Scrolls the calendar view to the start of a section view header.
/// If the calendar has no headers registered, then this function does nothing
/// - Paramater date: The calendar view will scroll to the header of
/// a this provided date
public func scrollToHeaderForDate(_ date: Date,
triggerScrollToDateDelegate: Bool = false,
withAnimation animation: Bool = false,
extraAddedOffset: CGFloat = 0,
completionHandler: (() -> Void)? = nil) {
let path = pathsFromDates([date])
// Return if date was incalid and no path was returned
if path.isEmpty { return }
scrollToHeaderInSection(
path[0].section,
triggerScrollToDateDelegate: triggerScrollToDateDelegate,
withAnimation: animation,
extraAddedOffset: extraAddedOffset,
completionHandler: completionHandler
)
}
/// Returns the visible dates of the calendar.
/// - returns:
/// - DateSegmentInfo
public func visibleDates()-> DateSegmentInfo {
let emptySegment = DateSegmentInfo(indates: [], monthDates: [], outdates: [])
if !isCalendarLayoutLoaded {
return emptySegment
}
let cellAttributes = calendarViewLayout.visibleElements(excludeHeaders: true)
let indexPaths: [IndexPath] = cellAttributes.map { $0.indexPath }.sorted()
return dateSegmentInfoFrom(visible: indexPaths)
}
/// Returns the visible dates of the calendar.
/// - returns:
/// - DateSegmentInfo
public func visibleDates(_ completionHandler: @escaping (_ dateSegmentInfo: DateSegmentInfo) ->()) {
if functionIsUnsafeSafeToRun {
delayedExecutionClosure.append {[unowned self] in
self.visibleDates(completionHandler)
}
return
}
let retval = visibleDates()
completionHandler(retval)
}
}
|
b286a6a7b2a901a487c7a8e262d64e0e
| 48.717431 | 160 | 0.609721 | false | false | false | false |
JLCdeSwift/DangTangDemo
|
refs/heads/master
|
DanTangdemo/Classes/Classify(分类)/Model/LCCollection.swift
|
mit
|
1
|
//
// LCCollection.swift
// DanTangdemo
//
// Created by 冀柳冲 on 2017/7/5.
// Copyright © 2017年 冀柳冲. All rights reserved.
// 顶部专题合集
import UIKit
class LCCollection: NSObject {
var status:Int?
var banner_image_url :String?
var subtitle: String?
var id: Int?
var created_at: Int?
var title: String?
var cover_image_url: String?
var updated_at: Int?
var posts_count: Int?
/*dict:[String:AnyObject]
*创建字典
* [String:AnyObject]
* 代表所有的key是字符串类型的,value值则是任意类型的
*/
init(dict:[String:AnyObject]) {
super.init()
//as? 类型转换,转换不成功(或者没值)返回nil
//由于 as? 在转换失败的时候也不会出现错误,所以对于如果能确保100%会成功的转换则可使用 as!,否则使用 as?
status = dict["status"] as?Int
banner_image_url = dict["banner_image_url"] as? String
subtitle = dict["subtitle"] as? String
id = dict["id"] as? Int
created_at = dict["created_at"] as? Int
title = dict["title"] as? String
cover_image_url = dict["cover_image_url"] as? String
updated_at = dict["updated_at"] as? Int
posts_count = dict["posts_count"] as? Int
}
}
|
372b65f3806cffd98aab96fa2313cf43
| 14.697674 | 69 | 0.502222 | false | false | false | false |
r4phab/ECAB
|
refs/heads/iOS9
|
ECAB/VisualSearchLogs.swift
|
mit
|
1
|
//
// VisualSearchLogs.swift
// ECAB
//
// Created by Raphaël Bertin on 21/08/2016.
// Copyright © 2016 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import Foundation
class VisualSearchLogs : SubtestLogs{
init(selectedSession : Session) {
super.init(selectedSession : selectedSession, gameName : "Visual search")
let difficulty = session.difficulty == Difficulty.Hard.rawValue ? "hard" : "easy"
let totals = ECABLogCalculator.getVisualSearchTotals(session)
addLogSestion("Session settings")
addLogLine("\(difficulty) difficulty")
addLogLine("Exposure: \(session.speed.doubleValue)")
addLogBlank()
addLogSestion("Session results")
addLogLine("Total score: \(session.score)")
addLogLine("False positives: \(session.failureScore)")
addLogLine("Time per target found[motor] = \(totals.average.motor)")
addLogLine("Time per target found[search] = \(totals.average.search)")
addLogLine("Search time - motor time per target = \(totals.average.search - totals.average.motor)")
addLogLine("Motor 1 total = \(totals.motorOneTotal)")
addLogLine("Motor 2 total = \(totals.motorTwoTotal)")
addLogLine("Motor 3 total = \(totals.motorThreeTotal)")
addLogLine("Search 1 total = \(totals.searchOneTotal)")
addLogLine("Search 2 total = \(totals.searchTwoTotal)")
addLogLine("Search 3 total = \(totals.searchThreeTotal)")
addLogBlank()
var emptyScreenCounter = 0
addLogSestion("Moves")
for case let move as Move in session.moves {
// Caluculate screen
var screenName = ""
let screenNum = move.screenNumber.integerValue
var trainig = false
switch screenNum {
case VisualSearchEasyModeView.TrainingOne.rawValue ... VisualSearchEasyModeView.TrainingThree.rawValue:
screenName = "Training \(screenNum + 1)"
trainig = true
case VisualSearchHardModeView.TrainingOne.rawValue ... VisualSearchHardModeView.TrainingThree.rawValue:
screenName = "Training \(screenNum - 10)"
trainig = true
case VisualSearchEasyModeView.MotorOne.rawValue ... VisualSearchEasyModeView.MotorThree.rawValue:
screenName = "Motor \(screenNum - 2)"
trainig = false
case VisualSearchHardModeView.MotorOne.rawValue, VisualSearchHardModeView.MotorTwo.rawValue:
screenName = "Motor \(screenNum - 13)"
trainig = false
case VisualSearchEasyModeView.One.rawValue ... VisualSearchEasyModeView.Three.rawValue:
screenName = "Search \(screenNum - 5)"
trainig = false
case VisualSearchHardModeView.One.rawValue, VisualSearchHardModeView.Two.rawValue:
screenName = "Search \(screenNum - 15)"
trainig = false
default:
break
}
// Success or failure
let progress = move.success.boolValue == true ? "success" : "false positive"
let `repeat` = move.`repeat`.boolValue == true ? "(repeat)" : "unique"
let dateStr = smallFormatter.stringFromDate(move.date)
if move.empty.boolValue == false {
counter += 1
addLogLine("\(counter)) \(screenName) Down: \(move.row) Across: \(move.column) \(dateStr) \(progress) \(`repeat`)")
} else {
if (!trainig) {
addLogLine("\(screenName) onset \(dateStr)")
} else {
addLogLine("\(screenName)")
}
emptyScreenCounter += 1
}
}
}
}
|
80eebb6c0e8195aed10ed67a125b2bfa
| 39 | 131 | 0.556203 | false | false | false | false |
Allow2CEO/browser-ios
|
refs/heads/master
|
brave/src/BraveApp.swift
|
mpl-2.0
|
1
|
/* 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 Deferred
var kIsDevelomentBuild: Bool = {
// Needed to avoid compiler warning when #if condition executes, so no early return
var isDev = false
#if DEBUG || BETA
isDev = true
#endif
if let bid = Bundle.main.bundleIdentifier, bid.contains(".dev") {
isDev = true
}
return isDev
}()
#if !NO_FABRIC
import Mixpanel
#endif
#if !DEBUG
func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {}
#endif
private let _singleton = BraveApp()
let kAppBootingIncompleteFlag = "kAppBootingIncompleteFlag"
let kDesktopUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_12) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.0 Safari/602.1.31"
#if !TEST
func getApp() -> AppDelegate {
// assertIsMainThread("App Delegate must be accessed on main thread")
return UIApplication.shared.delegate as! AppDelegate
}
#endif
extension URL {
// The url is a local webserver url or an about url, a.k.a something we don't display to users
public func isSpecialInternalUrl() -> Bool {
assert(WebServer.sharedInstance.base.startsWith("http"))
return absoluteString.startsWith(WebServer.sharedInstance.base) || AboutUtils.isAboutURL(self)
}
}
// Any app-level hooks we need from Firefox, just add a call to here
class BraveApp {
static var isSafeToRestoreTabs = true
// If app runs for this long, clear the saved pref that indicates it is safe to restore tabs
static let kDelayBeforeDecidingAppHasBootedOk = (Int64(NSEC_PER_SEC) * 10) // 10 sec
class var singleton: BraveApp {
return _singleton
}
#if !TEST
class func getCurrentWebView() -> BraveWebView? {
return getApp().browserViewController.tabManager.selectedTab?.webView
}
#endif
fileprivate init() {
}
class func isIPhoneLandscape() -> Bool {
return UIDevice.current.userInterfaceIdiom == .phone &&
UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation)
}
class func isIPhonePortrait() -> Bool {
return UIDevice.current.userInterfaceIdiom == .phone &&
UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation)
}
class func isIPhoneX() -> Bool {
if #available(iOS 11.0, *) {
if isIPhonePortrait() && getApp().window!.safeAreaInsets.top > 0 {
return true
} else if isIPhoneLandscape() && (getApp().window!.safeAreaInsets.left > 0 || getApp().window!.safeAreaInsets.right > 0) {
return true
}
}
return false
}
class func setupCacheDefaults() {
URLCache.shared.memoryCapacity = 6 * 1024 * 1024; // 6 MB
URLCache.shared.diskCapacity = 40 * 1024 * 1024;
}
class func didFinishLaunching() {
#if !NO_FABRIC
let telemetryOn = getApp().profile!.prefs.intForKey(BraveUX.PrefKeyUserAllowsTelemetry) ?? 1 == 1
if telemetryOn {
if let dict = Bundle.main.infoDictionary, let token = dict["MIXPANEL_TOKEN"] as? String {
// note: setting this in willFinishLaunching is causing a crash, keep it in didFinish
mixpanelInstance = Mixpanel.initialize(token: token)
mixpanelInstance?.serverURL = "https://metric-proxy.brave.com"
checkMixpanelGUID()
// Eventually GCDWebServer `base` could be used with monitoring outgoing posts to /track endpoint
// this would allow data to be swapped out in realtime without the need for a full Mixpanel fork
}
}
#endif
UINavigationBar.appearance().tintColor = BraveUX.BraveOrange
}
private class func checkMixpanelGUID() {
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let unit: NSCalendar.Unit = [NSCalendar.Unit.month, NSCalendar.Unit.year]
guard let dateComps = calendar?.components(unit, from: Date()), let month = dateComps.month, let year = dateComps.year else {
print("Failed to pull date components for GUID rotation")
return
}
// We only rotate on 'odd' months
let rotationMonth = Int(round(Double(month) / 2.0) * 2 - 1)
// The key for the last reset date
let resetDate = "\(rotationMonth)-\(year)"
let mixpanelGuidKey = "kMixpanelGuid"
let lastResetDate = getApp().profile!.prefs.stringForKey(mixpanelGuidKey)
if lastResetDate != resetDate {
// We have not rotated for this iteration (do not care _how_ far off it is, just that it is not the same)
mixpanelInstance?.distinctId = UUID().uuidString
getApp().profile?.prefs.setString(resetDate, forKey: mixpanelGuidKey)
}
}
// Be aware: the Prefs object has not been created yet
class func willFinishLaunching_begin() {
BraveApp.setupCacheDefaults()
Foundation.URLProtocol.registerClass(URLProtocol);
NotificationCenter.default.addObserver(BraveApp.singleton,
selector: #selector(BraveApp.didEnterBackground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(BraveApp.singleton,
selector: #selector(BraveApp.willEnterForeground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(BraveApp.singleton,
selector: #selector(BraveApp.memoryWarning(_:)), name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil)
#if !TEST
// these quiet the logging from the core of fx ios
// GCDWebServer.setLogLevel(5)
Logger.syncLogger.setup(level: .none)
Logger.browserLogger.setup(level: .none)
#endif
#if DEBUG
// desktop UA for testing
// let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
// defaults.registerDefaults(["UserAgent": kDesktopUserAgent])
#endif
}
// Prefs are created at this point
class func willFinishLaunching_end() {
BraveApp.isSafeToRestoreTabs = BraveApp.getPrefs()?.stringForKey(kAppBootingIncompleteFlag) == nil
BraveApp.getPrefs()?.setString("remove me when booted", forKey: kAppBootingIncompleteFlag)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(BraveApp.kDelayBeforeDecidingAppHasBootedOk) / Double(NSEC_PER_SEC), execute: {
BraveApp.getPrefs()?.removeObjectForKey(kAppBootingIncompleteFlag)
})
let args = ProcessInfo.processInfo.arguments
if args.contains("BRAVE-TEST-CLEAR-PREFS") {
BraveApp.getPrefs()!.clearAll()
}
if args.contains("BRAVE-TEST-NO-SHOW-INTRO") {
BraveApp.getPrefs()!.setInt(1, forKey: IntroViewControllerSeenProfileKey)
}
if args.contains("BRAVE-TEST-SHOW-OPT-IN") {
BraveApp.getPrefs()!.removeObjectForKey(BraveUX.PrefKeyOptInDialogWasSeen)
}
// Be careful, running it in production will result in destroying all bookmarks
if args.contains("BRAVE-DELETE-BOOKMARKS") {
Bookmark.removeAll()
}
if args.contains("BRAVE-UI-TEST") || AppConstants.IsRunningTest {
// Maybe we will need a specific flag to keep tabs for restoration testing
BraveApp.isSafeToRestoreTabs = false
if args.filter({ $0.startsWith("BRAVE") }).count == 1 || AppConstants.IsRunningTest { // only contains 1 arg
BraveApp.getPrefs()!.setInt(1, forKey: IntroViewControllerSeenProfileKey)
BraveApp.getPrefs()!.setInt(1, forKey: BraveUX.PrefKeyOptInDialogWasSeen)
}
}
if args.contains("LOCALE=RU") {
AdBlocker.singleton.currentLocaleCode = "ru"
}
AdBlocker.singleton.startLoading()
SafeBrowsing.singleton.networkFileLoader.loadData()
TrackingProtection.singleton.networkFileLoader.loadData()
HttpsEverywhere.singleton.networkFileLoader.loadData()
#if !TEST
PrivateBrowsing.singleton.startupCheckIfKilledWhileInPBMode()
CookieSetting.setupOnAppStart()
PasswordManagerButtonSetting.setupOnAppStart()
//BlankTargetLinkHandler.updatedEnabledState()
#endif
Domain.loadShieldsIntoMemory {
guard let shieldState = getApp().tabManager.selectedTab?.braveShieldStateSafeAsync.get() else { return }
if let wv = getCurrentWebView(), let url = wv.URL?.normalizedHost, let dbState = BraveShieldState.perNormalizedDomain[url], shieldState.isNotSet() {
// on init, the webview's shield state doesn't match the db
getApp().tabManager.selectedTab?.braveShieldStateSafeAsync.set(dbState)
wv.reloadFromOrigin()
}
}
}
// This can only be checked ONCE, the flag is cleared after this.
// This is because BrowserViewController asks this question after the startup phase,
// when tabs are being created by user actions. So without more refactoring of the
// Firefox logic, this is the simplest solution.
class func shouldRestoreTabs() -> Bool {
let ok = BraveApp.isSafeToRestoreTabs
BraveApp.isSafeToRestoreTabs = false
return ok
}
@objc func memoryWarning(_: Notification) {
URLCache.shared.memoryCapacity = 0
BraveApp.setupCacheDefaults()
}
@objc func didEnterBackground(_: Notification) {
}
@objc func willEnterForeground(_ : Notification) {
}
class func shouldHandleOpenURL(_ components: URLComponents) -> Bool {
// TODO look at what x-callback is for
let handled = components.scheme == "brave" || components.scheme == "brave-x-callback"
return handled
}
class func getPrefs() -> NSUserDefaultsPrefs? {
return getApp().profile?.prefs
}
static func showErrorAlert(title: String, error: String) {
postAsyncToMain(0) { // this utility function can be called from anywhere
UIAlertView(title: title, message: error, delegate: nil, cancelButtonTitle: "Close").show()
}
}
static func statusBarHeight() -> CGFloat {
if UIScreen.main.traitCollection.verticalSizeClass == .compact {
return 0
}
return 20
}
static var isPasswordManagerInstalled: Bool?
static func is3rdPartyPasswordManagerInstalled(_ refreshLookup: Bool) -> Deferred<Bool> {
let deferred = Deferred<Bool>()
if refreshLookup || isPasswordManagerInstalled == nil {
postAsyncToMain {
isPasswordManagerInstalled = OnePasswordExtension.shared().isAppExtensionAvailable()
deferred.fill(isPasswordManagerInstalled!)
}
} else {
deferred.fill(isPasswordManagerInstalled!)
}
return deferred
}
}
|
5ab002c3ca9a6f331b46eae72b7dc920
| 39.034722 | 198 | 0.647788 | false | false | false | false |
up-n-down/Up-N-Down
|
refs/heads/master
|
Git Service/CommitHandler.swift
|
gpl-3.0
|
1
|
//
// CommitHandler.swift
// Up-N-Down
//
// Created by Thomas Paul Mann on 05/12/2016.
// Copyright © 2016 Up-N-Down. All rights reserved.
//
import Foundation
import ObjectiveGit
struct CommitHandler {
// MARK: - Properties
let repository: GTRepository
// MARK: - API
func commit(message: String) throws {
do {
let head = try repository.headReference()
let index = try repository.index()
let tree = try index.writeTree()
guard
let parentCommit = parentCommit,
let signature = GTSignature(name: "Thomas Paul Mann", email: "[email protected]", time: Date())
else {
return
}
try repository.createCommit(with: tree,
message: message,
author: signature,
committer: signature,
parents: [parentCommit],
updatingReferenceNamed: head.name)
}
}
/// Returns the parent commit for the current head reference.
private var parentCommit: GTCommit? {
do {
let enumerator = try GTEnumerator(repository: repository)
let head = try repository.headReference()
try enumerator.pushSHA(head.targetOID.sha)
return enumerator.nextObject() as? GTCommit
} catch _ {
return nil
}
}
}
|
44a9e270d3511ba4ee06841abd7136b1
| 25.793103 | 115 | 0.514157 | false | false | false | false |
Andgfaria/MiniGitClient-iOS
|
refs/heads/develop
|
CocoaPods/Pods/R.swift.Library/Library/UIKit/TypedStoryboardSegueInfo+UIStoryboardSegue.swift
|
apache-2.0
|
24
|
//
// TypedStoryboardSegueInfo+UIStoryboardSegue.swift
// R.swift Library
//
// Created by Mathijs Kadijk on 06-12-15.
// From: https://github.com/mac-cain13/R.swift.Library
// License: MIT License
//
import Foundation
import UIKit
extension TypedStoryboardSegueInfo {
/**
Returns typed information about the given segue, fails if the segue types don't exactly match types.
- returns: A newly initialized TypedStoryboardSegueInfo object or nil.
*/
public init?<SegueIdentifier: StoryboardSegueIdentifierType>(segueIdentifier: SegueIdentifier, segue: UIStoryboardSegue)
where SegueIdentifier.SegueType == Segue, SegueIdentifier.SourceType == Source, SegueIdentifier.DestinationType == Destination
{
guard let identifier = segue.identifier,
let source = segue.source as? SegueIdentifier.SourceType,
let destination = segue.destination as? SegueIdentifier.DestinationType,
let segue = segue as? SegueIdentifier.SegueType, identifier == segueIdentifier.identifier
else {
return nil
}
self.segue = segue
self.identifier = identifier
self.source = source
self.destination = destination
}
}
|
2f1a4618585fa11f580db9beecee7afc
| 32.371429 | 130 | 0.743151 | false | false | false | false |
Fenrikur/ef-app_ios
|
refs/heads/master
|
Eurofurence/Activity/Events/Intents/SystemEventInteractionsRecorder.swift
|
mit
|
1
|
import EurofurenceIntentDefinitions
import EurofurenceModel
struct SystemEventInteractionsRecorder: EventInteractionRecorder {
var eventsService: EventsService
var eventIntentDonor: EventIntentDonor
var activityFactory: ActivityFactory
func makeInteraction(for event: EventIdentifier) -> Interaction? {
guard let entity = eventsService.fetchEvent(identifier: event) else { return nil }
let intentDefinition = ViewEventIntentDefinition(identifier: event, eventName: entity.title)
eventIntentDonor.donateEventIntent(definition: intentDefinition)
let activityTitle = String.viewEvent(named: entity.title)
let url = entity.makeContentURL()
let activity = activityFactory.makeActivity(type: "org.eurofurence.activity.view-event", title: activityTitle, url: url)
activity.markEligibleForPublicIndexing()
return ActivityInteraction(activity: activity)
}
}
|
8ce6fe1836635be228d19a0c93f6ddaf
| 39.666667 | 128 | 0.735656 | false | false | false | false |
menlatin/jalapeno
|
refs/heads/master
|
digeocache/mobile/iOS/diGeo/diGeo/DGCConstants.swift
|
mit
|
1
|
//
// DGCConstants.swift
// diGeo
//
// Created by Elliott Richerson on 3/11/15.
// Copyright (c) 2015 Elliott Richerson. All rights reserved.
//
import Foundation
let URL_ELLIOTT: String = "http://elliott.webfactional.com/"
//let URL_LOCAL: String = "http://localhost:3000"
// API Operations
// GET
let GET_FEED: String = "events"
let GET_CATEGORIES: String = "categories"
// POST
// Singleton
private let _DGCConstantsSharedInstance = DGCConstants()
class DGCConstants {
var isTestEnvironment: Bool = true
var host: String = ""
var requestManager: String = ""
class var sharedInstance: DGCConstants {
return _DGCConstantsSharedInstance
}
}
|
ca1514a99308728a03a52190672a862b
| 19.323529 | 62 | 0.686957 | false | false | false | false |
Holmusk/HMRequestFramework-iOS
|
refs/heads/master
|
HMRequestFramework-FullDemo/controller/profile/UserProfileVC.swift
|
apache-2.0
|
1
|
//
// UserProfileVC.swift
// HMRequestFramework-FullDemo
//
// Created by Hai Pham on 17/1/18.
// Copyright © 2018 Holmusk. All rights reserved.
//
import HMReactiveRedux
import HMRequestFramework
import RxDataSources
import RxSwift
import SwiftFP
import SwiftUIUtilities
import UIKit
public final class UserProfileVC: UIViewController {
public typealias Section = SectionModel<String,UserInformation>
public typealias DataSource = RxTableViewSectionedReloadDataSource<Section>
@IBOutlet fileprivate weak var nameLbl: UILabel!
@IBOutlet fileprivate weak var ageLbl: UILabel!
@IBOutlet fileprivate weak var visibleLbl: UILabel!
@IBOutlet fileprivate weak var tableView: UITableView!
@IBOutlet fileprivate weak var persistBtn: UIButton!
fileprivate var insertUserBtn: UIBarButtonItem? {
return navigationItem.rightBarButtonItem
}
fileprivate let disposeBag = DisposeBag()
fileprivate let decorator = UserProfileVCDecorator()
public var viewModel: UserProfileViewModel?
override public func viewDidLoad() {
super.viewDidLoad()
setupViews(self)
bindViewModel(self)
}
}
extension UserProfileVC: UITableViewDelegate {
public func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return 1
}
public func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
public func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = .black
return view
}
public func tableView(_ tableView: UITableView,
viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
}
public extension UserProfileVC {
fileprivate func setupViews(_ controller: UserProfileVC) {
guard let tableView = controller.tableView else { return }
tableView.registerNib(UserTextCell.self)
controller.navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Insert new user",
style: .done,
target: nil,
action: nil)
}
fileprivate func setupDataSource(_ controller: UserProfileVC) -> DataSource {
let dataSource = DataSource(configureCell: {[weak controller] in
if let controller = controller {
return controller.configureCells($0, $1, $2, $3, controller)
} else {
return UITableViewCell()
}
})
dataSource.canMoveRowAtIndexPath = {(_, _) in false}
dataSource.canEditRowAtIndexPath = {(_, _) in false}
return dataSource
}
fileprivate func configureCells(_ source: TableViewSectionedDataSource<Section>,
_ tableView: UITableView,
_ indexPath: IndexPath,
_ item: Section.Item,
_ controller: UserProfileVC)
-> UITableViewCell
{
guard let vm = controller.viewModel else { return UITableViewCell() }
let decorator = controller.decorator
if
let cell = tableView.deque(UserTextCell.self, at: indexPath),
let cm = vm.vmForUserTextCell(item)
{
cell.viewModel = cm
cell.decorate(decorator, item)
return cell
} else {
return UITableViewCell()
}
}
}
public extension UserProfileVC {
fileprivate func bindViewModel(_ controller: UserProfileVC) {
guard
let vm = controller.viewModel,
let tableView = controller.tableView,
let insertUserBtn = controller.insertUserBtn,
let persistBtn = controller.persistBtn,
let nameLbl = controller.nameLbl,
let ageLbl = controller.ageLbl,
let visibleLbl = controller.visibleLbl
else {
return
}
vm.setupBindings()
let disposeBag = controller.disposeBag
let dataSource = controller.setupDataSource(controller)
tableView.rx.setDelegate(controller).disposed(by: disposeBag)
Observable.just(UserInformation.allValues())
.map({SectionModel(model: "", items: $0)})
.map({[$0]})
.observeOnMain()
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
vm.userNameStream()
.mapNonNilOrElse({$0.value}, "No information yet")
.observeOnMain()
.bind(to: nameLbl.rx.text)
.disposed(by: disposeBag)
vm.userAgeStream()
.mapNonNilOrElse({$0.value}, "No information yet")
.observeOnMain()
.bind(to: ageLbl.rx.text)
.disposed(by: disposeBag)
vm.userVisibilityStream()
.mapNonNilOrElse({$0.value}, "No information yet")
.observeOnMain()
.bind(to: visibleLbl.rx.text)
.disposed(by: disposeBag)
insertUserBtn.rx.tap
.throttle(0.3, scheduler: MainScheduler.instance)
.bind(to: vm.insertUserTrigger())
.disposed(by: disposeBag)
persistBtn.rx.tap
.throttle(0.3, scheduler: MainScheduler.instance)
.bind(to: vm.persistDataTrigger())
.disposed(by: disposeBag)
}
}
public struct UserProfileVCDecorator: UserTextCellDecoratorType {
public func inputFieldKeyboard(_ info: UserInformation) -> UIKeyboardType {
switch info {
case .age: return .numberPad
case .name: return .default
}
}
}
public struct UserProfileModel {
fileprivate let provider: SingletonType
public init(_ provider: SingletonType) {
self.provider = provider
}
public func dbUserStream() -> Observable<Try<User>> {
return provider.trackedObjectManager.dbUserStream()
}
public func updateUserInDB(_ user: Try<User>) -> Observable<Try<Void>> {
let requestManager = provider.dbRequestManager
let prev = user.map({[$0]})
let qos: DispatchQoS.QoSClass = .background
return requestManager.upsertInMemory(prev, qos).map({$0.map({_ in})})
}
public func persistToDB<Prev>(_ prev: Try<Prev>) -> Observable<Try<Void>> {
let requestManager = provider.dbRequestManager
let qos: DispatchQoS.QoSClass = .background
return requestManager.persistToDB(prev, qos)
}
public func userName(_ user: User) -> String {
return "Name: \(user.name.getOrElse(""))"
}
public func userAge(_ user: User) -> String {
return "Age: \(user.age.getOrElse(0))"
}
public func userVisibility(_ user: User) -> String {
return "Visibility: \(user.visible.map({$0.boolValue}).getOrElse(false))"
}
}
public struct UserProfileViewModel {
fileprivate let provider: SingletonType
fileprivate let model: UserProfileModel
fileprivate let disposeBag: DisposeBag
fileprivate let insertUser: PublishSubject<Void>
fileprivate let persistData: PublishSubject<Void>
public init(_ provider: SingletonType, _ model: UserProfileModel) {
self.provider = provider
self.model = model
disposeBag = DisposeBag()
insertUser = PublishSubject()
persistData = PublishSubject()
}
public func setupBindings() {
let provider = self.provider
let disposeBag = self.disposeBag
let model = self.model
let actionTrigger = provider.reduxStore.actionTrigger()
let insertTriggered = userOnInsertTriggered().share(replay: 1)
let insertPerformed = insertTriggered
.map(Try.success)
.flatMapLatest({model.updateUserInDB($0)})
.share(replay: 1)
let persistTriggered = persistDataStream().share(replay: 1)
let persistPerformed = persistTriggered
.map(Try.success)
.flatMapLatest({model.persistToDB($0)})
.share(replay: 1)
Observable<Error>
.merge(insertPerformed.mapNonNilOrEmpty({$0.error}),
persistPerformed.mapNonNilOrEmpty({$0.error}))
.map(GeneralReduxAction.Error.Display.updateShowError)
.observeOnMain()
.bind(to: actionTrigger)
.disposed(by: disposeBag)
Observable<Bool>
.merge(insertTriggered.map({_ in true}),
insertPerformed.map({_ in false}),
persistTriggered.map({_ in true}),
persistPerformed.map({_ in false}))
.map(GeneralReduxAction.Progress.Display.updateShowProgress)
.observeOnMain()
.bind(to: actionTrigger)
.disposed(by: disposeBag)
}
public func vmForUserTextCell(_ info: UserInformation) -> UserTextCellViewModel? {
let provider = self.provider
switch info {
case .age:
let model = UserAgeTextCellModel(provider)
return UserTextCellViewModel(provider, model)
case .name:
let model = UserNameTextCellModel(provider)
return UserTextCellViewModel(provider, model)
}
}
public func userNameStream() -> Observable<Try<String>> {
let model = self.model
return model.dbUserStream().map({$0.map({model.userName($0)})})
}
public func userAgeStream() -> Observable<Try<String>> {
let model = self.model
return model.dbUserStream().map({$0.map({model.userAge($0)})})
}
public func userVisibilityStream() -> Observable<Try<String>> {
let model = self.model
return model.dbUserStream().map({$0.map({model.userVisibility($0)})})
}
public func insertUserTrigger() -> AnyObserver<Void> {
return insertUser.asObserver()
}
public func insertUserStream() -> Observable<Void> {
return insertUser.asObservable()
}
public func userOnInsertTriggered() -> Observable<User> {
return insertUserStream().map({User.builder()
.with(name: "Hai Pham - \(String.random(withLength: 5))")
.with(id: UUID().uuidString)
.with(age: NSNumber(value: Int.randomBetween(10, 99)))
.with(visible: NSNumber(value: true))
.build()
})
}
public func persistDataTrigger() -> AnyObserver<Void> {
return persistData.asObserver()
}
public func persistDataStream() -> Observable<Void> {
return persistData.asObservable()
}
}
|
83dc8d830d24693ccfa40c0905221fed
| 28.847561 | 84 | 0.676404 | false | false | false | false |
anzfactory/QiitaCollection
|
refs/heads/master
|
QiitaCollection/String+App.swift
|
mit
|
1
|
//
// String+App.swift
// QiitaCollection
//
// Created by ANZ on 2015/03/12.
// Copyright (c) 2015年 anz. All rights reserved.
//
import UIKit
extension String {
// http://qiita.com/edo_m18/items/54b6d6f5f562df55ac9b
func removeExceptionUnicode() -> String {
let exceptioUnicodes: [String] = [
"0900", "0901", "0902", "0903",
"093a", "093b", "093c", "093e", "093f",
"0940", "0941", "0942", "0943", "0944", "0945", "0946", "0947", "0948", "0949",
"094a", "094b", "094c", "094d", "094e", "094f",
"0953", "0954", "0955", "0956", "0957",
"0962", "0963"
]
let exceptionPattern: NSMutableString = NSMutableString()
for unicode in exceptioUnicodes {
exceptionPattern.appendFormat("\\u%@|", unicode)
}
var error: NSError? = nil
let regex: NSRegularExpression = NSRegularExpression(pattern: exceptionPattern as String, options: NSRegularExpressionOptions(rawValue: 0), error: &error)!
let target: NSMutableString = NSMutableString(string: self)
regex.replaceMatchesInString(target, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, target.length), withTemplate: "")
return String(target)
}
}
|
d288c1ba9965c8e3f8a28a3c91026963
| 33.631579 | 163 | 0.588593 | false | false | false | false |
iosdevelopershq/Camille
|
refs/heads/master
|
Sources/CamilleServices/Karma/KarmaService+Adjustments.swift
|
mit
|
1
|
import Chameleon
import Foundation
private typealias PartialUpdate = (user: ModelPointer<User>, operation: Operation)
private typealias Update = (ModelPointer<User>, (current: Int, change: Int))
private enum Operation: String {
case plus = "++"
case minus = "--"
func update(value: Int) -> Int {
switch self {
case .plus: return value + 1
case .minus: return value - 1
}
}
}
extension KarmaService {
func adjust(bot: SlackBot, message: MessageDecorator) throws {
guard !message.isIM else { return }
func partialUpdate(from link: MessageDecorator.Link<ModelPointer<User>>) throws -> PartialUpdate? {
guard try link.value.id != message.sender().id else { return nil }
let text = String(message.text[link.range.upperBound...])
let possibleOperation = text
.trimCharacters(in: [" ", ">", ":"])
.components(seperatedBy: [" ", "\n"])
.first ?? ""
guard let operation = Operation(rawValue: possibleOperation)
else { return nil }
return (link.value, operation)
}
func consolidatePartialUpdates(for user: ModelPointer<User>, partials: [PartialUpdate]) throws -> Update {
let count: Int = try storage.get(key: user.id, from: Keys.namespace, or: 0)
let change = partials.reduce(0) { $1.operation.update(value: $0) }
return (user, (count, change))
}
let updates = try message
.mentionedUsers
.flatMap(partialUpdate)
.group(by: { $0.user })
.map(consolidatePartialUpdates)
.filter { $0.value.change != 0 }
guard !updates.isEmpty else { return }
let response = try message.respond()
for (user, data) in updates {
let newTotal = data.current + data.change
storage.set(value: newTotal, forKey: user.id, in: Keys.namespace)
let comment = (data.change > 0
? config.positiveComments.randomElement
: config.negativeComments.randomElement
) ?? ""
response
.text([user, comment, newTotal])
.newLine()
}
try bot.send(response.makeChatMessage())
}
}
|
65db8a1ab0cdfe4844a1a137667db5c7
| 31.486111 | 114 | 0.569047 | false | false | false | false |
lixiangzhou/ZZLib
|
refs/heads/master
|
Source/ZZExtension/ZZNSExtension/Timer+ZZExtension.swift
|
mit
|
1
|
//
// Timer+ZZExtension.swift
// ZZLib
//
// Created by lxz on 2018/6/22.
// Copyright © 2018年 lixiangzhou. All rights reserved.
//
import Foundation
public extension Timer {
class ZZSafeTarget {
weak var target: AnyObject?
var selector: Selector?
weak var timer: Timer?
@objc func fire() {
if let target = target {
_ = target.perform(selector, with: timer?.userInfo)
} else {
timer?.invalidate()
}
}
}
@discardableResult
class func zz_scheduledTimer(timeInterval ti: TimeInterval, target aTarget: Any, selector aSelector: Selector, userInfo: Any?, repeats yesOrNo: Bool) -> Timer {
let safeTarget = ZZSafeTarget()
safeTarget.target = aTarget as AnyObject
safeTarget.selector = aSelector
safeTarget.timer = Timer.scheduledTimer(timeInterval: ti, target: safeTarget, selector: #selector(ZZSafeTarget.fire), userInfo: userInfo, repeats: yesOrNo)
return safeTarget.timer!
}
}
|
95a6dfdd11108a052a63234856760051
| 29.457143 | 164 | 0.621013 | false | false | false | false |
paulz/ImageCoordinateSpace
|
refs/heads/master
|
Example/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ImageCoordinateSpace
//
// Created by Paul Zabelin on 2/13/16.
//
//
import UIKit
import ImageCoordinateSpace
extension UIView.ContentMode {
func next() -> UIView.ContentMode {
return UIView.ContentMode(rawValue: rawValue + 1)!
}
}
extension UIView {
func nextContentModeSkipping(_ skip: ContentMode) {
let mode = contentMode.next()
contentMode = mode == skip ? mode.next() : mode
}
}
class ViewController: UIViewController {
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var overlayImageView: UIImageView!
// Placement is determined by SVG
// See: https://github.com/paulz/ImageCoordinateSpace/blob/master/Example/Visual.playground/Resources/overlayed.svg?short_path=993f69a#L10
// <image id="hello" sketch:type="MSBitmapLayer" x="321" y="102" width="63" height="64" xlink:href="hello.png"></image>
let placement = CGRect(x: 321, y: 102, width: 63, height: 64)
override func viewDidLayoutSubviews() {
updateOvelayPositionAnimated()
}
}
private extension ViewController {
@IBAction func didTap(_ sender: AnyObject) {
showNextContentMode()
}
func showNextContentMode() {
backgroundImageView.nextContentModeSkipping(.redraw)
updateOvelayPositionAnimated()
}
func updateOvelayPosition() {
overlayImageView.frame = backgroundImageView.contentSpace().convert(placement, to: view)
}
func updateOvelayPositionAnimated() {
UIView.animate(withDuration: 0.5, animations: updateOvelayPosition)
}
}
|
ea63672372efba38915b11ce76f07139
| 28.254545 | 145 | 0.69422 | false | false | false | false |
Rain-Li/CLCycleScrollView
|
refs/heads/master
|
Pod/Classes/CommonDef.swift
|
mit
|
1
|
//
// CommonDef.swift
// Pods
//
// Created by Rain on 16/3/9.
//
//
import Foundation
// MARK: - 全局属性
let screen_width = UIScreen.mainScreen().bounds.size.width
let screen_height = UIScreen.mainScreen().bounds.size.height
let statusBar_height:CGFloat = 20;
let navigationBar_height:CGFloat = 44
let top_height:CGFloat = 64
let tabBar_height:CGFloat = 49
// MARK: - 全局方法
|
5e25d35dc4618c5952bf0449658b60a8
| 18.842105 | 60 | 0.712766 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
UICollectionViewLayout/MagazineLayout-master/Example/MagazineLayoutExample/Views/Cell.swift
|
mit
|
1
|
// Created by bryankeller on 11/30/18.
// Copyright © 2018 Airbnb, 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 MagazineLayout
import UIKit
final class Cell: MagazineLayoutCollectionViewCell {
// MARK: Lifecycle
override init(frame: CGRect) {
label = UILabel(frame: .zero)
super.init(frame: frame)
label.font = UIFont.systemFont(ofSize: 24)
label.textColor = .white
label.numberOfLines = 0
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),
label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
label.topAnchor.constraint(equalTo: contentView.topAnchor),
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
override func prepareForReuse() {
super.prepareForReuse()
label.text = nil
contentView.backgroundColor = nil
}
func set(_ itemInfo: ItemInfo) {
label.text = itemInfo.text
contentView.backgroundColor = itemInfo.color
}
// MARK: Private
private let label: UILabel
}
|
1230292205f0b3268f4505a5199abd01
| 27.46875 | 89 | 0.728321 | false | false | false | false |
Khan/Cartography
|
refs/heads/master
|
Carthage/Checkouts/Cartography/Cartography/Property.swift
|
mit
|
4
|
//
// Property.swift
// Cartography
//
// Created by Robert Böhnke on 17/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol Property {
var attribute: NSLayoutAttribute { get }
var context: Context { get }
var view: View { get }
}
// MARK: Equality
/// Properties conforming to this protocol can use the `==` operator with
/// numerical constants.
public protocol NumericalEquality : Property { }
/// Declares a property equal to a numerical constant.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The numerical constant.
///
/// - returns: An `NSLayoutConstraint`.
///
public func == (lhs: NumericalEquality, rhs: CGFloat) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs))
}
/// Properties conforming to this protocol can use the `==` operator with other
/// properties of the same type.
public protocol RelativeEquality : Property { }
/// Declares a property equal to a the result of an expression.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The expression.
///
/// - returns: An `NSLayoutConstraint`.
///
public func == <P: RelativeEquality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients[0], to: rhs.value)
}
/// Declares a property equal to another property.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
public func == <P: RelativeEquality>(lhs: P, rhs: P) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs)
}
// MARK: Inequality
/// Properties conforming to this protocol can use the `<=` and `>=` operators
/// with numerical constants.
public protocol NumericalInequality : Property { }
/// Declares a property less than or equal to a numerical constant.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The numerical constant.
///
/// - returns: An `NSLayoutConstraint`.
///
public func <= (lhs: NumericalInequality, rhs: CGFloat) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs), relation: NSLayoutRelation.LessThanOrEqual)
}
/// Declares a property greater than or equal to a numerical constant.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The numerical constant.
///
/// - returns: An `NSLayoutConstraint`.
///
public func >= (lhs: NumericalInequality, rhs: CGFloat) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs), relation: NSLayoutRelation.GreaterThanOrEqual)
}
/// Properties conforming to this protocol can use the `<=` and `>=` operators
/// with other properties of the same type.
public protocol RelativeInequality : Property { }
/// Declares a property less than or equal to another property.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
public func <= <P: RelativeInequality>(lhs: P, rhs: P) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs, relation: NSLayoutRelation.LessThanOrEqual)
}
/// Declares a property greater than or equal to another property.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
public func >= <P: RelativeInequality>(lhs: P, rhs: P) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, to: rhs, relation: NSLayoutRelation.GreaterThanOrEqual)
}
/// Declares a property less than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
public func <= <P: RelativeInequality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients[0], to: rhs.value, relation: NSLayoutRelation.LessThanOrEqual)
}
/// Declares a property greater than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated view will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
public func >= <P: RelativeInequality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients[0], to: rhs.value, relation: NSLayoutRelation.GreaterThanOrEqual)
}
// MARK: Addition
public protocol Addition : Property { }
public func + <P: Addition>(c: CGFloat, rhs: P) -> Expression<P> {
return Expression(rhs, [ Coefficients(1, c) ])
}
public func + <P: Addition>(lhs: P, rhs: CGFloat) -> Expression<P> {
return rhs + lhs
}
public func + <P: Addition>(c: CGFloat, rhs: Expression<P>) -> Expression<P> {
return Expression(rhs.value, rhs.coefficients.map { $0 + c })
}
public func + <P: Addition>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return rhs + lhs
}
public func - <P: Addition>(c: CGFloat, rhs: P) -> Expression<P> {
return Expression(rhs, [ Coefficients(1, -c) ])
}
public func - <P: Addition>(lhs: P, rhs: CGFloat) -> Expression<P> {
return rhs - lhs
}
public func - <P: Addition>(c: CGFloat, rhs: Expression<P>) -> Expression<P> {
return Expression(rhs.value, rhs.coefficients.map { $0 - c})
}
public func - <P: Addition>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return rhs - lhs
}
#if os(iOS) || os(tvOS)
public func + (lhs: LayoutSupport, c : CGFloat) -> Expression<LayoutSupport> {
return Expression<LayoutSupport>(lhs, [Coefficients(1, c)])
}
public func - (lhs: LayoutSupport, c : CGFloat) -> Expression<LayoutSupport> {
return lhs + (-c)
}
#endif
// MARK: Multiplication
public protocol Multiplication : Property { }
public func * <P: Multiplication>(m: CGFloat, rhs: Expression<P>) -> Expression<P> {
return Expression(rhs.value, rhs.coefficients.map { $0 * m })
}
public func * <P: Multiplication>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return rhs * lhs
}
public func * <P: Multiplication>(m: CGFloat, rhs: P) -> Expression<P> {
return Expression(rhs, [ Coefficients(m, 0) ])
}
public func * <P: Multiplication>(lhs: P, rhs: CGFloat) -> Expression<P> {
return rhs * lhs
}
public func / <P: Multiplication>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> {
return lhs * (1 / rhs)
}
public func / <P: Multiplication>(lhs: P, rhs: CGFloat) -> Expression<P> {
return lhs * (1 / rhs)
}
|
7d262401a0d9f6cec60a47b104f19dbb
| 33.395455 | 138 | 0.690895 | false | false | false | false |
rhx/gir2swift
|
refs/heads/main
|
Sources/libgir2swift/models/gir elements/GirClass.swift
|
bsd-2-clause
|
1
|
//
// File.swift
//
//
// Created by Mikoláš Stuchlík on 17.11.2020.
//
import SwiftLibXML
extension GIR {
/// a class data type record
public class Class: Record {
/// String representation of `Class`es
public override var kind: String { return "Class" }
/// parent class name
public let parent: String
/// return the parent type of the given class
public override var parentType: Record? {
guard !parent.isEmpty else { return nil }
return GIR.knownDataTypes[parent] as? GIR.Record
}
/// return the top level ancestor type of the given class
public override var rootType: Record {
guard parent != "" else { return self }
guard let p = GIR.knownDataTypes[parent] as? GIR.Record else { return self }
return p.rootType
}
/// Initialiser to construct a class type from XML
/// - Parameters:
/// - node: `XMLElement` to construct this constant from
/// - index: Index within the siblings of the `node`
override init(node: XMLElement, at index: Int) {
var parent = node.attribute(named: "parent") ?? ""
if parent.isEmpty {
parent = node.children.lazy.filter { $0.name == "prerequisite" }.first?.attribute(named: "name") ?? ""
}
self.parent = parent
super.init(node: node, at: index)
}
}
}
|
c8809830fd12769f41a5d51ed35aa9d3
| 31.866667 | 119 | 0.571332 | false | false | false | false |
liuweihaocool/iOS_06_liuwei
|
refs/heads/master
|
新浪微博_swift/新浪微博_swift/class/Main/Main/Controller/LWMainTarbarController.swift
|
apache-2.0
|
1
|
//
// LWMainTabController.swift
// 新浪微博_swift
//
// Created by liuwei on 15/11/23.
// Copyright © 2015年 liuwei. All rights reserved.
//
import UIKit
class LWMainTarbarController: UITabBarController {
/// 跳转控制器
func composeClick() {
// 创建一个控制器
let LWCC = LWCompareController()
// 给创建的控制器包装一个 UINavigationController
let Nav = UINavigationController(rootViewController: LWCC);
presentViewController(Nav, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// let newTabBar = LWTabbar()
// setValue(newTabBar, forKey: "tabBar")
// newTabBar.composeButton.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
tabBar.tintColor = UIColor.orangeColor()
// 创建homeVC控制器并添加 到tabbar
let homeVC = LWHomeTabController()
addChildViewController(homeVC, title: "首页", imageName: "tabbar_home")
// 创建messageVC控制器并且添加到tarBarVC上
let messageVC = LWMessageTabController()
addChildViewController(messageVC, title: "消息", imageName: "tabbar_message_center")
// 占位控制器
addChildViewController(UIViewController())
// 创建profileVC控制器并且添加到tarBarVC 上
let profileVC = LWProfileTabController()
addChildViewController(profileVC, title: "我", imageName: "tabbar_profile")
// 创建 discover 控制器并添加到 tarBarVC
let discoverVC = LWDiscoverTabController()
addChildViewController(discoverVC, title: "发现", imageName: "tabbar_discover")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let width = tabBar.bounds.size.width*0.2
let frame = CGRect(x: 2 * width - 5 , y: 0, width: width + 10, height: tabBar.bounds.height)
composeButton.frame = frame
}
/**
创建tarBar的子窗口
:param: contoller 要传的控制器
:param: title 标题
:param: imageName 图片名称
*/
private func addChildViewController(contoller: UIViewController, title: String, imageName: String) {
/**
设置标题
*/
contoller.title = title
/** 设置标题颜色
*/
// contoller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: UIControlState.Highlighted)
/** 设置图片
*/
contoller.tabBarItem.image = UIImage(named: imageName)
/** 设置高亮图片
*/
contoller.tabBarItem.selectedImage = UIImage(named: (imageName + "_highlighted"))?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
/**
* 添加到控制器
*/
addChildViewController(UINavigationController(rootViewController: contoller))
}
/**
* 懒加载
*/
lazy var composeButton: UIButton = {
let button = UIButton()
/**
* 设置参数 设置按钮背景图片
*/
button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
// 高亮状态下的图片
button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
// 设置按钮图片
button.setImage (UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
//
button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
// 添加tabBar里面
self.tabBar.addSubview(button)
// 添加点击事件
button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
}
|
520c20451c2a76f87a0890063ada412a
| 28.053846 | 150 | 0.623246 | false | false | false | false |
janpo/cordova-plugin-pingpp
|
refs/heads/master
|
sdk/ios/example/demoapp-swift/demoapp-swift/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// demoapp-swift
//
// Created by Afon on 15/4/30.
// Copyright (c) 2015年 Pingplusplus. All rights reserved.
//
import UIKit
let kBackendChargeURL = "http://218.244.151.190/demo/charge" // 你的服务端创建并返回 charge 的 URL 地址,此地址仅供测试用。
let kAppURLScheme = "demoappswift" // 这个是你定义的 URL Scheme,支付宝、微信支付和测试模式需要。
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.
}
override func viewDidAppear(animated: Bool) {
let postDict : AnyObject = NSDictionary(objects: ["alipay", "10"], forKeys: ["channel", "amount"])
var postData: NSData = NSData()
do {
try postData = NSJSONSerialization.dataWithJSONObject(postDict, options: NSJSONWritingOptions.PrettyPrinted)
} catch {
print("Serialization error")
}
let url = NSURL(string: kBackendChargeURL)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData
let sessionTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if data != nil {
let charge = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(charge! as String)
dispatch_async(dispatch_get_main_queue()) {
Pingpp.createPayment(charge! as String, appURLScheme: kAppURLScheme) { (result, error) -> Void in
print(result)
if error != nil {
print(error.code.rawValue)
print(error.getMsg())
}
}
}
} else {
print("response data is nil")
}
}
sessionTask.resume()
}
}
|
582c940f415fd4def83c4d12a453441b
| 34.285714 | 120 | 0.586595 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker
|
refs/heads/master
|
OpenGpxTracker/CoreDataHelper+BatchDelete.swift
|
gpl-3.0
|
1
|
//
// CoreDataHelper+BatchDelete.swift
// OpenGpxTracker
//
// Created by Vincent on 1/8/20.
//
import CoreData
extension CoreDataHelper {
@available(iOS 10.0, *)
func modernBatchDelete<T: NSManagedObject>(of type: T.Type) {
let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.parent = appDelegate.managedObjectContext
privateManagedObjectContext.perform {
do {
let name = "\(T.self)" // Generic name of the object is the entityName
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: name)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
// execute delete request.
try privateManagedObjectContext.execute(deleteRequest)
try privateManagedObjectContext.save()
self.appDelegate.managedObjectContext.performAndWait {
do {
// Saves the changes from the child to the main context to be applied properly
try self.appDelegate.managedObjectContext.save()
} catch {
print("Failure to save context after delete: \(error)")
}
}
} catch {
print("Failed to delete all from core data, error: \(error)")
}
}
}
func legacyBatchDelete<T: NSManagedObject>(of type: T.Type) {
let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.parent = appDelegate.managedObjectContext
// Creates a fetch request
let fetchRequest = NSFetchRequest<T>(entityName: "\(T.self)")
fetchRequest.includesPropertyValues = false
let asynchronousWaypointFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { asynchronousFetchResult in
// Retrieves an array of points from Core Data
guard let results = asynchronousFetchResult.finalResult else { return }
for result in results {
privateManagedObjectContext.delete(result)
}
do {
try privateManagedObjectContext.save()
self.appDelegate.managedObjectContext.performAndWait {
do {
// Saves the changes from the child to the main context to be applied properly
try self.appDelegate.managedObjectContext.save()
} catch {
print("Failure to save context: \(error)")
}
}
} catch {
print("Failure to save context at child context: \(error)")
}
}
do {
try privateManagedObjectContext.execute(asynchronousWaypointFetchRequest)
} catch let error {
print("NSAsynchronousFetchRequest (while deleting \(T.self) error: \(error)")
}
}
}
|
b1f78faaf1511c64e708ce2ec99cf6ee
| 39.5 | 130 | 0.579012 | false | false | false | false |
00buggy00/SwiftOpenGLTutorials
|
refs/heads/master
|
11 OpenGLMVCPt1/SwiftOpenGLView.swift
|
mit
|
1
|
//
// SwiftOpenGLView.swift
// SwiftOpenGL
//
// Created by Myles Schultz on 9/30/16.
// Copyright © 2016 MyKo. All rights reserved.
//
// Ver. 11: Part 1 of MVC design. Vector and Matrix related
// code removed to separate files. This marks the first
// step in creating the model of the framework.
//
import Cocoa
import OpenGL.GL3
final class SwiftOpenGLView: NSOpenGLView {
// Replace the previous properties with out Shader, VertexArrayObject
// VertexBufferObject, and TextureBufferObject types. We don't have
// to worry about crashing the system if we initialize them right
// away because the OpenGL code will be initiated later in
// `prepareOpenGL`.
// Also decalre the data array to be of type [Vertex]
fileprivate var shader = Shader()
fileprivate var vao = VertexArrayObject()
fileprivate var vbo = VertexBufferObject()
fileprivate var tbo = TextureBufferObject()
fileprivate var data = [Vertex]()
fileprivate var previousTime = CFTimeInterval()
// Make the view and projection matrices of type `FloatMatrix4`
fileprivate var view = FloatMatrix4()
fileprivate var projection = FloatMatrix4()
// The CVDisplayLink for animating. Optional value initialized to nil.
fileprivate var displayLink: CVDisplayLink?
// In order to recieve keyboard input, we need to enable the view to accept first responder status
override var acceptsFirstResponder: Bool { return true }
required init?(coder: NSCoder) {
super.init(coder: coder)
// We'll use double buffering this time (one buffer is displayed while the other is
// calculated, then we swap them.
let attrs: [NSOpenGLPixelFormatAttribute] = [
NSOpenGLPixelFormatAttribute(NSOpenGLPFAAccelerated),
NSOpenGLPixelFormatAttribute(NSOpenGLPFADoubleBuffer),
NSOpenGLPixelFormatAttribute(NSOpenGLPFAColorSize), 32,
NSOpenGLPixelFormatAttribute(NSOpenGLPFAOpenGLProfile), NSOpenGLPixelFormatAttribute(NSOpenGLProfileVersion3_2Core),
0
]
guard let pixelFormat = NSOpenGLPixelFormat(attributes: attrs) else {
Swift.print("pixelFormat could not be constructed")
return
}
self.pixelFormat = pixelFormat
guard let context = NSOpenGLContext(format: pixelFormat, share: nil) else {
Swift.print("context could not be constructed")
return
}
self.openGLContext = context
// Set the context's swap interval parameter to 60Hz (i.e. 1 frame per swamp)
self.openGLContext?.setValues([1], for: .swapInterval)
}
override func prepareOpenGL() {
super.prepareOpenGL()
glClearColor(0.0, 0.0, 0.0, 1.0)
// Fill the data array with our new `Vertex` type. We'll also take
// this opportunity to make a new 3D mesh.
data = [
Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), /* Front face 1 */
normal: Float3(x: 0.0, y: 0.0, z: 1.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0),
normal: Float3(x: 0.0, y: 0.0, z: 1.0),
textureCoordinate: Float2(x: 1.0, y: 0.0),
color: Float3(x: 0.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0),
normal: Float3(x: 0.0, y: 0.0, z: 1.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0), /* Front face 2 */
normal: Float3(x: 0.0, y: 0.0, z: 1.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0),
normal: Float3(x: 0.0, y: 0.0, z: 1.0),
textureCoordinate: Float2(x: 0.0, y: 1.0),
color: Float3(x: 1.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0),
normal: Float3(x: 0.0, y: 0.0, z: 1.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0), /* Right face 1 */
normal: Float3(x: 1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 0.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0),
normal: Float3(x: 1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 0.0),
color: Float3(x: 1.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0),
normal: Float3(x: 1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), /* Right face 2 */
normal: Float3(x: 1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0),
normal: Float3(x: 1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0),
normal: Float3(x: 1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 0.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), /* Back face 1 */
normal: Float3(x: 0.0, y: 0.0, z: -1.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0),
normal: Float3(x: 0.0, y: 0.0, z: -1.0),
textureCoordinate: Float2(x: 1.0, y: 0.0),
color: Float3(x: 0.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0),
normal: Float3(x: 0.0, y: 0.0, z: -1.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 1.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0), /* Back face 2 */
normal: Float3(x: 0.0, y: 0.0, z: -1.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 1.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0),
normal: Float3(x: 0.0, y: 0.0, z: -1.0),
textureCoordinate: Float2(x: 0.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0),
normal: Float3(x: 0.0, y: 0.0, z: -1.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0), /* Left face 1 */
normal: Float3(x: -1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 0.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0),
normal: Float3(x: -1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 0.0),
color: Float3(x: 1.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0),
normal: Float3(x: -1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 1.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), /* Left face 2 */
normal: Float3(x: -1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 1.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0),
normal: Float3(x: -1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 1.0),
color: Float3(x: 1.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0),
normal: Float3(x: -1.0, y: 0.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 0.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0), /* Bottom face 1 */
normal: Float3(x: 0.0, y: -1.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: -1.0),
normal: Float3(x: 0.0, y: -1.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 0.0),
color: Float3(x: 0.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0),
normal: Float3(x: 0.0, y: -1.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 1.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: -1.0), /* Bottom face 2 */
normal: Float3(x: 0.0, y: -1.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 1.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: -1.0, z: 1.0),
normal: Float3(x: 0.0, y: -1.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 1.0),
color: Float3(x: 0.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: -1.0, z: 1.0),
normal: Float3(x: 0.0, y: -1.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 0.0, z: 0.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0), /* Top face 1 */
normal: Float3(x: 0.0, y: 1.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: 1.0),
normal: Float3(x: 0.0, y: 1.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 0.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0),
normal: Float3(x: 0.0, y: 1.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: 1.0, y: 1.0, z: -1.0), /* Top face 2 */
normal: Float3(x: 0.0, y: 1.0, z: 0.0),
textureCoordinate: Float2(x: 1.0, y: 1.0),
color: Float3(x: 0.0, y: 1.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: -1.0),
normal: Float3(x: 0.0, y: 1.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 1.0),
color: Float3(x: 1.0, y: 0.0, z: 1.0)),
Vertex(position: Float3(x: -1.0, y: 1.0, z: 1.0),
normal: Float3(x: 0.0, y: 1.0, z: 0.0),
textureCoordinate: Float2(x: 0.0, y: 0.0),
color: Float3(x: 1.0, y: 1.0, z: 1.0))
]
// This is where OpenGL initialization is going to happen. Also of our
// OpenGLObject's may now safely run their initialization code here.
// Load the texture--make sure you have a texture named "Texture" in your
// Assets.xcassets folder.
tbo.loadTexture(named: "Texture")
// Load our new data into the VBO.
vbo.load(data)
// Now we tell OpenGL what our vertex layout looks like.
vao.layoutVertexPattern()
// Define our view and projection matrices
view = FloatMatrix4().translate(x: 0.0, y: 0.0, z: -5.0)
projection = FloatMatrix4.projection(aspect: Float(bounds.size.width / bounds.size.height))
// Declare our Vertex and Fragment shader source code.
let vertexSource = "#version 330 core \n" +
"layout (location = 0) in vec3 position; \n" +
"layout (location = 1) in vec3 normal; \n" +
"layout (location = 2) in vec2 texturePosition; \n" +
"layout (location = 3) in vec3 color; \n" +
"out vec3 passPosition; \n" +
"out vec3 passNormal; \n" +
"out vec2 passTexturePosition; \n" +
"out vec3 passColor; \n" +
"uniform mat4 view; \n" +
"uniform mat4 projection; \n" +
"void main() \n" +
"{ \n" +
" gl_Position = projection * view * vec4(position, 1.0); \n" +
" passPosition = position; \n" +
" passNormal = normal; \n" +
" passTexturePosition = texturePosition; \n" +
" passColor = color; \n" +
"} \n"
let fragmentSource = "#version 330 core \n" +
"uniform sampler2D sample; \n" +
"uniform struct Light { \n" +
" vec3 color; \n" +
" vec3 position; \n" +
" float ambient; \n" +
" float specStrength; \n" +
" float specHardness; \n" +
"} light; \n" +
"in vec3 passPosition; \n" +
"in vec3 passNormal; \n" +
"in vec2 passTexturePosition; \n" +
"in vec3 passColor; \n" +
"out vec4 outColor; \n" +
"void main() \n" +
"{ \n" +
" vec3 normal = normalize(passNormal); \n" +
" vec3 lightRay = normalize(light.position - passPosition); \n" +
" float intensity = dot(normal, lightRay); \n" +
" intensity = clamp(intensity, 0, 1); \n" +
" vec3 viewer = normalize(vec3(0.0, 0.0, 0.2) - passPosition); \n" +
" vec3 reflection = reflect(lightRay, normal); \n" +
" float specular = pow(max(dot(viewer, reflection), 0.0), light.specHardness); \n" +
" vec3 light = light.ambient + light.color * intensity + light.specStrength * specular * light.color; \n" +
" vec3 surface = texture(sample, passTexturePosition).rgb * passColor; \n" +
" vec3 rgb = surface * light; \n" +
" outColor = vec4(rgb, 1.0); \n" +
"} \n"
// Pass in the source code to create our shader object and then set
// it's uniforms.
shader.create(withVertex: vertexSource, andFragment: fragmentSource)
shader.setInitialUniforms()
// We'll deal with this guy soon, but for now no changes here.
let displayLinkOutputCallback: CVDisplayLinkOutputCallback = {(displayLink: CVDisplayLink, inNow: UnsafePointer<CVTimeStamp>, inOutputTime: UnsafePointer<CVTimeStamp>, flagsIn: CVOptionFlags, flagsOut: UnsafeMutablePointer<CVOptionFlags>, displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn in
unsafeBitCast(displayLinkContext, to: SwiftOpenGLView.self).drawView()
return kCVReturnSuccess
}
CVDisplayLinkCreateWithActiveCGDisplays(&displayLink)
CVDisplayLinkSetOutputCallback(displayLink!, displayLinkOutputCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
CVDisplayLinkStart(displayLink!)
}
override func draw(_ dirtyRect: NSRect) {
drawView()
}
fileprivate func drawView() {
guard let context = self.openGLContext else {
Swift.print("oops")
return
}
context.makeCurrentContext()
context.lock()
let time = CACurrentMediaTime()
let value = Float(sin(time))
previousTime = time
glClearColor(GLfloat(value), GLfloat(value), GLfloat(value), 1.0)
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
glEnable(GLenum(GL_CULL_FACE))
// Bind the shader and VAO
shader.bind()
vao.bind()
// reset any uniforms we want to update. We're going to fix this later,
// but for fight now, we'll leave the camera out so we can adjust it's position
glUniform3fv(glGetUniformLocation(shader.id, "light.position"), 1, [value, 2.0, 2.0])
shader.update(view: view, projection: projection)
// "The moment we've all been waiting for", was ask OpenGL to draw our
// scene. Make sure that you adjust the `count` parameter or else you
// won't see anything more than one triangle. We'll use our `data`
// property's `count` property, but cast it into an Int32 which is
// what glDraw* is expecting.
glDrawArrays(GLenum(GL_TRIANGLES), 0, Int32(data.count))
// Unbind the shader.
shader.unbind()
context.flushBuffer()
context.unlock()
}
deinit {
CVDisplayLinkStop(displayLink!)
// Don't forget to be a good memory manager and delete what we don't
// need anymore.
shader.delete()
vao.delete()
vbo.delete()
tbo.delete()
}
}
|
af3af4e0d78658b0679cd5da4af65342
| 54.887097 | 307 | 0.435161 | false | false | false | false |
sopinetchat/SopinetChat-iOS
|
refs/heads/master
|
Pod/Views/SChatToolbarView.swift
|
gpl-3.0
|
1
|
//
// SChatToolbarView.swift
// Pods
//
// Created by David Moreno Lora on 28/4/16.
//
//
import UIKit
public class SChatToolbarView: UIView {
// MARK: Outlets
@IBOutlet weak var leftButtonView: UIView!
@IBOutlet weak var contentTextView: SChatComposerTextView!
@IBOutlet weak var rightButtonView: UIView!
// MARK: Actions
// MARK: Properties
weak var leftBarButtonItem: UIButton? {
didSet
{
if leftBarButtonItem != nil {
leftBarButtonItem?.removeFromSuperview()
}
// TODO: Improve this to allow developers remove this button
if let auxLeftBarButtomItem = leftBarButtonItem
{
if CGRectEqualToRect(auxLeftBarButtomItem.frame, CGRectZero)
{
auxLeftBarButtomItem.frame = leftButtonView.bounds
}
}
leftButtonView.hidden = false
leftBarButtonItem?.translatesAutoresizingMaskIntoConstraints = false
leftButtonView.backgroundColor = UIColor.clearColor()
leftButtonView.addSubview(leftBarButtonItem!)
leftButtonView.sChatPinAllEdgesOfSubview(leftBarButtonItem!)
self.setNeedsUpdateConstraints()
}
}
weak var rightBarButtonItem: UIButton? {
didSet
{
if rightBarButtonItem != nil {
rightBarButtonItem?.removeFromSuperview()
}
if let auxRightBarButtonItem = rightBarButtonItem
{
if CGRectEqualToRect(auxRightBarButtonItem.frame, CGRectZero)
{
auxRightBarButtonItem.frame = rightButtonView.bounds
}
}
rightButtonView.hidden = false
rightBarButtonItem?.translatesAutoresizingMaskIntoConstraints = false
rightButtonView.backgroundColor = UIColor.clearColor()
rightButtonView.addSubview(rightBarButtonItem!)
rightButtonView.sChatPinAllEdgesOfSubview(rightBarButtonItem!)
self.setNeedsUpdateConstraints()
}
}
// MARK: Initializers
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.translatesAutoresizingMaskIntoConstraints = false
}
// MARK: UIView overrides
public override func setNeedsDisplay() {
super.setNeedsDisplay()
}
}
|
4747ee2ea74153cef179c1cca942249f
| 27.42268 | 81 | 0.582155 | false | false | false | false |
LYM-mg/MGDYZB
|
refs/heads/master
|
MGDYZB简单封装版/MGDYZB/Class/Profile/Setting/M/SettingItem.swift
|
mit
|
1
|
//
// SettingModel.swift
// MGDYZB
//
// Created by ming on 16/10/30.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
//
import UIKit
class SettingItem: NSObject {
var title:String = ""
var subTitle:String = ""
var icon:String = ""
// 保存每一行cell做的事情
var operationBlock: ((_ indexPath: IndexPath) -> ())?
init(title: String, subTitle: String = "", icon: String = "") {
self.icon = icon
self.title = title
self.subTitle = subTitle
}
init(dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) { }
}
|
1ba433a042c4033962464dcfb1438f24
| 21.542857 | 74 | 0.588086 | false | false | false | false |
honghaoz/UW-Quest-iOS
|
refs/heads/master
|
UW Quest/ThirdParty/ZHTableLayout/TableCollectionViewLayout.swift
|
apache-2.0
|
1
|
//
// TableLayout.swift
// PageFlowLayout
//
// Created by Honghao Zhang on 3/1/15.
// Copyright (c) 2015 Honghao Zhang. All rights reserved.
//
import UIKit
@objc protocol TableLayoutDataSource {
func numberOfColumnsInCollectionView(collectionView: UICollectionView) -> Int
func collectionView(collectionView: UICollectionView, numberOfRowsInColumn column: Int) -> Int
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: TableCollectionViewLayout, titleForColumn column: Int) -> String
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: TableCollectionViewLayout, contentForColumn column: Int, row: Int) -> String
}
class TableCollectionViewLayout: UICollectionViewLayout {
// NSIndexPath.item == 0, for title cells
// NSIndexPath.item > 0, for content cells
// However, for TableLayoutDataSource, column and row start from zero
// SeparatorLine is decorationViews
var titleFont: UIFont = UIFont(name: "HelveticaNeue", size: 17)!
var contentFont: UIFont = UIFont(name: "HelveticaNeue-Light", size: 17)!
var horizontalPadding: CGFloat = 5.0
var verticalPadding: CGFloat = 1.0
var separatorLineWidth: CGFloat = 1.0
var separatorColor: UIColor = UIColor(white: 0.0, alpha: 0.5)
{
didSet {
TableCollectionViewSeparatorView.separatorColor = separatorColor
}
}
var titleLabelHeight: CGFloat { return "ABC".zhExactSize(titleFont).height }
var contentLabelHeight: CGFloat { return "ABC".zhExactSize(contentFont).height }
var dataSource: UICollectionViewDataSource {
return self.collectionView!.dataSource!
}
var dataSourceTableLayout: TableLayoutDataSource {
return (self.collectionView! as! TableCollectionView).tableLayoutDataSource
}
var sections: Int {
return dataSource.numberOfSectionsInCollectionView!(collectionView!)
}
var maxWidthsForSections = [CGFloat]()
var maxContentHeight: CGFloat = 0
var kSeparatorViewKind = "Separator"
var cellAttrsIndexPathDict = [NSIndexPath: UICollectionViewLayoutAttributes]()
override init() {
super.init()
self.registerClass(TableCollectionViewSeparatorView.self, forDecorationViewOfKind: kSeparatorViewKind)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareLayout() {
buildMaxWidthsHeight()
buildCellAttrsDict()
}
override func collectionViewContentSize() -> CGSize {
var width: CGFloat = maxWidthsForSections.reduce(0, combine: +)
width += CGFloat(sections - 1) * separatorLineWidth
width += CGFloat(sections) * horizontalPadding * 2
return CGSizeMake(width, maxContentHeight)
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
return cellAttrsIndexPathDict[indexPath]
}
override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
var attrs = UICollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, withIndexPath: indexPath)
attrs.hidden = true
if elementKind == kSeparatorViewKind {
if indexPath.item == 0 {
attrs.hidden = false
if indexPath.section == 0 {
var x: CGFloat = 0
var y = titleLabelHeight + verticalPadding * 2
var width = self.collectionViewContentSize().width
attrs.frame = CGRectMake(x, y, width, separatorLineWidth)
} else {
var x: CGFloat = 0
for sec in 0 ..< indexPath.section {
x += maxWidthsForSections[sec] + separatorLineWidth + horizontalPadding * 2
}
x -= separatorLineWidth
var y: CGFloat = 0.0
var width = separatorLineWidth
var height = self.collectionViewContentSize().height
attrs.frame = CGRectMake(x, y, width, height)
}
}
}
return attrs
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var attrs = [UICollectionViewLayoutAttributes]()
let cellIndexPaths = cellIndexPathsForRect(rect)
for indexPath in cellIndexPaths {
attrs.append(self.layoutAttributesForItemAtIndexPath(indexPath))
}
for sec in 0 ..< sections {
for row in 0 ..< collectionView!.dataSource!.collectionView(collectionView!, numberOfItemsInSection: sec) {
attrs.append(self.layoutAttributesForDecorationViewOfKind(kSeparatorViewKind, atIndexPath: NSIndexPath(forItem: row, inSection: sec)))
}
}
return attrs
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return false
}
}
// MARK: Helper functions
extension TableCollectionViewLayout {
func buildMaxWidthsHeight() {
// Calculate MaxWidths
maxWidthsForSections.removeAll(keepCapacity: false)
for col in 0 ..< sections {
let title = dataSourceTableLayout.collectionView(collectionView!, layout: self, titleForColumn: col)
var maxWidth = title.zhExactSize(titleFont).width
let items = dataSource.collectionView(collectionView!, numberOfItemsInSection: col)
for row in 1 ..< items {
// row: row - 1, to let row start from 0
let content = dataSourceTableLayout.collectionView(collectionView!, layout: self, contentForColumn: col, row: row - 1)
var contentWidth = content.zhExactSize(contentFont).width
if contentWidth > maxWidth {
maxWidth = contentWidth
}
}
maxWidthsForSections.append(maxWidth)
}
// Calculate Max Height
var maxItemsCount = 0
for i in 0 ..< sections {
let itemsCount = dataSource.collectionView(collectionView!, numberOfItemsInSection: i)
if maxItemsCount < itemsCount {
maxItemsCount = itemsCount
}
}
maxContentHeight = titleLabelHeight + verticalPadding * 2 + separatorLineWidth + CGFloat(maxItemsCount - 1) * (contentLabelHeight + verticalPadding * 2)
}
func buildCellAttrsDict() {
cellAttrsIndexPathDict.removeAll(keepCapacity: false)
for sec in 0 ..< sections {
let items = dataSource.collectionView(collectionView!, numberOfItemsInSection: sec)
for item in 0 ..< items {
let indexPath = NSIndexPath(forItem: item, inSection: sec)
cellAttrsIndexPathDict[indexPath] = cellAttrisForIndexPath(indexPath)
}
}
}
func cellAttrisForIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes {
var attrs = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
var x: CGFloat = 0
for sec in 0 ..< indexPath.section {
x += maxWidthsForSections[sec] + separatorLineWidth + horizontalPadding * 2
}
var y: CGFloat = 0
let width: CGFloat = maxWidthsForSections[indexPath.section] + horizontalPadding * 2
var height = dataSourceTableLayout.collectionView(collectionView!, layout: self, titleForColumn: indexPath.section).zhExactSize(titleFont).height + verticalPadding * 2
if indexPath.item > 0 {
y = dataSourceTableLayout.collectionView(collectionView!, layout: self, titleForColumn: indexPath.section).zhExactSize(titleFont).height + verticalPadding * 2 + separatorLineWidth
for item in 1 ..< indexPath.item {
y += dataSourceTableLayout.collectionView(collectionView!, layout: self, contentForColumn: indexPath.section, row: item).zhExactSize(contentFont).height + verticalPadding * 2.0
}
// row: indexPath.item - 1, to let row start from 0
height = dataSourceTableLayout.collectionView(collectionView!, layout: self, contentForColumn: indexPath.section, row: indexPath.item - 1).zhExactSize(contentFont).height + verticalPadding * 2
}
attrs.frame = CGRectMake(x, y, width, height)
return attrs
}
func cellIndexPathsForRect(rect: CGRect) -> [NSIndexPath] {
let rectLeft: CGFloat = rect.origin.x
let rectRight: CGFloat = rect.origin.x + rect.width
let rectTop: CGFloat = rect.origin.y
let rectBottom: CGFloat = rect.origin.y + rect.height
var fromSectionIndex = -1
var endSectionIndex = -1
var fromRowIndex = -1
var endRowIndex = -1
// Determin section
var calX: CGFloat = 0.0
for sec in 0 ..< sections {
let nextWidth = maxWidthsForSections[sec] + horizontalPadding * 2 + separatorLineWidth
if calX < rectLeft && rectLeft <= (calX + nextWidth) {
fromSectionIndex = sec
}
if calX < rectRight && rectRight <= (calX + nextWidth) {
endSectionIndex = sec
break
}
calX += nextWidth
}
if fromSectionIndex == -1 {
fromSectionIndex = 0
}
if endSectionIndex == -1 {
endSectionIndex = sections - 1
}
// Determin row
var calY: CGFloat = 0.0
let rowsCount = dataSource.collectionView(collectionView!, numberOfItemsInSection: 0)
for row in 0 ..< rowsCount {
var nextHeight: CGFloat = 0.0
if row == 0 {
nextHeight = titleLabelHeight + verticalPadding * 2 + separatorLineWidth
} else {
nextHeight = contentLabelHeight + verticalPadding * 2
}
if calY < rectTop && rectTop <= (calY + nextHeight) {
fromRowIndex = row
}
if calY < rectBottom && rectBottom <= (calY + nextHeight) {
endRowIndex = row
break
}
calY += nextHeight
}
if fromRowIndex == -1 {
fromRowIndex = 0
}
if endRowIndex == -1 {
endRowIndex = rowsCount - 1
}
// Create array of indexPaths
var indexPaths = [NSIndexPath]()
for sec in fromSectionIndex ... endSectionIndex {
for row in fromRowIndex ... endRowIndex {
indexPaths.append(NSIndexPath(forItem: row, inSection: sec))
}
}
return indexPaths
}
}
extension String {
func zhExactSize(font: UIFont) -> CGSize {
var newSize = self.sizeWithAttributes([NSFontAttributeName: font])
if self.isEmpty {
newSize = " ".sizeWithAttributes([NSFontAttributeName: font])
}
newSize.width = ceil(newSize.width)
newSize.height = ceil(newSize.height)
return newSize
}
}
|
16185ac0d90acc8a6dc1be229b0f8929
| 39.734767 | 204 | 0.621788 | false | false | false | false |
wscqs/QSWB
|
refs/heads/master
|
DSWeibo/DSWeibo/Classes/Tools/NSDate+Category.swift
|
mit
|
1
|
//
// NSDate+Category.swift
// DSWeibo
//
// Created by xiaomage on 16/9/13.
// Copyright © 2016年 小码哥. All rights reserved.
//
import UIKit
extension NSDate
{
class func dateWithStr(time: String) ->NSDate {
// 1.将服务器返回给我们的时间字符串转换为NSDate
// 1.1.创建formatter
let formatter = NSDateFormatter()
// 1.2.设置时间的格式
formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
// 1.3设置时间的区域(真机必须设置, 否则可能不能转换成功)
formatter.locale = NSLocale(localeIdentifier: "en")
// 1.4转换字符串, 转换好的时间是去除时区的时间
let createdDate = formatter.dateFromString(time)!
return createdDate
}
/**
刚刚(一分钟内)
X分钟前(一小时内)
X小时前(当天)
昨天 HH:mm(昨天)
MM-dd HH:mm(一年内)
yyyy-MM-dd HH:mm(更早期)
*/
var descDate:String{
let calendar = NSCalendar.currentCalendar()
// 1.判断是否是今天
if calendar.isDateInToday(self)
{
// 1.0获取当前时间和系统时间之间的差距(秒数)
let since = Int(NSDate().timeIntervalSinceDate(self))
// 1.1是否是刚刚
if since < 60
{
return "刚刚"
}
// 1.2多少分钟以前
if since < 60 * 60
{
return "\(since/60)分钟前"
}
// 1.3多少小时以前
return "\(since / (60 * 60))小时前"
}
// 2.判断是否是昨天
var formatterStr = "HH:mm"
if calendar.isDateInYesterday(self)
{
// 昨天: HH:mm
formatterStr = "昨天:" + formatterStr
}else
{
// 3.处理一年以内
formatterStr = "MM-dd " + formatterStr
// 4.处理更早时间
let comps = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
if comps.year >= 1
{
formatterStr = "yyyy-" + formatterStr
}
}
// 5.按照指定的格式将时间转换为字符串
// 5.1.创建formatter
let formatter = NSDateFormatter()
// 5.2.设置时间的格式
formatter.dateFormat = formatterStr
// 5.3设置时间的区域(真机必须设置, 否则可能不能转换成功)
formatter.locale = NSLocale(localeIdentifier: "en")
// 5.4格式化
return formatter.stringFromDate(self)
}
}
|
87909fa430cdbba9ba7dba5d989c7dde
| 24.888889 | 139 | 0.501717 | false | false | false | false |
iCodesign/ICSTable
|
refs/heads/master
|
ICSTable/Data.swift
|
mit
|
1
|
//
// Data.swift
// ICSTable
//
// Created by LEI on 4/12/15.
// Copyright (c) 2015 TouchingApp. All rights reserved.
//
import UIKit
public protocol Data {
var value: Any? {get set}
var displayText: String? {get}
}
public protocol OptionObject: Data {
func isOptionEqualTo(another: OptionObject) -> Bool
}
public struct DataOf: Data {
public var value: Any?
public var displayText: String? {
switch value {
case .None:
return nil
case let .Some(v):
return "\(v)"
}
}
public init(_ value: Any?){
self.value = value
}
}
public struct DateDataOf: Data {
private var dateformatter = NSDateFormatter()
public var value: Any?
public var displayText: String? {
if let date = value as? NSDate {
return dateformatter.stringFromDate(date)
}
return nil
}
public init(_ value: Any?){
dateformatter.dateStyle = .MediumStyle
dateformatter.timeStyle = .NoStyle
self.value = value
}
}
public struct TimeDataOf: Data {
private var dateformatter = NSDateFormatter()
public var value: Any?
public var displayText: String? {
if let date = value as? NSDate {
return dateformatter.stringFromDate(date)
}
return nil
}
public init(_ value: Any?){
dateformatter.dateStyle = .NoStyle
dateformatter.timeStyle = .ShortStyle
self.value = value
}
}
public struct DateAndTimeDataOf: Data {
private var dateformatter = NSDateFormatter()
public var value: Any?
public var displayText: String? {
if let date = value as? NSDate {
return dateformatter.stringFromDate(date)
}
return nil
}
public init(_ value: Any?){
dateformatter.dateStyle = .MediumStyle
dateformatter.timeStyle = .ShortStyle
self.value = value
}
}
|
818553828293aae077c55d3c47a6230a
| 21.848837 | 56 | 0.6 | false | false | false | false |
kylef/CardKit
|
refs/heads/master
|
Tests/CardKitTests/ValueSpec.swift
|
bsd-2-clause
|
1
|
import Spectre
import CardKit
func testValue() {
describe("Value") {
$0.it("is equatable") {
try expect(Value.ace) == Value.ace
try expect(Value.ace) != Value.two
}
$0.it("is hashable") {
try expect(Value.ace.hashValue) == Value.ace.hashValue
}
$0.describe("custom string convertible") {
$0.it("describes an ace") {
try expect(Value.ace.description) == "A"
}
$0.it("describes a two") {
try expect(Value.two.description) == "2"
}
$0.it("describes a three") {
try expect(Value.three.description) == "3"
}
$0.it("describes a four") {
try expect(Value.four.description) == "4"
}
$0.it("describes a five") {
try expect(Value.five.description) == "5"
}
$0.it("describes a six") {
try expect(Value.six.description) == "6"
}
$0.it("describes a seven") {
try expect(Value.seven.description) == "7"
}
$0.it("describes an eight") {
try expect(Value.eight.description) == "8"
}
$0.it("describes a nine") {
try expect(Value.nine.description) == "9"
}
$0.it("describes a ten") {
try expect(Value.ten.description) == "10"
}
$0.it("describes a jack") {
try expect(Value.jack.description) == "J"
}
$0.it("describes a queen") {
try expect(Value.queen.description) == "Q"
}
$0.it("describes a king") {
try expect(Value.king.description) == "K"
}
}
}
}
|
c64888ebdfc4c6f72c79820221d48ba8
| 21.214286 | 60 | 0.526045 | false | false | false | false |
dangquochoi2007/cleancodeswift
|
refs/heads/master
|
CleanStore/CleanStore/App/Services/ImageManager.swift
|
mit
|
1
|
//
// ImageManager.swift
// CleanStore
//
// Created by hoi on 1/6/17.
// Copyright © 2017 hoi. All rights reserved.
//
import UIKit
/// _ImageMemoryStore_ is an image store backed by an in-memory cache
class ImageManager {
static let shareInstance = ImageManager()
private let memoryStore = ImageMemoryStore()
private let networkStore = ImageNetworkStore()
var updateNetworkStatusActivityIndicator: Bool = true
/// Loads an image from memory cache or the network if not cached
///
/// - parameter url: The image URL
/// - parameter completion: The closure to trigger when the image has been loaded
func loadImage(url: URL, completion: @escaping (UIImage?, Error?) -> ()) {
memoryStore.loadImage(url: url) { [weak self] cachedImage, memoryStoreError in
if let strongSelf = self {
if let _ = cachedImage {
completion(cachedImage, nil)
} else {
strongSelf.setNetworkActivityIndicatorVisible(visible: true)
strongSelf.networkStore.loadImage(url: url, completion: { downloadedImage, networkStoreError in
strongSelf.setNetworkActivityIndicatorVisible(visible: false)
strongSelf.memoryStore.saveImage(image: downloadedImage, url: url)
completion(downloadedImage, networkStoreError)
})
}
}
}
}
/// Clears all images from all caches
func clearCache() {
memoryStore.removeAllImages()
}
// MARK: - Private
private func setNetworkActivityIndicatorVisible(visible: Bool) {
if (updateNetworkStatusActivityIndicator) {
UIApplication.shared.isNetworkActivityIndicatorVisible = visible
}
}
}
|
2cce3e34523fb1b941cdebc0b1b7bdf9
| 29.029412 | 115 | 0.562684 | false | false | false | false |
peferron/algo
|
refs/heads/master
|
EPI/Searching/Find the missing IP address/swift/main.swift
|
mit
|
1
|
// swiftlint:disable variable_name
public func findMissingNumber(_ numbers: [UInt8]) -> UInt8? {
var missing: UInt8 = 0
// We process from the most significant bit (7th bit) down to the least significant bit (0th
// bit). This makes this algorithm return the lowest missing number, which can be a nice
// property to have.
for i: UInt8 in (0..<8).reversed() {
// Consider only the numbers that have the same 0...i bits as missing.
let mask = i == 7 ? 0 : UInt8.max << i
// Count how many numbers have their ith bit set to 0 and 1.
var zeroCount = 0
var oneCount = 0
for number in numbers where number & mask == missing & mask {
if (number >> i) & 1 == 1 {
oneCount += 1
} else {
zeroCount += 1
}
}
let combinationCount = 1 << Int(i)
if zeroCount < combinationCount {
// There is a missing number with its ith bit set to 0.
// `missing` is initialized with 0s by default, so do nothing!
} else if oneCount < combinationCount {
// There is a missing number with its ith bit set to 1.
missing |= (1 << i)
} else {
// All combinations are taken; there is no missing number.
return nil
}
}
return missing
}
|
26d1f06d3654e6863d54c286ad976c2d
| 34.179487 | 96 | 0.559038 | false | false | false | false |
sudiptasahoo/IVP-Luncheon
|
refs/heads/master
|
IVP Luncheon/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// IVP Luncheon
//
// Created by Sudipta Sahoo on 21/05/17.
// Copyright © 2017 Sudipta Sahoo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var locationService : SSLocationService!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Init location service
locationService = SSLocationService.shared
self.appDefaults()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "IVP_Luncheon")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func appDefaults(){
UINavigationBar.appearance().isTranslucent = false
//Scope for many more global customizations
}
}
|
552a2ba97dcf45107fde70ad76577037
| 45.152381 | 285 | 0.682625 | false | false | false | false |
Holmusk/HMRequestFramework-iOS
|
refs/heads/master
|
HMRequestFrameworkTests/database/CoreDataRequestTest.swift
|
apache-2.0
|
1
|
//
// CoreDataRequestTest.swift
// HMRequestFrameworkTests
//
// Created by Hai Pham on 8/9/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import CoreData
import RxSwift
import RxBlocking
import RxTest
import SwiftFP
import SwiftUtilities
import SwiftUtilitiesTests
import XCTest
@testable import HMRequestFramework
public class CoreDataRequestTest: CoreDataRootTest {
let generatorError = "Generator error!"
let processorError = "Processor error!"
/// This test represents the upper layer (API user). We are trying to prove
/// that this upper layer knows nothing about the specific database
/// implementation (e.g. CoreData or Realm).
///
/// All specific database references are restricted to request generators
/// and result processors.
public func test_databaseRequestProcessor_shouldNotLeakContext() {
/// Setup
let observer = scheduler.createObserver(Try<Any>.self)
let expect = expectation(description: "Should have completed")
let dbProcessor = self.dbProcessor!
let generator = errorDBRgn()
let processor = errorDBRps()
let qos: DispatchQoS.QoSClass = .background
/// When
dbProcessor.processTyped(dummy, generator, processor, qos)
.map({$0.map({$0 as Any})})
.flatMap({dbProcessor.processTyped($0, generator, processor, qos)})
.map({$0.map({$0 as Any})})
.flatMap({dbProcessor.processTyped($0, generator, processor, qos)})
.map({$0.map({$0 as Any})})
.flatMap({dbProcessor.processTyped($0, generator, processor, qos)})
.map({$0.map({$0 as Any})})
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 1)
let first = nextElements.first!
XCTAssertEqual(first.error?.localizedDescription, generatorError)
}
public func test_insertAndDeleteRandomDummies_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let dbProcessor = self.dbProcessor!
let manager = self.manager!
let context = manager.disposableObjectContext()
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let cdObjects = try! manager.constructUnsafely(context, pureObjects)
let splitIndex = Int(dummyCount / 2)
// We get some from pure objects and the rest from CoreData objects to
// check that the delete request works correctly by splitting the
// deleted data into the appropriate slices (based on their types).
let deletedObjects: [HMCDObjectConvertibleType] = [
pureObjects[0..<splitIndex].map({$0 as HMCDObjectConvertibleType}),
cdObjects[splitIndex..<dummyCount].map({$0 as HMCDObjectConvertibleType})
].flatMap({$0})
let deleteGn = dummyMemoryDeleteRgn(deletedObjects)
let qos: DispatchQoS.QoSClass = .background
/// When
// Save the changes in the disposable context.
dbProcessor.saveToMemory(Try.success(pureObjects), qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch to verify that data have been persisted.
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
.doOnNext({XCTAssertTrue(pureObjects.all($0.contains))})
.map(Try.success)
// Delete data from memory, but do not persist to DB yet.
.flatMap({dbProcessor.processVoid($0, deleteGn, qos)})
// Persist changes to DB.
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch to verify that the data have been deleted.
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 0)
}
public func test_deletePureObjects_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let dbProcessor = self.dbProcessor!
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let qos: DispatchQoS.QoSClass = .background
/// When
// Save the original objects to DB.
dbProcessor.saveToMemory(Try.success(pureObjects), qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch to verify that data have been persisted.
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
.doOnNext({XCTAssertTrue(pureObjects.all($0.contains))})
.map(Try.success)
// Delete pure objects from DB and persist changes.
.flatMap({_ in dbProcessor.deleteInMemory(Try.success(pureObjects), qos)})
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch to verify that the data have been deleted.
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 0)
}
public func test_fetchAndDeleteWithProperties_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let dbProcessor = self.dbProcessor!
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
var fetchedProps: [String : [CVarArg]] = [:]
fetchedProps["id"] = pureObjects.flatMap({$0.id})
fetchedProps["date"] = pureObjects.flatMap({$0.date.map({$0 as NSDate})})
fetchedProps["float"] = pureObjects.flatMap({$0.float})
fetchedProps["int64"] = pureObjects.flatMap({$0.int64})
let qos: DispatchQoS.QoSClass = .background
/// When
// Save the pure objects to DB.
dbProcessor.saveToMemory(Try.success(pureObjects), qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch with properties and confirm that they match randomObjects.
.flatMap({dbProcessor.fetchWithProperties($0, Dummy1.self, fetchedProps, .and, qos)})
.map({try $0.getOrThrow()})
.doOnNext({XCTAssertEqual($0.count, pureObjects.count)})
.doOnNext({XCTAssertTrue(pureObjects.all($0.contains))})
// Delete with properties and confirm that the DB is empty.
.map(Try.success)
.flatMap({dbProcessor.deleteWithProperties($0, Dummy1.self, fetchedProps, .and, qos)})
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch with properties again to check that all objects are gone.
.flatMap({dbProcessor.fetchWithProperties($0, Dummy1.self, fetchedProps, .and, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 0)
}
public func test_batchDelete_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let dbProcessor = self.dbProcessor!
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let qos: DispatchQoS.QoSClass = .background
/// When
// Save the changes in the disposable context.
dbProcessor.saveToMemory(Try.success(pureObjects), qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
.doOnNext({XCTAssertTrue(pureObjects.all($0.contains))})
.map(Try.success)
// Delete data from DB. Make sure this is a SQLite store though.
.flatMap({dbProcessor.deleteAllInMemory($0, Dummy1.self, qos)})
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch to verify that the data have been deleted.
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 0)
}
public func test_upsertWithOverwriteStrategy_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let dbProcessor = self.dbProcessor!
let context = manager.disposableObjectContext()
let times1 = 1000
let times2 = 2000
let pureObjects1 = (0..<times1).map({_ in Dummy1()})
let pureObjects2 = (0..<times2).map({_ in Dummy1()})
// Since we are using overwrite, we expect the upsert to still succeed.
let pureObjects3 = (0..<times1).map({(index) -> Dummy1 in
let previous = pureObjects1[index]
return Dummy1.builder()
.with(id: previous.id)
.with(version: (previous.version!.intValue + 1) as NSNumber)
.build()
})
let pureObjects23 = [pureObjects2, pureObjects3].flatMap({$0})
let cdObjects23 = try! manager.constructUnsafely(context, pureObjects23)
let upsertGn = dummy1UpsertRgn(cdObjects23, .overwrite)
let upsertPs = dummy1UpsertRps()
let qos: DispatchQoS.QoSClass = .background
/// When
// Insert the first set of data.
dbProcessor.saveToMemory(Try.success(pureObjects1), qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.doOnNext({XCTAssertTrue(pureObjects1.all($0.contains))})
.doOnNext({XCTAssertEqual($0.count, times1)})
.cast(to: Any.self).map(Try.success)
// Upsert the second set of data. This set of data contains some
// data with the same ids as the first set of data.
.flatMap({dbProcessor.processTyped($0, upsertGn, upsertPs, qos)})
// Persist changes to DB.
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch all data to check that the upsert was successful.
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, pureObjects23.count)
XCTAssertTrue(pureObjects23.all(nextElements.contains))
XCTAssertFalse(pureObjects1.any(nextElements.contains))
}
public func test_upsertVersionableWithErrorStrategy_shouldNotOverwrite() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let dbProcessor = self.dbProcessor!
let context = manager.disposableObjectContext()
let times = 1000
let pureObjects1 = (0..<times).map({_ in Dummy1()})
// Since we are using error, we expect the upsert to fail.
let pureObjects2 = (0..<times).map({(index) -> Dummy1 in
let previous = pureObjects1[index]
return Dummy1.builder()
.with(id: previous.id)
.with(version: (previous.version!.intValue + 1) as NSNumber)
.build()
})
let cdObjects2 = try! manager.constructUnsafely(context, pureObjects2)
let upsertGn = dummy1UpsertRgn(cdObjects2, .error)
let upsertPs = dummy1UpsertRps()
let qos: DispatchQoS.QoSClass = .background
/// When
// Insert the first set of data.
dbProcessor.saveToMemory(Try.success(pureObjects1), qos)
// Persist changes to DB.
.flatMap({dbProcessor.persistToDB($0, qos)})
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.doOnNext({XCTAssertTrue(pureObjects1.all($0.contains))})
.doOnNext({XCTAssertEqual($0.count, times)})
.cast(to: Any.self).map(Try.success)
// Upsert the second set of data.
.flatMap({dbProcessor.processTyped($0, upsertGn, upsertPs, qos)})
// Persist changes to DB.
.flatMap({dbProcessor.persistToDB($0, qos)})
// Fetch all data to check that the upsert failed.
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
// Only the old data exists in the DB. The updated versionables are not
// persisted due to error conflict strategy.
XCTAssertEqual(nextElements.count, times)
XCTAssertTrue(pureObjects1.all(nextElements.contains))
XCTAssertFalse(pureObjects2.any(nextElements.contains))
}
public func test_insertConvertibleData_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let dbProcessor = self.dbProcessor!
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let qos: DispatchQoS.QoSClass = .background
/// When
dbProcessor.saveToMemory(Try.success(pureObjects), qos)
.map({$0.map({$0 as Any})})
.flatMap({dbProcessor.persistToDB($0, qos)})
.map({$0.map({$0 as Any})})
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, pureObjects.count)
XCTAssertTrue(pureObjects.all(nextElements.contains))
}
public func test_resetDBStack_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let dbProcessor = self.dbProcessor!
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let qos: DispatchQoS.QoSClass = .background
/// When
dbProcessor.saveToMemory(Try.success(pureObjects), qos)
.flatMap({dbProcessor.persistToDB($0, qos)})
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
.map(Try.success)
.flatMap({dbProcessor.resetStack($0, qos)})
.flatMap({dbProcessor.fetchAllDataFromDB($0, Dummy1.self, qos)})
.map({try $0.getOrThrow()})
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 0)
}
public func test_cdNonTypedRequestObject_shouldThrowErrorsIfNecessary() {
var currentCheck = 0
let processor = self.dbProcessor!
let checkError: (Req, Bool) -> Req = {
currentCheck += 1
print("Checking request \(currentCheck)")
let request = $0
do {
_ = try processor.execute(request)
.subscribeOnConcurrent(qos: .background)
.toBlocking()
.first()
} catch let e {
print(e)
XCTAssertTrue($1)
}
return request
}
/// 1
let request1 = checkError(Req.builder().build(), true)
/// 2
let request2 = checkError(request1.cloneBuilder()
.with(entityName: "E1")
.build(), true)
/// 3
let request3 = checkError(request2.cloneBuilder()
.with(operation: .persistLocally)
.build(), true)
/// End
_ = request3
}
}
extension CoreDataRequestTest {
func dummy1UpsertRequest(_ data: [Dummy1.CDClass],
_ strategy: VersionConflict.Strategy) -> Req {
return Req.builder()
.with(operation: .upsert)
.with(poType: Dummy1.self)
.with(upsertedData: data)
.with(vcStrategy: strategy)
.build()
}
func dummy1UpsertRgn(_ data: [Dummy1.CDClass],
_ strategy: VersionConflict.Strategy)
-> HMRequestGenerator<Any,Req>
{
let request = dummy1UpsertRequest(data, strategy)
return HMRequestGenerators.forceGn(request, Any.self)
}
func dummy1UpsertRps() -> HMResultProcessor<HMCDResult,Void> {
return {Observable.just($0).map(toVoid).map(Try.success)}
}
func dummyMemoryDeleteRequest(_ data: [HMCDObjectConvertibleType]) -> Req {
return Req.builder()
.with(operation: .deleteData)
.with(deletedData: data)
.build()
}
func dummyMemoryDeleteRgn(_ data: [HMCDObjectConvertibleType]) -> HMRequestGenerator<Any,Req> {
return HMRequestGenerators.forceGn(dummyMemoryDeleteRequest(data))
}
}
extension CoreDataRequestTest {
func errorDBRgn() -> HMRequestGenerator<Any,Req> {
return {_ in throw Exception(self.generatorError)}
}
func errorDBRps() -> HMResultProcessor<NSManagedObject,Any> {
return {_ in throw Exception(self.processorError)}
}
}
|
2ae945d777d58cee5d3e6dccb093c81e
| 34.042553 | 97 | 0.676988 | false | false | false | false |
wangxin20111/WaterFlowView
|
refs/heads/master
|
WaterFlowView/WaterFlowCell.swift
|
mit
|
1
|
//
// WaterFlowCell.swift
// WaterFlowView
//
// Created by 王鑫 on 17/4/23.
// Copyright © 2017年 王鑫. All rights reserved.
//
import UIKit
class WaterFlowCell: UIView {
var identifier:String?
private lazy var imageView:UIImageView = UIImageView()
private lazy var lable:UILabel = UILabel()
var shopM:WaterFlowModel?{
didSet{
imageView.image = UIImage.init(named: "WaterFlowView.bundle/placeholder")
lable.text = (shopM!.price)!
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
addSubview(lable)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
lable.frame = CGRect(x:0,y:self.bounds.height - 10,width:WFScreenWidth,height:10)
}
}
|
d794710d01a61cba4e1e08c1463365b1
| 23.02439 | 89 | 0.610152 | false | false | false | false |
MastodonKit/MastodonKit
|
refs/heads/master
|
Sources/MastodonKit/Models/Card.swift
|
mit
|
1
|
//
// Card.swift
// MastodonKit
//
// Created by Ornithologist Coder on 4/9/17.
// Copyright © 2017 MastodonKit. All rights reserved.
//
import Foundation
public struct Card: Codable, Hashable {
public enum PreviewType: String, Codable {
/// Link OEmbed
case link
/// Photo OEmbed
case photo
/// Video OEmbed
case video
/// iframe OEmbed. Not currently accepted, so won't show up in practice.
case rich
}
/// The url associated with the card.
public let url: URL
/// The title of the card.
public let title: String
/// The card description.
public let description: String
/// The image associated with the card, if any.
public let image: URL?
/// The type of the preview card.
public let type: PreviewType?
/// The author of the original resource.
public let authorName: String?
/// A link to the author of the original resource.
public let authorURL: String?
/// The provider of the original resource.
public let providerName: String?
/// A link to the provider of the original resource.
public let providerURL: String?
/// HTML to be used for generating the preview card.
public let html: String?
/// Width of preview, in pixels.
public let width: Double?
/// Height of preview, in pixels.
public let height: Double?
/// Used for photo embeds, instead of custom html.
public let embedURL: String?
/// A hash computed by the [BlurHash](https://github.com/woltapp/blurhash) algorithm, for
/// generating colorful preview thumbnails when media has not been downloaded yet.
public let blurhash: String?
private enum CodingKeys: String, CodingKey {
case url
case title
case description
case image
case type
case authorName = "author_name"
case authorURL = "author_url"
case providerName = "provider_name"
case providerURL = "provider_url"
case html
case width
case height
case embedURL = "embed_url"
case blurhash
}
}
|
0bcd76dbd597950179169ed2ef5ccf14
| 29.042254 | 93 | 0.6376 | false | false | false | false |
flodolo/firefox-ios
|
refs/heads/main
|
Client/Frontend/Toolbar+URLBar/ReaderModeButton.swift
|
mpl-2.0
|
2
|
// 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
class ReaderModeButton: UIButton {
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
adjustsImageWhenHighlighted = false
setImage(UIImage.templateImageNamed("reader"), for: .normal)
imageView?.contentMode = .scaleAspectFit
contentHorizontalAlignment = .left
applyTheme()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Variables
var selectedTintColor: UIColor?
var unselectedTintColor: UIColor?
override var isSelected: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override open var isHighlighted: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override var tintColor: UIColor! {
didSet {
self.imageView?.tintColor = self.tintColor
}
}
private var savedReaderModeState = ReaderModeState.unavailable
var readerModeState: ReaderModeState {
get {
return savedReaderModeState
}
set (newReaderModeState) {
savedReaderModeState = newReaderModeState
switch savedReaderModeState {
case .available:
self.isEnabled = true
self.isSelected = false
case .unavailable:
self.isEnabled = false
self.isSelected = false
case .active:
self.isEnabled = true
self.isSelected = true
}
}
}
}
extension ReaderModeButton: NotificationThemeable {
func applyTheme() {
selectedTintColor = UIColor.theme.urlbar.readerModeButtonSelected
unselectedTintColor = UIColor.theme.urlbar.readerModeButtonUnselected
}
}
|
215ef028f1542e3e4a6487256f476040
| 27.92 | 100 | 0.622407 | false | false | false | false |
manfengjun/KYMart
|
refs/heads/master
|
Section/Order/Model/KYOrderInfoModel.swift
|
mit
|
1
|
//
// KYOrderInfoModel.swift
// KYMart
//
// Created by jun on 2017/7/12.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYOrderInfoModel: NSObject {
var order_statis_id: Int = 0
var return_btn: Int = 0
var user_id: Int = 0
var shipping_code: String!
var store_phone: String!
var pay_name: String!
var order_prom_type: Int = 0
var province: Int = 0
var shipping_time: String!
var receive_btn: Int = 0
var comment_btn: Int = 0
var integral: Int = 0
var order_status_desc: String!
var vrorder: [Vrorder]!
var invoice_title: String!
var cancel_btn: Int = 0
var confirm_time: Int = 0
var user_money: String!
var order_prom_amount: String!
var pay_btn: Int = 0
var address: String!
var coupon_price: String!
var goods_price: String!
var shipping_status: Int = 0
var shipping_name: String!
var pay_code: String!
var goods_list: [Order_Info_Goods_list]!
var is_comment: Int = 0
var add_time: Int = 0
var deleted: Int = 0
var shipping_btn: Int = 0
var country: Int = 0
var store_qq: String!
var email: String!
var parent_sn: String!
var order_status_code: String!
var pay_time: Int = 0
var store_id: Int = 0
var master_order_sn: String!
var district: Int = 0
var admin_note: String!
var user_note: String!
var store_name: String!
var twon: Int = 0
var pay_status: Int = 0
var order_prom_id: Int = 0
var order_sn: String!
var consignee: String!
var shipping_price: String!
var order_status: Int = 0
var order_id: Int = 0
var total_amount: String!
var city: Int = 0
var zipcode: String!
var integral_money: String!
var mobile: String!
var order_amount: String!
var invoice_no: String!
var discount: String!
var transaction_id: String!
class func modelContainerPropertyGenericClass() -> NSDictionary {
return ["goods_list" : Order_Info_Goods_list.classForCoder(),"vrorder" : Vrorder.classForCoder()]
}
}
class Order_Info_Goods_list :NSObject{
var order_sn: String!
var is_comment: Int = 0
var spec_key: String!
var is_checkout: Int = 0
var spec_key_name: String!
var delivery_id: Int = 0
var sku: String!
var market_price: String!
var goods_name: String!
var deleted: Int = 0
var store_id: Int = 0
var bar_code: String!
var give_integral: Int = 0
var order_id: Int = 0
var goods_num: Int = 0
var distribut: String!
var prom_id: Int = 0
var prom_type: Int = 0
var cost_price: String!
var commission: Int = 0
var member_goods_price: String!
var original_img: String!
var goods_price: String!
var goods_id: Int = 0
var is_send: Int = 0
var goods_sn: String!
var rec_id: Int = 0
var reason: String!//退货时描述
}
class Vrorder: NSObject {
var vr_code: String!
var vr_usetime: String!
var vr_state: Int = 0
var vr_indate: Int = 0
}
|
cb24948e4df072d0a01f67401f859275
| 25.80531 | 105 | 0.623968 | false | false | false | false |
tonystone/geofeatures2
|
refs/heads/master
|
Sources/GeoFeatures/Bounds.swift
|
apache-2.0
|
1
|
///
/// Bounds.swift
///
/// Copyright (c) 2018 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 3/24/18.
///
import Swift
///
/// Represents the min and max X Y coordinates of a collection of Coordinates (any geometry).
///
/// This object can be thought of as the bounding box and represents the lower right and upper left coordinates of a Ractangle.
///
public struct Bounds {
///
/// Min X Y values
///
public let min: (x: Double, y: Double)
///
/// Max X Y values
///
public let max: (x: Double, y: Double)
///
/// Mid X Y values
///
public var mid: (x: Double, y: Double) {
return (x: (min.x + max.x) / 2, y: (min.y + max.y) / 2)
}
///
/// Initialize a Bounds with the min and max coordinates.
///
public init(min: Coordinate, max: Coordinate) {
self.min = (x: min.x, y: min.y)
self.max = (x: max.x, y: max.y)
}
///
/// Initialize a Bounds with the min and max tuples.
///
public init(min: (x: Double, y: Double), max: (x: Double, y: Double)) {
self.min = (x: min.x, y: min.y)
self.max = (x: max.x, y: max.y)
}
}
extension Bounds {
///
/// Returns the minX, minY, maxX, maxY, of 2 `Bounds`s as a `Bounds`.
///
public func expand(other: Bounds) -> Bounds {
return Bounds(min: (x: Swift.min(self.min.x, other.min.x), y: Swift.min(self.min.y, other.min.y)),
max: (x: Swift.max(self.max.x, other.max.x), y: Swift.max(self.max.y, other.max.y)))
}
}
extension Bounds: Equatable {
public static func == (lhs: Bounds, rhs: Bounds) -> Bool {
return lhs.min == rhs.min && lhs.max == rhs.max
}
}
extension Bounds: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "\(type(of: self))(min: \(self.min), max: \(self.max))"
}
public var debugDescription: String {
return self.description
}
}
|
c68ad2930d29f64f426f67db902b959e
| 27.333333 | 127 | 0.600784 | false | false | false | false |
Candyroot/Fonts
|
refs/heads/master
|
Fonts/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// Fonts
//
// Created by Liu Bing on 3/30/15.
// Copyright (c) 2015 UnixOSS. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
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:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.fontDescriptor == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
|
ce55e995c0609a6801a249c2669efb25
| 51.968254 | 285 | 0.750674 | false | false | false | false |
telldus/telldus-live-mobile-v3
|
refs/heads/master
|
ios/WidgetHelpers/APICacher.swift
|
gpl-3.0
|
1
|
//
// APICacher.swift
// TelldusLiveApp
//
// Created by Rimnesh Fernandez on 27/10/20.
// Copyright © 2020 Telldus Technologies AB. All rights reserved.
//
import Foundation
/**
This class does fetching of data from API and caching in local DB
*/
struct APICacher {
/**
Fetches a sensor info from API and update local DB
*/
func cacheSensorData(sensorId: Int, completion: @escaping () -> Void) {
SensorsAPI().getSensorInfo(sensorId: sensorId) {result in
var db: SQLiteDatabase? = nil
do {
db = try SQLiteDatabase.open(nil)
try db?.createTable(table: SensorDetailsModel.self)
try db?.createTable(table: SensorDataModel.self)
} catch {
completion()
return
}
guard db != nil else {
completion()
return
}
guard let sensor = result["sensor"] as? Sensor else {
completion()
return
}
guard let authData = result["authData"] as? Dictionary<String, Any> else {
completion()
return
}
let email = authData["email"] as? String
let uuid = authData["uuid"] as? String
guard email != nil && uuid != nil else {
completion()
return
}
let did = sensor.id;
let id = Int(did)!
let name = sensor.name;
guard name != nil else {
completion()
return
}
let lastUpdated = sensor.lastUpdated;
let sensorProtocol = sensor.sensorProtocol;
guard let dataFromDb = db?.sensorDetailsModel(sensorId: Int32(id)) else {
completion()
return
}
let sensorDetailsModel = SensorDetailsModel(
id: id,
name: name!,
userId: uuid!,
sensorId: dataFromDb.sensorId,
clientId: dataFromDb.clientId,
lastUpdated: lastUpdated,
model: dataFromDb.model,
sensorProtocol: sensorProtocol,
isUpdating: 0,
userEmail: email!
)
do {
try db?.insertSensorDetailsModel(sensorDetailsModel: sensorDetailsModel)
} catch {
}
guard let data = sensor.data else {
completion()
return
}
guard data.count > 0 else {
completion()
return
}
for item in data {
let _scale = item.scale;
let _value = item.value;
let scale = Int(_scale)!
let value = Double(_value)!
let _lastUpdated = item.lastUpdated;
let scaleName = item.name;
let sensorDataModel = SensorDataModel(
sensorId: id,
userId: uuid!,
scale: scale,
value: value,
name: scaleName,
lastUpdated: _lastUpdated
)
do {
try db?.insertSensorDataModel(sensorDataModel: sensorDataModel)
} catch {
}
}
completion()
}
}
/**
Fetches Devices, Sensors and Gateways list from API and update local DB
*/
func cacheAPIData(completion: @escaping () -> Void) {
var db: SQLiteDatabase? = nil
do {
db = try SQLiteDatabase.open(nil)
// try db?.createTable(table: DeviceDetailsModel.self) // TODO: Enable device widget
try db?.createTable(table: SensorDetailsModel.self)
try db?.createTable(table: SensorDataModel.self)
try db?.createTable(table: GatewayDetailsModel.self)
} catch {
completion()
return
}
guard db != nil else {
completion()
return
}
// cacheDevicesData(db: db!) {// TODO: Enable device widget
cacheSensorsData(db: db!) {
completion()
cacheGatewaysData(db: db!){
}
}
// }
}
/**
Fetches Devices list from API and update local DB
*/
func cacheDevicesData(db: SQLiteDatabase, completion: @escaping () -> Void) {
DevicesAPI().getDevicesList() {result in
guard let devices = result["devices"] as? [Device] else {
completion()
return
}
guard let authData = result["authData"] as? Dictionary<String, Any> else {
completion()
return
}
let email = authData["email"] as? String
let uuid = authData["uuid"] as? String
guard email != nil && uuid != nil else {
completion()
return
}
// db.deleteAllRecordsCurrentAccount(table: DeviceDetailsModel.self, userId: uuid as! NSString) // TODO: Enable device widget
for device in devices {
let id = Int(device.id)!
let name = device.name ?? ""
let state = device.state
let methods = device.methods
let deviceType = device.deviceType
let stateValue = ""
let _clientId = device.client
let clientId = Int(_clientId)!
let _clientDeviceId = device.clientDeviceId
let clientDeviceId = Int(_clientDeviceId)!
let deviceDetailsModel = DeviceDetailsModel(
id: id,
name: name,
state: state,
methods: methods,
deviceType: deviceType,
stateValue: stateValue,
userId: uuid!,
secStateValue: "",
methodRequested: 0,
clientId: clientId,
clientDeviceId: clientDeviceId,
requestedStateValue: "",
requestedSecStateValue: "",
userEmail: email!
)
do {
try db.insertDeviceDetailsModel(deviceDetailsModel: deviceDetailsModel)
} catch {
}
}
completion()
}
}
}
/**
Fetches Sensors list from API and update local DB
*/
func cacheSensorsData(db: SQLiteDatabase, completion: @escaping () -> Void) {
SensorsAPI().getSensorsList() {result in
guard let sensors = result["sensors"] as? [Sensor] else {
completion()
return
}
guard let authData = result["authData"] as? Dictionary<String, Any> else {
completion()
return
}
let email = authData["email"] as? String
let uuid = authData["uuid"] as? String
guard email != nil && uuid != nil else {
completion()
return
}
db.deleteAllRecordsCurrentAccount(table: SensorDetailsModel.self, userId: uuid as! NSString)
for sensor in sensors {
let did = sensor.id
let id = Int(did)!
guard let name = sensor.name else {
continue
}
let _sensorId = sensor.sensorId
let sensorId = Int(_sensorId!)!
let _clientId = sensor.client
let clientId = Int(_clientId!)!
let lastUpdated = sensor.lastUpdated
let model = sensor.model!
let sensorProtocol = sensor.sensorProtocol
guard let sensorData = sensor.data else {
continue
}
guard sensorData.count > 0 else {
continue
}
let sensorDetailsModel = SensorDetailsModel(
id: id,
name: name,
userId: uuid!,
sensorId: sensorId,
clientId: clientId,
lastUpdated: lastUpdated,
model: model,
sensorProtocol: sensorProtocol,
isUpdating: 0,
userEmail: email!
)
do {
try db.insertSensorDetailsModel(sensorDetailsModel: sensorDetailsModel)
for item in sensorData {
let _scale = item.scale;
let scale = Int(_scale)!
let _value = item.value;
let value = Double(_value)!
let _lastUpdated = item.lastUpdated;
let scaleName = item.name;
let sensorDataModel = SensorDataModel(
sensorId: id,
userId: uuid!,
scale: scale,
value: value,
name: scaleName,
lastUpdated: _lastUpdated
)
do {
try db.insertSensorDataModel(sensorDataModel: sensorDataModel)
} catch {
}
}
} catch {
}
}
completion()
}
}
/**
Fetches Gateways list from API and update local DB
*/
func cacheGatewaysData(db: SQLiteDatabase, completion: @escaping () -> Void) {
GatewaysAPI().getGatewaysList() {result in
guard let clients = result["clients"] as? [Gateway] else {
completion()
return
}
guard let authData = result["authData"] as? Dictionary<String, Any> else {
completion()
return
}
let email = authData["email"] as? String
let uuid = authData["uuid"] as? String
guard email != nil && uuid != nil else {
completion()
return
}
db.deleteAllRecordsCurrentAccount(table: GatewayDetailsModel.self, userId: uuid as! NSString)
for client in clients {
let cid = client.id;
let id = Int(cid)!
var timezone = client.timezone;
if timezone == nil {
timezone = ""
}
let gatewayDetailsModel = GatewayDetailsModel(
id: id,
userId: uuid!,
timezone: timezone!
)
do {
try db.insertGatewayDetailsModel(gatewayDetailsModel: gatewayDetailsModel)
} catch {
}
}
completion()
}
}
|
5f1f15602e58e6437909498830c9967b
| 26.420732 | 136 | 0.574049 | false | false | false | false |
mjec/ios-tip-calculator
|
refs/heads/master
|
TipCalc/NumericTextFieldDelegate.swift
|
apache-2.0
|
1
|
//
// NumericTextFieldDelegate.swift
// TipCalc
//
// Created by Michael Cordover on 07/15/2017.
// Copyright © 2017 Michael Cordover. All rights reserved.
//
import UIKit
class NumericTextFieldDelegate: NSObject, UITextFieldDelegate {
// MARK: - internal variables
private var formatter: NumberFormatter
// MARK: - initalizer
init(withFormatter aFormatter: NumberFormatter) {
formatter = aFormatter
}
// MARK: - delegated methods
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.text = NumericTextHelper.removeNonNumericCharcters(string: textField.text ?? "")
if convertToDouble(string: textField.text!) == 0 {
textField.text = ""
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let resulting_text = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string
if string.characters.count == 0 {
return true
} else if NumericTextHelper.removeNonNumericCharcters(string: string) == string && resulting_text.components(separatedBy: NumericTextHelper.decimalSeparator).count < 3 {
return true
} else {
return false
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.text = formatter.string(from: convertToDouble(string: textField.text!) as NSNumber)
}
// MARK: - helper methods
private func convertToDouble(string: String) -> Double {
let dbl = Double(string) ?? 0
// this switch on formatter style feels a little gross, but it's not unreasonable
switch formatter.numberStyle {
case .percent:
return dbl / 100
default:
return dbl
}
}
}
|
747556eff50e10b5a65fa9df0379933a
| 31.614035 | 177 | 0.654115 | false | false | false | false |
nalexn/ViewInspector
|
refs/heads/master
|
Sources/ViewInspector/SwiftUI/DisclosureGroup.swift
|
mit
|
1
|
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct DisclosureGroup: KnownViewType {
public static var typePrefix: String = "DisclosureGroup"
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
public extension InspectableView where View: SingleViewContent {
func disclosureGroup() throws -> InspectableView<ViewType.DisclosureGroup> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
public extension InspectableView where View: MultipleViewContent {
func disclosureGroup(_ index: Int) throws -> InspectableView<ViewType.DisclosureGroup> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Content Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.DisclosureGroup: MultipleViewContent {
public static func children(_ content: Content) throws -> LazyGroup<Content> {
let view = try Inspector.attribute(label: "content", value: content.view)
return try Inspector.viewsInContainer(view: view, medium: content.medium)
}
}
// MARK: - Non Standard Children
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.DisclosureGroup: SupplementaryChildrenLabelView { }
// MARK: - Custom Attributes
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
public extension InspectableView where View == ViewType.DisclosureGroup {
func labelView() throws -> InspectableView<ViewType.ClassifiedView> {
return try View.supplementaryChildren(self).element(at: 0)
.asInspectableView(ofType: ViewType.ClassifiedView.self)
}
func isExpanded() throws -> Bool {
guard let external = try isExpandedBinding() else {
return try isExpandedState().wrappedValue
}
return external.wrappedValue
}
func expand() throws { try set(isExpanded: true) }
func collapse() throws { try set(isExpanded: false) }
private func set(isExpanded: Bool) throws {
if let external = try isExpandedBinding() {
external.wrappedValue = isExpanded
} else {
// @State mutation from outside is ignored by SwiftUI
// try isExpandedState().wrappedValue = isExpanded
// swiftlint:disable line_length
throw InspectionError.notSupported("You need to enable programmatic expansion by using `DisclosureGroup(isExpanded:, content:, label:`")
// swiftlint:enable line_length
}
}
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
private extension InspectableView where View == ViewType.DisclosureGroup {
func isExpandedState() throws -> State<Bool> {
return try Inspector
.attribute(path: "_isExpanded|state", value: content.view, type: State<Bool>.self)
}
func isExpandedBinding() throws -> Binding<Bool>? {
return try? Inspector
.attribute(path: "_isExpanded|binding", value: content.view, type: Binding<Bool>.self)
}
}
|
c4d7d72326b558a349165168316c7273
| 33.041667 | 148 | 0.679621 | false | false | false | false |
WildDogTeam/demo-ios-officemover
|
refs/heads/master
|
OfficeMover5000/FurnitureView.swift
|
mit
|
1
|
//
// FurnitureButton.swift
// OfficeMover500
//
// Created by Garin on 11/2/15.
// Copyright (c) 2015 Wilddog. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
enum DragState: Int {
case None = 0, Maybe, Dragging
}
class FurnitureView : UIButton, UIAlertViewDelegate, UITextFieldDelegate {
// --- Model state handlers
var moveHandler: ((Int, Int) -> ())?
var rotateHandler: ((Int, Int, Int) -> ())?
var deleteHandler: (() -> ())?
var editHandler: ((String) -> ())?
var moveToTopHandler: (() -> ())?
// --- Calculated propeties. Set these from the outside to set the view
var top:Int {
get {
return Int(frame.origin.y)
}
set (newValue) {
if newValue < 0 {
frame.origin.y = 0
} else if newValue > RoomHeight - Int(frame.size.height) {
frame.origin.y = CGFloat(RoomHeight) - frame.size.height
} else {
frame.origin.y = CGFloat(newValue)
}
}
}
var left:Int {
get {
return Int(frame.origin.x)
}
set (newValue) {
if newValue < 0 {
frame.origin.x = 0
} else if newValue > RoomWidth - Int(frame.size.width) {
frame.origin.x = CGFloat(RoomWidth) - frame.size.width
} else {
frame.origin.x = CGFloat(newValue)
}
}
}
var rotation:Int {
get {
let radians = atan2f(Float(transform.b), Float(transform.a))
let degrees = radians * Float(180/M_PI)
switch (degrees) {
case -90:
return 90
case -180, 180:
return 180
case 90, -270:
return 270
default:
return 0
}
}
set (newValue) {
transform = CGAffineTransformMakeRotation(CGFloat(newValue / 90) * CGFloat(M_PI / -2))
}
}
var name:String? {
get {
return currentTitle
}
set (newValue) {
setTitle(newValue, forState:.Normal)
}
}
var zIndex:Int {
get {
return Int(layer.zPosition)
}
set (newValue) {
layer.zPosition = CGFloat(newValue)
}
}
// --- Handling UI state
var dragging = DragState.None
var menuShowing = false
let type: String
var startDown: CGPoint?
private var menuListener: AnyObject?
private var alert: UIAlertView?
func handleLogout() {
// Stop drag event
stopDrag()
// Hide menu
let menuController = UIMenuController.sharedMenuController()
menuController.setMenuVisible(false, animated:false)
if let listener = menuListener {
NSNotificationCenter.defaultCenter().removeObserver(listener)
}
// Hide alert view
if let alertView = alert {
alertView.dismissWithClickedButtonIndex(0, animated: false)
}
}
// --- Initializers
required init?(coder aDecoder: NSCoder) {
type = "desk"
super.init(coder: aDecoder)
}
init(furniture: Furniture) {
type = furniture.type == "plant" ? "plant1" : furniture.type // hack because we have 2 plant images
super.init(frame: CGRectMake((CGFloat(RoomWidth)-100)/2, (CGFloat(RoomHeight)-100)/2, 10, 10))
// Setup image and size
let image = UIImage(named:"\(type).png")
setBackgroundImage(image, forState:.Normal)
frame.size = image!.size
// Setup other properties
setViewState(furniture)
self.titleLabel?.font = UIFont(name: "Proxima Nova", size: 20)
// Add touch events
addTarget(self, action:Selector("dragged:withEvent:"), forControlEvents:[.TouchDragInside, .TouchDragOutside])
addTarget(self, action:Selector("touchDown:withEvent:"), forControlEvents:.TouchDown)
addTarget(self, action:Selector("touchUp:withEvent:"), forControlEvents:[.TouchUpInside, .TouchUpOutside])
}
// --- Set state given model
func setViewState(model: Furniture) {
self.rotation = model.rotation
self.top = model.top
self.left = model.left
self.name = model.name
self.zIndex = model.zIndex
}
// --- Delege the view
func delete() {
if menuShowing {
let menuController = UIMenuController.sharedMenuController()
menuController.setMenuVisible(false, animated: true)
menuShowing = false
}
if superview != nil {
removeFromSuperview()
}
}
// --- Methods for handling touch events
func dragged(button: UIButton, withEvent event: UIEvent) {
temporarilyHideMenu() // Hide the menu while dragging
// Get the touch in view, bound it to the room, and move the button there
let set : Set<NSObject> = event.touchesForView(button)!
if let touch = set.first as? UITouch {
let touchLoc = touch.locationInView(self.superview)
if let startDown = self.startDown{
if abs(startDown.x - touchLoc.x) > 10 || abs(startDown.y - touchLoc.y) > 10 {
dragging = DragState.Dragging // To aviod triggering tap functionality
showSeeThrough()
}
center = boundCenterLocToRoom(touchLoc)
}
}
}
// helper to bound location to the room based on the center loc.
func boundCenterLocToRoom(centerLoc: CGPoint) -> CGPoint {
var pt = CGPointMake(centerLoc.x, centerLoc.y)
// Bound x inside of width
if centerLoc.x < frame.size.width / 2 {
pt.x = frame.size.width / 2
} else if centerLoc.x > CGFloat(RoomWidth) - frame.size.width / 2 {
pt.x = CGFloat(RoomWidth) - frame.size.width / 2
}
// Bound y inside of height
if centerLoc.y < frame.size.height / 2 {
pt.y = frame.size.height / 2
} else if centerLoc.y > CGFloat(RoomHeight) - frame.size.height / 2 {
pt.y = CGFloat(RoomHeight) - frame.size.height / 2
}
return pt
}
func touchDown(button: UIButton, withEvent event: UIEvent) {
startDown = center
dragging = .Maybe
showShadow()
superview?.bringSubviewToFront(self)
moveToTopHandler?()
NSTimer.scheduledTimerWithTimeInterval(0.04, target:self, selector: Selector("debouncedMove:"), userInfo: nil, repeats:true)
}
func touchUp(button: UIButton, withEvent event: UIEvent) {
stopDrag()
}
func stopDrag() {
startDown = nil
hideSeeThrough()
if dragging == .Dragging {
triggerMove()
dragging = .None // This always ends drag events
if !menuShowing {
// Don't show menu at the end of dragging if there wasn't a menu to begin with
hideShadow()
return
}
}
dragging = .None // This always ends drag events
showMenu()
}
// --- Updates for move
func debouncedMove(timer: NSTimer) {
if dragging == .None {
timer.invalidate()
} else {
triggerMove()
}
}
func triggerMove() {
moveHandler?(top, left)
}
// --- Menu buttons were clicked
func triggerRotate(sender: AnyObject) {
transform = CGAffineTransformRotate(transform, CGFloat(M_PI / -2))
hideShadow()
rotateHandler?(top, left, rotation)
}
func triggerDelete(sender: AnyObject) {
deleteHandler?()
}
func triggerEdit(sender:AnyObject) {
// The OK button actually doesn't do anything.
let alert = UIAlertView(title: "Who sits here?", message: "Enter name below", delegate: self, cancelButtonTitle: "OK")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput;
if let textField = alert.textFieldAtIndex(0) {
textField.text = name
textField.placeholder = "Name"
textField.delegate = self
textField.autocapitalizationType = .Words
textField.addTarget(self, action: Selector("textFieldChanged:"), forControlEvents: .EditingChanged)
}
alert.show()
self.alert = alert
}
// --- Delegates for handling name editing
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
hideShadow()
if buttonIndex == 1 { // This is the ok button, and not the cancel button
if let newName = alertView.textFieldAtIndex(0)?.text {
name = newName
editHandler?(newName)
}
}
}
func textFieldChanged(textField: UITextField) {
editHandler?(textField.text!)
}
// --- Selected shadow
func showShadow() {
layer.shadowColor = TopbarBlue.CGColor
layer.shadowRadius = 4.0
layer.shadowOpacity = 0.9
layer.shadowOffset = CGSizeZero
layer.masksToBounds = false
}
func hideShadow() {
layer.shadowOpacity = 0
}
func showSeeThrough() {
layer.opacity = 0.5
}
func hideSeeThrough() {
layer.opacity = 1
}
// --- Menu helper methods
func showMenu() {
showShadow()
menuShowing = true
let menuController = UIMenuController.sharedMenuController()
// Set new menu location
if superview != nil {
menuController.setTargetRect(frame, inView:superview!)
}
// Set menu items
menuController.menuItems = [
UIMenuItem(title: "Rotate", action:Selector("triggerRotate:")),
UIMenuItem(title: "Delete", action:Selector("triggerDelete:"))
]
if type == "desk" {
menuController.menuItems?.insert(UIMenuItem(title: "Edit", action:Selector("triggerEdit:")), atIndex:0)
}
// Handle displaying and disappearing the menu
becomeFirstResponder()
menuController.setMenuVisible(true, animated: true)
watchForMenuExited()
}
// Temporarily hide it when item is moving
func temporarilyHideMenu() {
let menuController = UIMenuController.sharedMenuController()
menuController.setMenuVisible(false, animated:false)
}
// Watch for menu exited - handles the menuShowing state for cancels and such
func watchForMenuExited() {
if menuListener != nil {
NSNotificationCenter.defaultCenter().removeObserver(menuListener!)
}
menuListener = NSNotificationCenter.defaultCenter().addObserverForName(UIMenuControllerWillHideMenuNotification, object:nil, queue: nil, usingBlock: { [unowned self]
notification in
if self.dragging == .Dragging || self.dragging == .None {
self.menuShowing = false
}
if self.dragging == .None {
self.hideShadow()
}
NSNotificationCenter.defaultCenter().removeObserver(self.menuListener!)
})
}
}
// UIResponder override methods
extension FurnitureView {
override func canBecomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
return action == Selector("triggerRotate:") || action == Selector("triggerDelete:") || action == Selector("triggerEdit:")
}
}
|
b4c4976736730be66f9fa9ec9bcef756
| 30.569149 | 173 | 0.569166 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/Classes/ViewRelated/System/FilterTabBar.swift
|
gpl-2.0
|
1
|
import UIKit
/// Filter Tab Bar is a tabbed control (much like a segmented control), but
/// has an appearance similar to Android tabs.
///
protocol FilterTabBarItem {
var title: String { get }
var attributedTitle: NSAttributedString? { get }
var accessibilityIdentifier: String { get }
var accessibilityLabel: String? { get }
var accessibilityValue: String? { get }
var accessibilityHint: String? { get }
}
extension FilterTabBarItem {
var attributedTitle: NSAttributedString? { return nil }
var accessibilityLabel: String? { return nil }
var accessibilityValue: String? { return nil }
var accessibilityHint: String? { return nil }
}
extension FilterTabBarItem where Self: RawRepresentable {
var accessibilityIdentifier: String {
return "\(self)"
}
}
class FilterTabBar: UIControl {
private let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
return scrollView
}()
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.spacing = 0
return stackView
}()
private let selectionIndicator: UIView = {
let selectionIndicator = UIView()
selectionIndicator.translatesAutoresizingMaskIntoConstraints = false
selectionIndicator.isHidden = true
return selectionIndicator
}()
private let divider: UIView = {
let divider = UIView()
divider.translatesAutoresizingMaskIntoConstraints = false
return divider
}()
var items: [FilterTabBarItem] = [] {
didSet {
refreshTabs()
}
}
private var tabBarHeightConstraint: NSLayoutConstraint! {
didSet {
if let oldValue = oldValue {
NSLayoutConstraint.deactivate([oldValue])
tabBarHeightConstraint.isActive = true
}
}
}
var tabBarHeight = AppearanceMetrics.height {
didSet {
tabBarHeightConstraint = heightAnchor.constraint(equalToConstant: tabBarHeight)
}
}
var tabBarHeightConstraintPriority: Float = UILayoutPriority.required.rawValue {
didSet {
tabBarHeightConstraint.priority = UILayoutPriority(tabBarHeightConstraintPriority)
}
}
var equalWidthFill: UIStackView.Distribution = .fillEqually {
didSet {
stackView.distribution = equalWidthFill
}
}
var equalWidthSpacing: CGFloat = 0 {
didSet {
stackView.spacing = equalWidthSpacing
}
}
// MARK: - Appearance
/// Tint color will be applied to the floating selection indicator.
/// If selectedTitleColor is not provided, tint color will also be applied to
/// titles of selected tabs.
///
override var tintColor: UIColor! {
didSet {
tabs.forEach({
$0.tintColor = tintColor
$0.setTitleColor(titleColorForSelected, for: .selected)
$0.setTitleColor(titleColorForSelected, for: .highlighted)
$0.setAttributedTitle(addColor(titleColorForSelected, toAttributedString: $0.currentAttributedTitle),
for: .selected)
$0.setAttributedTitle(addColor(titleColorForSelected, toAttributedString: $0.currentAttributedTitle),
for: .highlighted)
})
selectionIndicator.backgroundColor = tintColor
}
}
/// Selected Title Color will be applied to titles of selected tabs.
///
var selectedTitleColor: UIColor? {
didSet {
tabs.forEach({
$0.setTitleColor(selectedTitleColor, for: .selected)
$0.setTitleColor(selectedTitleColor, for: .highlighted)
})
}
}
private var titleColorForSelected: UIColor {
return selectedTitleColor ?? tintColor
}
var deselectedTabColor: UIColor = .lightGray {
didSet {
tabs.forEach({ $0.setTitleColor(deselectedTabColor, for: .normal) })
}
}
var dividerColor: UIColor = .lightGray {
didSet {
divider.backgroundColor = dividerColor
}
}
/// Accessory view displayed on the leading end of the tab bar.
///
var accessoryView: UIView? = nil {
didSet {
if let oldValue = oldValue {
oldValue.removeFromSuperview()
}
if let accessoryView = accessoryView {
accessoryView.setContentCompressionResistancePriority(.required, for: .horizontal)
stackView.insertArrangedSubview(accessoryView, at: 0)
}
}
}
// MARK: - Tab Sizing
private var stackViewEdgeConstraints: [NSLayoutConstraint]! {
didSet {
if let oldValue = oldValue {
NSLayoutConstraint.deactivate(oldValue)
}
}
}
private var stackViewWidthConstraint: NSLayoutConstraint! {
didSet {
if let oldValue = oldValue {
NSLayoutConstraint.deactivate([oldValue])
}
}
}
enum TabSizingStyle {
/// The tabs will fill the space available to the filter bar,
/// with all tabs having equal widths. Tabs will not scroll.
/// Because of different language widths, ideally this should only be
/// used for 3 tabs or less.
case equalWidths
/// The tabs will have differing widths which fit their content size.
/// If the tabs are too large to fit in the area available, the
/// filter bar will scroll.
case fitting
}
/// Defines how the tabs should be sized within the tab view.
///
var tabSizingStyle: TabSizingStyle = .fitting {
didSet {
updateTabSizingConstraints()
activateTabSizingConstraints()
}
}
// MARK: - Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
init() {
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
commonInit()
}
private func commonInit() {
tabBarHeightConstraint = heightAnchor.constraint(equalToConstant: tabBarHeight)
tabBarHeightConstraint?.isActive = true
divider.backgroundColor = dividerColor
addSubview(divider)
NSLayoutConstraint.activate([
divider.leadingAnchor.constraint(equalTo: leadingAnchor),
divider.trailingAnchor.constraint(equalTo: trailingAnchor),
divider.bottomAnchor.constraint(equalTo: bottomAnchor),
divider.heightAnchor.constraint(equalToConstant: AppearanceMetrics.bottomDividerHeight)
])
addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: divider.topAnchor),
scrollView.topAnchor.constraint(equalTo: topAnchor)
])
scrollView.addSubview(stackView)
stackView.isLayoutMarginsRelativeArrangement = true
// We will manually constrain the stack view to the content layout guide
scrollView.contentInsetAdjustmentBehavior = .never
stackViewWidthConstraint = stackView.widthAnchor.constraint(equalTo: scrollView.safeAreaLayoutGuide.widthAnchor)
updateTabSizingConstraints()
activateTabSizingConstraints()
NSLayoutConstraint.activate([
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.bottomAnchor.constraint(equalTo: divider.topAnchor),
stackView.topAnchor.constraint(equalTo: topAnchor)
])
addSubview(selectionIndicator)
NSLayoutConstraint.activate([
selectionIndicator.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
selectionIndicator.heightAnchor.constraint(equalToConstant: AppearanceMetrics.selectionIndicatorHeight)
])
}
// MARK: - Tabs
private var tabs: [UIButton] = []
private func refreshTabs() {
tabs.forEach({ $0.removeFromSuperview() })
tabs = items.map(makeTab)
stackView.addArrangedSubviews(tabs)
layoutIfNeeded()
setSelectedIndex(selectedIndex, animated: false)
}
private func makeTab(_ item: FilterTabBarItem) -> UIButton {
let tab = TabBarButton(type: .custom)
tab.setTitle(item.title, for: .normal)
tab.setTitleColor(titleColorForSelected, for: .selected)
tab.setTitleColor(deselectedTabColor, for: .normal)
tab.tintColor = tintColor
tab.setAttributedTitle(item.attributedTitle, for: .normal)
tab.titleLabel?.lineBreakMode = .byWordWrapping
tab.titleLabel?.textAlignment = .center
tab.setAttributedTitle(addColor(titleColorForSelected, toAttributedString: item.attributedTitle), for: .selected)
tab.setAttributedTitle(addColor(deselectedTabColor, toAttributedString: item.attributedTitle), for: .normal)
tab.accessibilityIdentifier = item.accessibilityIdentifier
tab.accessibilityLabel = item.accessibilityLabel
tab.accessibilityValue = item.accessibilityValue
tab.accessibilityHint = item.accessibilityHint
tab.contentEdgeInsets = item.attributedTitle != nil ?
AppearanceMetrics.buttonInsetsAttributedTitle :
AppearanceMetrics.buttonInsets
tab.sizeToFit()
tab.addTarget(self, action: #selector(tabTapped(_:)), for: .touchUpInside)
return tab
}
private func addColor(_ color: UIColor, toAttributedString attributedString: NSAttributedString?) -> NSAttributedString? {
guard let attributedString = attributedString else {
return nil
}
let mutableString = NSMutableAttributedString(attributedString: attributedString)
mutableString.addAttributes([.foregroundColor: color], range: NSMakeRange(0, mutableString.string.count))
return mutableString
}
private func updateTabSizingConstraints() {
let padding = (tabSizingStyle == .equalWidths) ? 0 : AppearanceMetrics.horizontalPadding
stackViewEdgeConstraints = [
stackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor, constant: padding),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -padding)
]
}
private func activateTabSizingConstraints() {
NSLayoutConstraint.activate(stackViewEdgeConstraints)
switch tabSizingStyle {
case .equalWidths:
stackView.distribution = equalWidthFill
stackView.spacing = equalWidthSpacing
NSLayoutConstraint.activate([stackViewWidthConstraint])
case .fitting:
stackView.distribution = .fill
NSLayoutConstraint.deactivate([stackViewWidthConstraint])
}
}
// MARK: - Tab Selection
@objc
private func tabTapped(_ tab: UIButton) {
guard let index = tabs.firstIndex(of: tab) else {
return
}
setSelectedIndex(index)
sendActions(for: .valueChanged)
}
/// The index of the currently selected tab.
///
private(set) var selectedIndex: Int = 0 {
didSet {
if selectedIndex != oldValue && oldValue < tabs.count {
let oldTab = tabs[oldValue]
oldTab.isSelected = false
}
}
}
var currentlySelectedItem: FilterTabBarItem? {
return items[safe: selectedIndex]
}
func setSelectedIndex(_ index: Int, animated: Bool = true) {
guard items.indices.contains(index) else {
DDLogError("FilterTabBar - Tried to set an invalid index")
return
}
selectedIndex = index
guard let tab = selectedTab else {
return
}
tab.isSelected = true
moveSelectionIndicator(to: selectedIndex, animated: animated)
scroll(to: tab, animated: animated)
}
private var selectedTab: UIButton? {
guard selectedIndex < tabs.count else {
return nil
}
return tabs[selectedIndex]
}
// Used to adjust the position of the selection indicator to track the
// currently selected tab.
private var selectionIndicatorLeadingConstraint: NSLayoutConstraint? = nil
private var selectionIndicatorTrailingConstraint: NSLayoutConstraint? = nil
private func moveSelectionIndicator(to index: Int, animated: Bool = true) {
guard index < tabs.count else {
return
}
let tab = tabs[index]
updateSelectionIndicatorConstraints(for: tab)
if selectionIndicator.isHidden || animated == false {
selectionIndicator.isHidden = false
selectionIndicator.layoutIfNeeded()
} else {
UIView.animate(withDuration: SelectionAnimation.duration,
delay: 0,
usingSpringWithDamping: SelectionAnimation.springDamping,
initialSpringVelocity: SelectionAnimation.initialVelocity,
options: .curveEaseInOut,
animations: {
self.layoutIfNeeded()
})
}
}
/// Intelligently scrolls the tab bar to the specified tab.
///
/// * If the tab's center is within half the bar's width from the leading
/// edge of the bar, the bar will scroll all the way to the beginning.
/// * If the tab's center is within half the bar's width from the trailing
/// edge of the bar, the bar will scroll all the way to the end.
/// * Otherwise, the bar will scroll so that the specified tab is centered.
///
private func scroll(to tab: UIButton, animated: Bool = true) {
// Check the bar has enough content to scroll
guard scrollView.contentSize.width > scrollView.frame.width, bounds.width > 0 else {
return
}
let tabCenterX = scrollView.convert(tab.frame, from: stackView).midX
if tabCenterX <= bounds.midX {
// If the tab is within the first half width of the bar, scroll to the beginning
scrollView.setContentOffset(.zero, animated: animated)
} else if tabCenterX > scrollView.contentSize.width - bounds.midX {
// If the tab is within the last half width of the bar, scroll to the end
scrollView.setContentOffset(CGPoint(x: scrollView.contentSize.width - bounds.width, y: 0), animated: animated)
} else {
// Otherwise scroll so the tab is centered
let centerPoint = CGPoint(x: tabCenterX - bounds.midX, y: 0)
scrollView.setContentOffset(centerPoint, animated: animated)
}
}
/// Move the selection indicator to below the specified tab.
///
private func updateSelectionIndicatorConstraints(for tab: UIButton) {
selectionIndicatorLeadingConstraint?.isActive = false
selectionIndicatorTrailingConstraint?.isActive = false
let buttonInsets = tab.currentAttributedTitle != nil ?
AppearanceMetrics.buttonInsetsAttributedTitle :
AppearanceMetrics.buttonInsets
let leadingConstant = (tabSizingStyle == .equalWidths) ? 0.0 : (tab.contentEdgeInsets.left - buttonInsets.left)
let trailingConstant = (tabSizingStyle == .equalWidths) ? 0.0 : (-tab.contentEdgeInsets.right + buttonInsets.right)
selectionIndicatorLeadingConstraint = selectionIndicator.leadingAnchor.constraint(equalTo: tab.leadingAnchor, constant: leadingConstant)
selectionIndicatorTrailingConstraint = selectionIndicator.trailingAnchor.constraint(equalTo: tab.trailingAnchor, constant: trailingConstant)
selectionIndicatorLeadingConstraint?.isActive = true
selectionIndicatorTrailingConstraint?.isActive = true
}
private enum AppearanceMetrics {
static let height: CGFloat = 46.0
static let bottomDividerHeight: CGFloat = .hairlineBorderWidth
static let selectionIndicatorHeight: CGFloat = 2.0
static let horizontalPadding: CGFloat = 0.0
static let buttonInsets = UIEdgeInsets(top: 14.0, left: 12.0, bottom: 14.0, right: 12.0)
static let buttonInsetsAttributedTitle = UIEdgeInsets(top: 10.0, left: 2.0, bottom: 10.0, right: 2.0)
}
private enum SelectionAnimation {
static let duration: TimeInterval = 0.3
static let springDamping: CGFloat = 0.9
static let initialVelocity: CGFloat = -0.5
}
}
private class TabBarButton: UIButton {
private enum TabFont {
static let maxSize: CGFloat = 28.0
}
override init(frame: CGRect) {
super.init(frame: frame)
setFont()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setFont()
}
private func setFont() {
titleLabel?.font = WPStyleGuide.fontForTextStyle(.subheadline, symbolicTraits: .traitBold, maximumPointSize: TabFont.maxSize)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory {
setFont()
}
}
}
extension FilterTabBar: Accessible {
func prepareForVoiceOver() {
isAccessibilityElement = false
accessibilityTraits = [super.accessibilityTraits, .tabBar]
}
}
|
397079b59d28ed8608a0a3a48d4020a4
| 33.772467 | 148 | 0.65193 | false | false | false | false |
dreamsxin/swift
|
refs/heads/master
|
test/decl/inherit/inherit.swift
|
apache-2.0
|
2
|
// RUN: %target-parse-verify-swift
class A { }
protocol P { }
// Duplicate inheritance
class B : A, A { } // expected-error{{duplicate inheritance from 'A'}}{{12-15=}}
// Duplicate inheritance from protocol
class B2 : P, P { } // expected-error{{duplicate inheritance from 'P'}}{{13-16=}}
// Multiple inheritance
class C : B, A { } // expected-error{{multiple inheritance from classes 'B' and 'A'}}
// Superclass in the wrong position
class D : P, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{12-15=}}{{11-11=A, }}
// Struct inheriting a class
struct S : A { } // expected-error{{non-class type 'S' cannot inherit from class 'A'}}
// Protocol inheriting a class
protocol Q : A { } // expected-error{{non-class type 'Q' cannot inherit from class 'A'}}
// Extension inheriting a class
extension C : A { } // expected-error{{extension of type 'C' cannot inherit from class 'A'}}
// Keywords in inheritance clauses
struct S2 : struct { } // expected-error{{expected identifier for type name}}
// Protocol composition in inheritance clauses
struct S3 : P, protocol<P> { } // expected-error{{duplicate inheritance from 'P'}}
// expected-error@-1{{protocol composition is neither allowed nor needed here}}{{16-25=}}{{26-27=}}
struct S4 : protocol< { } // expected-error{{expected identifier for type name}}
// expected-error@-1{{protocol composition is neither allowed nor needed here}}{{13-23=}}
class GenericBase<T> {}
class GenericSub<T> : GenericBase<T> {} // okay
class InheritGenericParam<T> : T {} // expected-error {{inheritance from non-protocol, non-class type 'T'}}
class InheritBody : T { // expected-error {{use of undeclared type 'T'}}
typealias T = A
}
class InheritBodyBad : fn { // expected-error {{use of undeclared type 'fn'}}
func fn() {}
}
|
de6ce4d6af5cecef9c955472266e46db
| 39.608696 | 130 | 0.667024 | false | false | false | false |
ProjectDent/ARKit-CoreLocation
|
refs/heads/develop
|
Sources/ARKit-CoreLocation/SceneLocationView+ARSCNViewDelegate.swift
|
mit
|
1
|
//
// SceneLocationView+ARSCNViewDelegate.swift
// ARKit+CoreLocation
//
// Created by Ilya Seliverstov on 08/08/2017.
// Copyright © 2017 Project Dent. All rights reserved.
//
import Foundation
import ARKit
import CoreLocation
import MapKit
// MARK: - ARSCNViewDelegate
@available(iOS 11.0, *)
extension SceneLocationView: ARSCNViewDelegate {
public func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
return arViewDelegate?.renderer?(renderer, nodeFor: anchor) ?? nil
}
public func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
arViewDelegate?.renderer?(renderer, didAdd: node, for: anchor)
}
public func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) {
arViewDelegate?.renderer?(renderer, willUpdate: node, for: anchor)
}
public func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
arViewDelegate?.renderer?(renderer, didUpdate: node, for: anchor)
}
public func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
arViewDelegate?.renderer?(renderer, didRemove: node, for: anchor)
}
}
// MARK: - ARSessionObserver
@available(iOS 11.0, *)
extension SceneLocationView {
public func session(_ session: ARSession, didFailWithError error: Error) {
defer {
arViewDelegate?.session?(session, didFailWithError: error)
}
print("session did fail with error: \(error)")
sceneTrackingDelegate?.session(session, didFailWithError: error)
}
public func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
defer {
arViewDelegate?.session?(session, cameraDidChangeTrackingState: camera)
}
switch camera.trackingState {
case .limited(.insufficientFeatures):
print("camera did change tracking state: limited, insufficient features")
case .limited(.excessiveMotion):
print("camera did change tracking state: limited, excessive motion")
case .limited(.initializing):
print("camera did change tracking state: limited, initializing")
case .normal:
print("camera did change tracking state: normal")
case .notAvailable:
print("camera did change tracking state: not available")
case .limited(.relocalizing):
print("camera did change tracking state: limited, relocalizing")
default:
print("camera did change tracking state: unknown...")
}
sceneTrackingDelegate?.session(session, cameraDidChangeTrackingState: camera)
}
public func sessionWasInterrupted(_ session: ARSession) {
defer {
arViewDelegate?.sessionWasInterrupted?(session)
}
print("session was interrupted")
sceneTrackingDelegate?.sessionWasInterrupted(session)
}
public func sessionInterruptionEnded(_ session: ARSession) {
defer {
arViewDelegate?.sessionInterruptionEnded?(session)
}
print("session interruption ended")
sceneTrackingDelegate?.sessionInterruptionEnded(session)
}
@available(iOS 11.3, *)
public func sessionShouldAttemptRelocalization(_ session: ARSession) -> Bool {
return arViewDelegate?.sessionShouldAttemptRelocalization?(session) ?? true
}
public func session(_ session: ARSession, didOutputAudioSampleBuffer audioSampleBuffer: CMSampleBuffer) {
arViewDelegate?.session?(session, didOutputAudioSampleBuffer: audioSampleBuffer)
}
}
// MARK: - SCNSceneRendererDelegate
@available(iOS 11.0, *)
extension SceneLocationView {
public func renderer(_ renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: TimeInterval) {
defer {
arViewDelegate?.renderer?(renderer, didRenderScene: scene, atTime: time)
}
if sceneNode == nil {
sceneNode = SCNNode()
scene.rootNode.addChildNode(sceneNode!)
if showAxesNode {
let axesNode = SCNNode.axesNode(quiverLength: 0.1, quiverThickness: 0.5)
sceneNode?.addChildNode(axesNode)
}
}
if !didFetchInitialLocation {
//Current frame and current location are required for this to be successful
if session.currentFrame != nil,
let currentLocation = sceneLocationManager.currentLocation {
didFetchInitialLocation = true
sceneLocationManager.addSceneLocationEstimate(location: currentLocation)
}
}
}
public func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
arViewDelegate?.renderer?(renderer, updateAtTime: time)
}
public func renderer(_ renderer: SCNSceneRenderer, didApplyAnimationsAtTime time: TimeInterval) {
arViewDelegate?.renderer?(renderer, didApplyAnimationsAtTime: time)
}
public func renderer(_ renderer: SCNSceneRenderer, didSimulatePhysicsAtTime time: TimeInterval) {
arViewDelegate?.renderer?(renderer, didSimulatePhysicsAtTime: time)
}
public func renderer(_ renderer: SCNSceneRenderer, didApplyConstraintsAtTime time: TimeInterval) {
arViewDelegate?.renderer?(renderer, didApplyConstraintsAtTime: time)
}
public func renderer(_ renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: TimeInterval) {
arViewDelegate?.renderer?(renderer, willRenderScene: scene, atTime: time)
}
}
|
648abadd8e4072dffa97aa84d9b00770
| 36.276316 | 116 | 0.68461 | false | false | false | false |
brianjmoore/material-components-ios
|
refs/heads/develop
|
components/ActivityIndicator/examples/ActivityIndicatorExample.swift
|
apache-2.0
|
3
|
/*
Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents.MaterialActivityIndicator
class ActivityIndicatorSwiftController: UIViewController {
struct MDCPalette {
static let blue: UIColor = UIColor(red: 0.129, green: 0.588, blue: 0.953, alpha: 1.0)
static let red: UIColor = UIColor(red: 0.957, green: 0.263, blue: 0.212, alpha: 1.0)
static let green: UIColor = UIColor(red: 0.298, green: 0.686, blue: 0.314, alpha: 1.0)
static let yellow: UIColor = UIColor(red: 1.0, green: 0.922, blue: 0.231, alpha: 1.0)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let width: CGFloat = view.bounds.width / 2
let height: CGFloat = view.bounds.height / 2
//Initialize single color progress indicator
let frame1: CGRect = CGRect(x: width - 16, y: height - 116, width: 32, height: 32)
let activityIndicator1 = MDCActivityIndicator(frame: frame1)
view.addSubview(activityIndicator1)
activityIndicator1.delegate = self
// Set the progress of the indicator
activityIndicator1.progress = 0.6
// Set the progress indicator to determinate
activityIndicator1.indicatorMode = .determinate
activityIndicator1.sizeToFit()
activityIndicator1.startAnimating()
// Initialize indeterminate indicator
let frame2: CGRect = CGRect(x: width - 16, y: height - 16, width: 32, height: 32)
let activityIndicator2 = MDCActivityIndicator(frame: frame2)
view.addSubview(activityIndicator2)
activityIndicator2.delegate = self
activityIndicator2.indicatorMode = .indeterminate
activityIndicator2.sizeToFit()
activityIndicator2.startAnimating()
// Initialize multiple color indicator
let frame3: CGRect = CGRect(x: width - 16, y: height + 84, width: 32, height: 32)
let activityIndicator3 = MDCActivityIndicator(frame: frame3)
view.addSubview(activityIndicator3)
// Pass colors you want to indicator to cycle through
activityIndicator3.cycleColors = [MDCPalette.blue, MDCPalette.red, MDCPalette.green, MDCPalette.yellow]
activityIndicator3.delegate = self
activityIndicator3.indicatorMode = .indeterminate
activityIndicator3.sizeToFit()
activityIndicator3.startAnimating()
// Initialize with different radius and stroke with
let frame4: CGRect = CGRect(x: width - 24, y: height + 176, width: 48, height: 48)
let activityIndicator4 = MDCActivityIndicator(frame: frame4)
view.addSubview(activityIndicator4)
activityIndicator4.delegate = self
// Set the radius of the circle
activityIndicator4.radius = 18.0
activityIndicator4.indicatorMode = .indeterminate
// Set the width of the ring
activityIndicator4.strokeWidth = 4.0
activityIndicator4.sizeToFit()
activityIndicator4.startAnimating()
}
}
extension ActivityIndicatorSwiftController : MDCActivityIndicatorDelegate {
func activityIndicatorAnimationDidFinish(_ activityIndicator: MDCActivityIndicator) {
return
}
// MARK: Catalog by convention
@objc class func catalogBreadcrumbs() -> [String] {
return ["Activity Indicator", "Activity Indicator (Swift)"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
}
|
82611af6d86e4430482f81f98c8a06f1
| 41.204301 | 109 | 0.719745 | false | false | false | false |
IBM-Swift/BluePic
|
refs/heads/master
|
BluePic-iOS/BluePic/Controllers/ImageDetailViewController.swift
|
apache-2.0
|
1
|
/**
* Copyright IBM Corporation 2016
*
* 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
class ImageDetailViewController: UIViewController {
//Image view that shows the image
@IBOutlet weak var imageView: UIImageView!
//dim view that dims the images with a see-through black view
@IBOutlet weak var dimView: UIView!
//back button that when pressed pops the vc on the navigation stack
@IBOutlet weak var backButton: UIButton!
//colection view that shows the tags for the current image displayed
@IBOutlet weak var tagCollectionView: UICollectionView!
//view model that will keep all state and data handling for the image detail vc
var viewModel: ImageDetailViewModel!
/**
Method called upon view did load. It sets up the subviews and the tag collection view
*/
override func viewDidLoad() {
super.viewDidLoad()
setupSubViews()
setupTagCollectionView()
}
/**
Method called upon view will appear. It sets the status bar to be white color
- parameter animated: Bool
*/
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.statusBarStyle = .lightContent
}
/**
Method called by the OS when the application receieves a memory warning
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/**
Method is called when the back button is pressed
- parameter sender: Any
*/
@IBAction func backButtonAction(_ sender: Any) {
_ = self.navigationController?.popViewController(animated: true)
}
}
//UI Setup Methods
extension ImageDetailViewController {
/**
Method sets up the tag collection view
*/
func setupTagCollectionView() {
let layout = KTCenterFlowLayout()
layout.minimumInteritemSpacing = 10.0
layout.minimumLineSpacing = 10.0
layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 15.0)
tagCollectionView.setCollectionViewLayout(layout, animated: false)
tagCollectionView.delegate = self
tagCollectionView.dataSource = self
Utils.registerSupplementaryElementOfKindNibWithCollectionView("ImageInfoHeaderCollectionReusableView", kind: UICollectionElementKindSectionHeader, collectionView: tagCollectionView)
Utils.registerNibWith("TagCollectionViewCell", collectionView: tagCollectionView)
}
/**
Method sets up subviews
*/
func setupSubViews() {
setupImageView()
setupBlurView()
}
/**
Method sets up the image view
*/
func setupImageView() {
if let urlString = viewModel.getImageURLString() {
let nsurl = URL(string: urlString)
imageView.sd_setImage(with: nsurl)
}
}
/**
Method sets up the blur view
*/
func setupBlurView() {
dimView.isHidden = true
let blurViewFrame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
let blurViewHolderView = UIView(frame: blurViewFrame)
let darkBlur = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = blurViewFrame
blurViewHolderView.alpha = 0.90
blurViewHolderView.addSubview(blurView)
imageView.addSubview(blurViewHolderView)
}
}
extension ImageDetailViewController : UICollectionViewDataSource {
/**
Method asks the view model for the number of items in the section
- parameter collectionView: UICollectionView
- parameter section: Int
- returns: Int
*/
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.numberOfItemsInSection(section)
}
/**
Method asks the viewModel for the number of sections in the collection view
- parameter collectionView: UICollectionView
- returns: Int
*/
func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.numberOfSectionsInCollectionView()
}
/**
Method asks the view model to set up the view for supplementary element of kind, aka the header view
- parameter collectionView: UICollectionView
- parameter kind: String
- parameter indexPath: IndexPath
- returns: UICollectionReusableView
*/
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return viewModel.setUpSectionHeaderViewForIndexPath(
indexPath,
kind: kind,
collectionView: collectionView
)
}
/**
Method asks the viewModel to set up the collection view for indexPath
- parameter collectionView: UICollectionView
- parameter indexPath: IndexPath
- returns: UICollectionViewCell
*/
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return viewModel.setUpCollectionViewCell(indexPath, collectionView: collectionView)
}
}
extension ImageDetailViewController: UICollectionViewDelegateFlowLayout {
/**
Method asks the viewModel for the size for item at indexPath
- parameter collectionView: UICollectionView
- parameter collectionViewLayout: UICollectionViewLayout
- parameter indexPath: IndexPath
- returns: CGSize
*/
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return viewModel.sizeForItemAtIndexPath(indexPath, collectionView: collectionView)
}
/**
Method asks the viewModel for the reference size for header in section
- parameter collectionView: UICollectionView
- parameter collectionViewLayout: UICollectionViewLayout
- parameter section: Int
- returns: CGSize
*/
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return viewModel.referenceSizeForHeaderInSection(collectionView, layout: collectionViewLayout, section: section, superViewHeight: self.view.frame.size.height)
}
}
extension ImageDetailViewController : UICollectionViewDelegate {
/**
Method is called when a cell in the collection view is selected
- parameter collectionView: UICollectionView
- parameter indexPath: IndexPath
*/
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let vc = viewModel.getFeedViewControllerForTagSearchAtIndexPath(indexPath) {
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
103e2b9d1cbbdd6dfd5dd0f1ff2f0f16
| 29.783673 | 189 | 0.700743 | false | false | false | false |
Syerram/asphalos
|
refs/heads/master
|
asphalos/FormSegmentedControlCell.swift
|
mit
|
1
|
//
// FormSegmentedControlCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 21/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
class FormSegmentedControlCell: FormBaseCell {
/// MARK: Cell views
let titleLabel = UILabel()
let segmentedControl = UISegmentedControl()
/// MARK: Properties
private var customConstraints: [AnyObject]!
/// MARK: FormBaseCell
override func configure() {
super.configure()
selectionStyle = .None
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
segmentedControl.setTranslatesAutoresizingMaskIntoConstraints(false)
titleLabel.setContentCompressionResistancePriority(500, forAxis: .Horizontal)
segmentedControl.setContentCompressionResistancePriority(500, forAxis: .Horizontal)
titleLabel.font = UIFont(name: Globals.Theme.RegularFont, size: 16)
contentView.addSubview(titleLabel)
contentView.addSubview(segmentedControl)
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
segmentedControl.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
}
override func update() {
super.update()
titleLabel.text = rowDescriptor.title
updateSegmentedControl()
var idx = 0
if rowDescriptor.value != nil {
for optionValue in rowDescriptor.options {
if optionValue as! NSObject == rowDescriptor.value {
segmentedControl.selectedSegmentIndex = idx
break
}
++idx
}
}
}
override func constraintsViews() -> [String : UIView] {
return ["titleLabel" : titleLabel, "segmentedControl" : segmentedControl]
}
override func defaultVisualConstraints() -> [String] {
if titleLabel.text != nil && count(titleLabel.text!) > 0 {
return ["H:|-16-[titleLabel]-16-[segmentedControl]-16-|"]
}
else {
return ["H:|-16-[segmentedControl]-16-|"]
}
}
/// MARK: Actions
func valueChanged(sender: UISegmentedControl) {
let optionValue = rowDescriptor.options[sender.selectedSegmentIndex] as? NSObject
rowDescriptor.value = optionValue
}
/// MARK: Private
private func updateSegmentedControl() {
segmentedControl.removeAllSegments()
var idx = 0
for optionValue in rowDescriptor.options {
segmentedControl.insertSegmentWithTitle(rowDescriptor.titleForOptionValue(optionValue as! NSObject), atIndex: idx, animated: false)
++idx
}
}
}
|
f8a81e16b35fa64656ce682bfc641a86
| 32.126316 | 191 | 0.631395 | false | false | false | false |
mitchtreece/Spider
|
refs/heads/master
|
Spider/Classes/Core/SSE/Events/EventProtocol.swift
|
mit
|
1
|
//
// EventProtocol.swift
// Spider-Web
//
// Created by Mitch Treece on 10/6/20.
//
import Foundation
/// Protocol describing the characteristics of a server-side-event.
public protocol EventProtocol {
/// The event's unique id.
var id: String? { get }
/// The event's type (or name).
var type: String? { get }
/// The event's data payload.
var data: String? { get }
/// The event's retry time.
var retryTime: Int? { get }
}
public extension EventProtocol /* JSON data */ {
/// A `JSON` representation of the event data.
var jsonData: JSON? {
guard let string = self.data,
let data = string.data(using: .utf8) else { return nil }
return try? JSONSerialization.jsonObject(
with: data,
options: []
) as? JSON
}
/// A `[JSON]` representation of the event data.
var jsonArrayData: [JSON]? {
guard let string = self.data,
let data = string.data(using: .utf8) else { return nil }
return try? JSONSerialization.jsonObject(
with: data,
options: []
) as? [JSON]
}
}
internal extension EventProtocol /* Retry */ {
var isRetry: Bool {
let hasAnyValue = (self.id == nil || self.type == nil || self.data == nil)
if let _ = self.retryTime, !hasAnyValue {
return true
}
return false
}
}
|
4913610d88d19c11d84a3a24e2cd48f8
| 20.746479 | 82 | 0.522021 | false | false | false | false |
MasterGerhard/ParkShark
|
refs/heads/master
|
GMap1/Views/UIViewExtension.swift
|
cc0-1.0
|
2
|
//
// UIViewExtension.swift
// Feed Me
//
// Created by Ron Kliffer on 8/30/14.
// Copyright (c) 2014 Ron Kliffer. All rights reserved.
//
import UIKit
extension UIView {
func lock() {
if let lockView = viewWithTag(10) {
//View is already locked
}
else {
let lockView = UIView(frame: bounds)
lockView.backgroundColor = UIColor(white: 0.0, alpha: 0.75)
lockView.tag = 10
lockView.alpha = 0.0
let activity = UIActivityIndicatorView(activityIndicatorStyle: .White)
activity.hidesWhenStopped = true
activity.center = lockView.center
lockView.addSubview(activity)
activity.startAnimating()
addSubview(lockView)
UIView.animateWithDuration(0.2) {
lockView.alpha = 1.0
}
}
}
func unlock() {
if let lockView = self.viewWithTag(10) {
UIView.animateWithDuration(0.2, animations: {
lockView.alpha = 0.0
}) { finished in
lockView.removeFromSuperview()
}
}
}
func fadeOut(duration: NSTimeInterval) {
UIView.animateWithDuration(duration) {
self.alpha = 0.0
}
}
func fadeIn(duration: NSTimeInterval) {
UIView.animateWithDuration(duration) {
self.alpha = 1.0
}
}
class func viewFromNibName(name: String) -> UIView? {
let views = NSBundle.mainBundle().loadNibNamed(name, owner: nil, options: nil)
return views.first as? UIView
}
}
|
219178c6c512cc70ae4cf73aeb3e54f4
| 22.688525 | 82 | 0.628374 | false | false | false | false |
smoope/swift-client-conversation
|
refs/heads/master
|
Framework/Source/PreviewCell.swift
|
apache-2.0
|
1
|
//
// Copyright 2017 smoope GmbH
//
// 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 SmoopeService
internal class PreviewCell: BaseConversationCell, ReusableLoadingImageView {
private static let _defaultImage: UIImage? = nil
private static let _downloadImage: UIImage? = nil
internal var imageView: UIImageView
internal var defaultImage: UIImage? { return nil }
private var fileMetaBackgroundView: UIVisualEffectView
private var arrowImageView: UIImageView
private var sizeLabel: UILabel
private var activityIndicatorView: UIActivityIndicatorView
private weak var file: Service.MediaFile?
internal override init(frame: CGRect) {
imageView = UIImageView(frame: CGRect(origin: .zero, size: frame.size))
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.backgroundColor = .white
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.cornerRadius = 16
imageView.layer.borderWidth = 1
imageView.layer.borderColor = UIColor(white: 0, alpha: 0.1).cgColor
fileMetaBackgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
fileMetaBackgroundView.translatesAutoresizingMaskIntoConstraints = false
fileMetaBackgroundView.layer.cornerRadius = 25
fileMetaBackgroundView.layer.masksToBounds = true
fileMetaBackgroundView.contentView.heightAnchor.constraint(equalToConstant: 50).isActive = true
arrowImageView = UIImageView(image: UIImage(named: "download-arrow", in: Bundle(for: PreviewCell.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate))
arrowImageView.translatesAutoresizingMaskIntoConstraints = false
arrowImageView.tintColor = .darkText
sizeLabel = UILabel(frame: .zero)
sizeLabel.translatesAutoresizingMaskIntoConstraints = false
sizeLabel.textColor = .darkText
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorView.color = .darkText
super.init(frame: frame)
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
sizeLabel.text = ""
}
internal func prepare(messagePart part: MessagePart) {
sizeLabel.text = ByteCountFormatter.spc_cachedFormatter.string(fromByteCount: part.fileSize)
guard let file = Service.MediaFile.findOrCreate(messagePart: part)
else { return }
updateActionArea(file)
file.add(delegate: self)
}
fileprivate func updateActionArea(_ file: Service.MediaFile) {
switch file.status {
case .remote:
showRemote()
case .loading:
showLoading()
case .cached:
showCached()
case .error:
showError()
}
}
fileprivate func showRemote() {
fileMetaBackgroundView.removeFromSuperview()
activityIndicatorView.removeFromSuperview()
sizeLabel.removeFromSuperview()
arrowImageView.removeFromSuperview()
contentView.addSubview(fileMetaBackgroundView)
contentView.centerXAnchor.constraint(equalTo: fileMetaBackgroundView.centerXAnchor).isActive = true
contentView.centerYAnchor.constraint(equalTo: fileMetaBackgroundView.centerYAnchor).isActive = true
let content = fileMetaBackgroundView.contentView
content.addSubview(arrowImageView)
content.addSubview(sizeLabel)
arrowImageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 12).isActive = true
content.trailingAnchor.constraint(equalTo: sizeLabel.trailingAnchor, constant: 12).isActive = true
content.centerYAnchor.constraint(equalTo: sizeLabel.centerYAnchor).isActive = true
sizeLabel.leadingAnchor.constraint(equalTo: arrowImageView.trailingAnchor, constant: 8).isActive = true
arrowImageView.centerYAnchor.constraint(equalTo: sizeLabel.centerYAnchor).isActive = true
}
fileprivate func showLoading() {
fileMetaBackgroundView.removeFromSuperview()
activityIndicatorView.removeFromSuperview()
sizeLabel.removeFromSuperview()
arrowImageView.removeFromSuperview()
contentView.addSubview(fileMetaBackgroundView)
contentView.centerXAnchor.constraint(equalTo: fileMetaBackgroundView.centerXAnchor).isActive = true
contentView.centerYAnchor.constraint(equalTo: fileMetaBackgroundView.centerYAnchor).isActive = true
let content = fileMetaBackgroundView.contentView
content.addSubview(activityIndicatorView)
activityIndicatorView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 8).isActive = true
content.trailingAnchor.constraint(equalTo: activityIndicatorView.trailingAnchor, constant: 6).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: content.centerYAnchor, constant: 1).isActive = true
activityIndicatorView.startAnimating()
}
fileprivate func showCached() {
fileMetaBackgroundView.removeFromSuperview()
activityIndicatorView.removeFromSuperview()
sizeLabel.removeFromSuperview()
arrowImageView.removeFromSuperview()
}
fileprivate func showError() {
showRemote()
}
internal override class func size(in collectionView: UICollectionView, with userInfo: [ConversationCellUserInfoKey : Any]?) -> CGSize {
return .init(width: 200, height: 200)
}
}
extension PreviewCell: ServiceDownloadManagerDelegate {
func startDownload(file: Service.MediaFile) {
guard superview != nil else { return }
DispatchQueue.main.async { [weak self] in
self?.updateActionArea(file)
}
}
func updateDownload(file: Service.MediaFile, progress: Float) {
guard superview != nil else { return }
}
func endDownload(file: Service.MediaFile, error: Error?) {
guard superview != nil else { return }
DispatchQueue.main.async { [weak self] in
self?.updateActionArea(file)
}
}
}
|
12c363ac6117b1d4ff2bf9c41881706d
| 36.096447 | 169 | 0.683771 | false | false | false | false |
peteratseneca/dps923winter2015
|
refs/heads/master
|
Project_Templates/ClassesV1/Classes/Model.swift
|
mit
|
1
|
//
// Model.swift
// Classes
//
// Created by Peter McIntyre on 2015-02-01.
// Copyright (c) 2015 School of ICT, Seneca College. All rights reserved.
//
import CoreData
class Model {
// MARK: - Private properties
private var cdStack: CDStack!
lazy private var applicationDocumentsDirectory: NSURL = {
return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
}()
// MARK: - Public properties
lazy var frc_example: NSFetchedResultsController = {
// Use this as a template to create other fetched results controllers
let frc = self.cdStack.frcForEntityNamed("Example", withPredicateFormat: nil, predicateObject: nil, sortDescriptors: "attribute1,true", andSectionNameKeyPath: nil)
return frc
}()
// MARK: - Public methods
init() {
// Check whether the app is being launched for the first time
// If yes, check if there's an object store file in the app bundle
// If yes, copy the object store file to the Documents directory
// If no, create some new data if you need to
// URL to the object store file in the app bundle
let storeFileInBundle: NSURL? = NSBundle.mainBundle().URLForResource("ObjectStore", withExtension: "sqlite")
// URL to the object store file in the Documents directory
let storeFileInDocumentsDirectory: NSURL = applicationDocumentsDirectory.URLByAppendingPathComponent("ObjectStore.sqlite")
// System file manager
let fs: NSFileManager = NSFileManager()
// Check whether this is the first launch of the app
let isFirstLaunch: Bool = !fs.fileExistsAtPath(storeFileInDocumentsDirectory.path!)
// Check whether the app is supplied with starter data in the app bundle
let hasStarterData: Bool = storeFileInBundle != nil
if isFirstLaunch {
if hasStarterData {
// Use the supplied starter data
fs.copyItemAtURL(storeFileInBundle!, toURL: storeFileInDocumentsDirectory, error: nil)
// Initialize the Core Data stack
cdStack = CDStack()
} else {
// Initialize the Core Data stack before creating new data
cdStack = CDStack()
// Create some new data
StoreInitializer.create(cdStack)
}
} else {
// This app has been used/started before, so initialize the Core Data stack
cdStack = CDStack()
}
}
func saveChanges() { cdStack.saveContext() }
// Add more methods here for data maintenance
// For example, get-all, get-some, get-one, add, update, delete
// And other command-oriented operations
}
|
fb33220926dece197d30c10d5085d44e
| 33.639535 | 171 | 0.611279 | false | false | false | false |
Off-Piste/Trolley.io
|
refs/heads/master
|
Trolley/Database/TRLDatabase-Objc/TRLRequest-Objc.swift
|
mit
|
2
|
//
// TRLNetworkManagerExt-Objc.swift
// Pods
//
// Created by Harry Wright on 03.07.17.
//
//
import Foundation
import PromiseKit
import SwiftyJSON
@available(swift, introduced: 1.0, obsoleted: 2.0)
public extension TRLRequest {
// MARK: Obj-C | JSON
@available(swift, introduced: 1.0, obsoleted: 1.0)
@objc(responseJSON)
func responseJSONPromise() -> AnyPromise {
let promise = Promise<Any> { fullfill, reject in
self.responseJSON(handler: { (json, error) in
if error != nil {
reject(error!)
} else {
if json.arrayObject == nil || json.dictionaryObject == nil {
reject(createError("JSON is nil for [\(json.rawString() ?? "")]"))
} else {
if json.dictionaryObject != nil { fullfill(json.dictionaryObject!) }
else if json.arrayObject != nil { fullfill(json.arrayObject!) }
else { fatalError("JSON Error") }
}
}
})
}
return AnyPromise(promise)
}
@available(swift, introduced: 1.0, obsoleted: 1.0)
@objc(responseJSONArray:)
func responseJSONArray(withBlock block:@escaping ([Any], Error?) -> Void) {
self.responseJSON(handler: { (json, error) in
if error != nil { block([], error); return }
if json.arrayObject == nil {
block([], createError("Dictionary is nil for [\(json.rawString() ?? "")]"))
} else {
block(json.arrayObject!, nil)
}
})
}
@available(swift, introduced: 1.0, obsoleted: 1.0)
@objc(responseJSONDictionary:)
func responseJSONDictionary(withBlock block:@escaping ([String : Any], Error?) -> Void) {
self.responseJSON(handler: { (json, error) in
if error != nil { block([:], error); return }
if json.dictionaryObject == nil {
block([:], createError("Dictionary is nil for [\(json.rawString() ?? "")]"))
} else {
block(json.dictionaryObject!, nil)
}
})
}
}
|
e03023f27d750326348299124b21ba2e
| 32.073529 | 93 | 0.51534 | false | false | false | false |
GenerallyHelpfulSoftware/ATSCgh
|
refs/heads/master
|
Classes/Core Data Categories/NSDate+DigitalTV.swift
|
mit
|
1
|
//
// NSDate+DigitalTV.swift
// Signal GH
//
// Created by Glenn Howes on 4/8/17.
// Copyright © 2017 Generally Helpful Software. All rights reserved.
//
import Foundation
public extension Date
{
public static func startTimeNearestMinute(toDate baseTime: Date) -> UInt64
{
let seconds = rint(baseTime.timeIntervalSince1970)
var result : UInt64 = UInt64(seconds)+30
result /= 60
result *= 60
return result
}
public var dateAtNearestMinute : Date
{
let timeIntervalNearestMinute = TimeInterval(Date.startTimeNearestMinute(toDate: self))
guard self.timeIntervalSince1970 != timeIntervalNearestMinute else
{
return self
}
return Date(timeIntervalSince1970: timeIntervalNearestMinute)
}
}
|
bdafa02b764842e7b29458e2f4effef3
| 23.636364 | 95 | 0.661747 | false | false | false | false |
johndpope/objc2swift
|
refs/heads/develop
|
src/test/resources/if_statement_sample.swift
|
mit
|
1
|
class IfStatementSample: NSObject, SomeProtocol {
@IBOutlet var label: UILabel!
func fuga() {
if a == 0 {
b = a * b - 1 / a
}
if a > 2 {
b = 2
}
if a <= 1 {
b = 3
}
if a && b {
b = 1
}
if x && y {
a = b + c
}
if a {
b = 1
if b {
c = d
}
}
if a == b {
return 1
}
if a == b {
return 2
}
if comps.containsObject("画像") {
return YSSSearchTypeImage
} else {
return YSSSearchTypeDefault
}
if comps.containsObject("画像") {
return YSSSearchTypeImage
} else {
return YSSSearchTypeDefault
}
if comps.containsObject("画像") {
a = b + c
return YSSSearchTypeImage
} else {
if comps.containsObject("動画") {
a = b - c
return YSSSearchTypeVideo
} else {
a = b * c
return YSSSearchTypeDefault
}
}
if comps.containsObject("画像2") {
return YSSSearchTypeImage
} else {
if comps.containsObject("動画2") {
return YSSSearchTypeVideo
} else {
return YSSSearchTypeDefault
}
}
}
}
|
9346662e96637b13e6ef138e8635608a
| 17.822785 | 49 | 0.376597 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
refs/heads/develop
|
WordPressKit/WordPressKit/RemotePerson.swift
|
gpl-2.0
|
2
|
import Foundation
import WordPressShared
// MARK: - Defines all of the peroperties a Person may have
//
public protocol RemotePerson {
/// Properties
///
var ID: Int { get }
var username: String { get }
var firstName: String? { get }
var lastName: String? { get }
var displayName: String { get }
var role: String { get }
var siteID: Int { get }
var linkedUserID: Int { get }
var avatarURL: URL? { get }
var isSuperAdmin: Bool { get }
var fullName: String { get }
/// Static Properties
///
static var kind: PersonKind { get }
/// Initializers
///
init(ID: Int,
username: String,
firstName: String?,
lastName: String?,
displayName: String,
role: String,
siteID: Int,
linkedUserID: Int,
avatarURL: URL?,
isSuperAdmin: Bool)
}
// MARK: - Specifies all of the Roles a Person may have
//
public struct RemoteRole {
public let slug: String
public let name: String
public init(slug: String, name: String) {
self.slug = slug
self.name = name
}
}
extension RemoteRole {
public static let viewer = RemoteRole(slug: "follower", name: NSLocalizedString("Viewer", comment: "User role badge"))
public static let follower = RemoteRole(slug: "follower", name: NSLocalizedString("Follower", comment: "User role badge"))
}
// MARK: - Specifies all of the possible Person Types that might exist.
//
public enum PersonKind: Int {
case user = 0
case follower = 1
case viewer = 2
}
// MARK: - Defines a Blog's User
//
public struct User: RemotePerson {
public let ID: Int
public let username: String
public let firstName: String?
public let lastName: String?
public let displayName: String
public let role: String
public let siteID: Int
public let linkedUserID: Int
public let avatarURL: URL?
public let isSuperAdmin: Bool
public static let kind = PersonKind.user
public init(ID: Int,
username: String,
firstName: String?,
lastName: String?,
displayName: String,
role: String,
siteID: Int,
linkedUserID: Int,
avatarURL: URL?,
isSuperAdmin: Bool) {
self.ID = ID
self.username = username
self.firstName = firstName
self.lastName = lastName
self.displayName = displayName
self.role = role
self.siteID = siteID
self.linkedUserID = linkedUserID
self.avatarURL = avatarURL
self.isSuperAdmin = isSuperAdmin
}
}
// MARK: - Defines a Blog's Follower
//
public struct Follower: RemotePerson {
public let ID: Int
public let username: String
public let firstName: String?
public let lastName: String?
public let displayName: String
public let role: String
public let siteID: Int
public let linkedUserID: Int
public let avatarURL: URL?
public let isSuperAdmin: Bool
public static let kind = PersonKind.follower
public init(ID: Int,
username: String,
firstName: String?,
lastName: String?,
displayName: String,
role: String,
siteID: Int,
linkedUserID: Int,
avatarURL: URL?,
isSuperAdmin: Bool) {
self.ID = ID
self.username = username
self.firstName = firstName
self.lastName = lastName
self.displayName = displayName
self.role = role
self.siteID = siteID
self.linkedUserID = linkedUserID
self.avatarURL = avatarURL
self.isSuperAdmin = isSuperAdmin
}
}
// MARK: - Defines a Blog's Viewer
//
public struct Viewer: RemotePerson {
public let ID: Int
public let username: String
public let firstName: String?
public let lastName: String?
public let displayName: String
public let role: String
public let siteID: Int
public let linkedUserID: Int
public let avatarURL: URL?
public let isSuperAdmin: Bool
public static let kind = PersonKind.viewer
public init(ID: Int,
username: String,
firstName: String?,
lastName: String?,
displayName: String,
role: String,
siteID: Int,
linkedUserID: Int,
avatarURL: URL?,
isSuperAdmin: Bool) {
self.ID = ID
self.username = username
self.firstName = firstName
self.lastName = lastName
self.displayName = displayName
self.role = role
self.siteID = siteID
self.linkedUserID = linkedUserID
self.avatarURL = avatarURL
self.isSuperAdmin = isSuperAdmin
}
}
// MARK: - Extensions
//
public extension RemotePerson {
var fullName: String {
let first = firstName ?? String()
let last = lastName ?? String()
let separator = (first.isEmpty == false && last.isEmpty == false) ? " " : ""
return "\(first)\(separator)\(last)"
}
}
// MARK: - Operator Overloading
//
public func ==<T: RemotePerson>(lhs: T, rhs: T) -> Bool {
return lhs.ID == rhs.ID
&& lhs.username == rhs.username
&& lhs.firstName == rhs.firstName
&& lhs.lastName == rhs.lastName
&& lhs.displayName == rhs.displayName
&& lhs.role == rhs.role
&& lhs.siteID == rhs.siteID
&& lhs.linkedUserID == rhs.linkedUserID
&& lhs.avatarURL == rhs.avatarURL
&& lhs.isSuperAdmin == rhs.isSuperAdmin
&& type(of: lhs) == type(of: rhs)
}
|
44b587dcff678e4ada57381c69205ffc
| 26.946078 | 126 | 0.593405 | false | false | false | false |
ricobeck/Swell
|
refs/heads/master
|
Swell/Formatter.swift
|
apache-2.0
|
1
|
//
// Formatter.swift
// Swell
//
// Created by Hubert Rabago on 6/20/14.
// Copyright (c) 2014 Minute Apps LLC. All rights reserved.
//
import Foundation
/// A Log Formatter implementation generates the string that will be sent to a log location
/// if the log level requirement is met by a call to log a message.
public protocol LogFormatter {
/// Formats the message provided for the given logger
func formatLog<T>(logger: Logger, level: LogLevel, @autoclosure message: () -> T,
filename: String?, line: Int?, function: String?) -> String;
/// Returns an instance of this class given a configuration string
static func logFormatterForString(formatString: String) -> LogFormatter;
/// Returns a string useful for describing this class and how it is configured
func description() -> String;
}
public enum QuickFormatterFormat: Int {
case MessageOnly = 0x0001
case LevelMessage = 0x0101
case NameMessage = 0x0011
case LevelNameMessage = 0x0111
case DateLevelMessage = 0x1101
case DateMessage = 0x1001
case All = 0x1111
}
/// QuickFormatter provides some limited options for formatting log messages.
/// Its primary advantage over FlexFormatter is speed - being anywhere from 20% to 50% faster
/// because of its limited options.
public class QuickFormatter: LogFormatter {
let format: QuickFormatterFormat
public init(format: QuickFormatterFormat = .LevelNameMessage) {
self.format = format
}
public func formatLog<T>(logger: Logger, level: LogLevel, @autoclosure message givenMessage: () -> T,
filename: String?, line: Int?, function: String?) -> String {
var s: String;
let message = givenMessage()
switch format {
case .LevelNameMessage:
s = "\(level.label) \(logger.name): \(message)";
case .DateLevelMessage:
s = "\(NSDate()) \(level.label): \(message)";
case .MessageOnly:
s = "\(message)";
case .NameMessage:
s = "\(logger.name): \(message)";
case .LevelMessage:
s = "\(level.label): \(message)";
case .DateMessage:
s = "\(NSDate()) \(message)";
case .All:
s = "\(NSDate()) \(level.label) \(logger.name): \(message)";
}
return s
}
public class func logFormatterForString(formatString: String) -> LogFormatter {
var format: QuickFormatterFormat
switch formatString {
case "LevelNameMessage": format = .LevelNameMessage
case "DateLevelMessage": format = .DateLevelMessage
case "MessageOnly": format = .MessageOnly
case "LevelMessage": format = .LevelMessage
case "NameMessage": format = .NameMessage
case "DateMessage": format = .DateMessage
default: format = .All
}
return QuickFormatter(format: format)
}
public func description() -> String {
var s: String;
switch format {
case .LevelNameMessage:
s = "LevelNameMessage";
case .DateLevelMessage:
s = "DateLevelMessage";
case .MessageOnly:
s = "MessageOnly";
case .LevelMessage:
s = "LevelMessage";
case .NameMessage:
s = "NameMessage";
case .DateMessage:
s = "DateMessage";
case .All:
s = "All";
}
return "QuickFormatter format=\(s)"
}
}
public enum FlexFormatterPart: Int {
case DATE
case NAME
case LEVEL
case MESSAGE
case LINE
case FUNC
}
/// FlexFormatter provides more control over the log format, allowing
/// the flexibility to specify what data appears and on what order.
public class FlexFormatter: LogFormatter {
var format: [FlexFormatterPart]
public init(parts: FlexFormatterPart...) {
format = parts
// Same thing as below
//format = [FlexFormatterPart]()
//for part in parts {
// format += part
//}
}
/// This overload is needed (as of Beta 3) because
/// passing an array to a variadic param is not yet supported
init(parts: [FlexFormatterPart]) {
format = parts
}
func getFunctionFormat(function: String) -> String {
var result = function;
if (result.hasPrefix("Optional(")) {
let len = "Optional(".characters.count
let start = result.startIndex.advancedBy(len)
let end = result.endIndex.advancedBy(-len)
let range = start..<end
result = result[range]
}
if (!result.hasSuffix(")")) {
result = result + "()"
}
return result
}
public func formatLog<T>(logger: Logger, level: LogLevel, @autoclosure message givenMessage: () -> T,
filename: String?, line: Int?, function: String?) -> String {
var logMessage = ""
for (index, part) in format.enumerate() {
switch part {
case .MESSAGE:
let message = givenMessage()
logMessage += "\(message)"
case .NAME: logMessage += logger.name
case .LEVEL: logMessage += level.label
case .DATE: logMessage += NSDate().description
case .LINE:
if (filename != nil) && (line != nil) {
logMessage += "[\((filename! as NSString).lastPathComponent):\(line!)]"
}
case .FUNC:
if (function != nil) {
let output = getFunctionFormat(function!)
logMessage += "[\(output)]"
}
}
if (index < format.count-1) {
if (format[index+1] == .MESSAGE) {
logMessage += ":"
}
logMessage += " "
}
}
return logMessage
}
public class func logFormatterForString(formatString: String) -> LogFormatter {
var formatSpec = [FlexFormatterPart]()
let parts = formatString.uppercaseString.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
for part in parts {
switch part {
case "MESSAGE": formatSpec += [.MESSAGE]
case "NAME": formatSpec += [.NAME]
case "LEVEL": formatSpec += [.LEVEL]
case "LINE": formatSpec += [.LINE]
case "FUNC": formatSpec += [.FUNC]
default: formatSpec += [.DATE]
}
}
return FlexFormatter(parts: formatSpec)
}
public func description() -> String {
var desc = ""
for (index, part) in format.enumerate() {
switch part {
case .MESSAGE: desc += "MESSAGE"
case .NAME: desc += "NAME"
case .LEVEL: desc += "LEVEL"
case .DATE: desc += "DATE"
case .LINE: desc += "LINE"
case .FUNC: desc += "FUNC"
}
if (index < format.count-1) {
desc += " "
}
}
return "FlexFormatter with \(desc)"
}
}
|
80c0bded6582638485cbcac0d4f92984
| 31.80531 | 126 | 0.544106 | false | false | false | false |
PerfectExamples/Perfect-Authentication-Demo
|
refs/heads/master
|
Sources/PageHandlers.swift
|
apache-2.0
|
1
|
//
// PageHandlers.swift
// Perfect-Authentication
//
// Created by Jonathan Guthrie on 2017-01-18.
//
//
import PerfectMustache
import PerfectHTTP
public struct MustacheHandler: MustachePageHandler {
var context: [String: Any]
public func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector) {
contxt.extendValues(with: context)
do {
contxt.webResponse.setHeader(.contentType, value: "text/html")
try contxt.requestCompleted(withCollector: collector)
} catch {
let response = contxt.webResponse
response.status = .internalServerError
response.appendBody(string: "\(error)")
response.completed()
}
}
public init(context: [String: Any] = [String: Any]()) {
self.context = context
}
}
extension HTTPResponse {
public func render(template: String, context: [String: Any] = [String: Any]()) {
mustacheRequest(request: self.request, response: self, handler: MustacheHandler(context: context), templatePath: request.documentRoot + "/\(template).mustache")
}
}
|
ac5b7b8aff0f0913f10a5bf97a04bf41
| 27.702703 | 162 | 0.741996 | false | false | false | false |
esttorhe/eidolon
|
refs/heads/master
|
Kiosk/Bid Fulfillment/ConfirmYourBidPINViewController.swift
|
mit
|
2
|
import UIKit
import Moya
import ReactiveCocoa
import Swift_RAC_Macros
class ConfirmYourBidPINViewController: UIViewController {
dynamic var pin = ""
@IBOutlet var keypadContainer: KeypadContainerView!
@IBOutlet var pinTextField: TextField!
@IBOutlet var confirmButton: Button!
@IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView!
lazy var pinSignal: RACSignal = { self.keypadContainer.stringValueSignal }()
lazy var provider: ReactiveCocoaMoyaProvider<ArtsyAPI> = Provider.sharedProvider
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> ConfirmYourBidPINViewController {
return storyboard.viewControllerWithID(.ConfirmYourBidPIN) as! ConfirmYourBidPINViewController
}
override func viewDidLoad() {
super.viewDidLoad()
RAC(self, "pin") <~ pinSignal
RAC(pinTextField, "text") <~ pinSignal
RAC(fulfillmentNav().bidDetails, "bidderPIN") <~ pinSignal
let pinExistsSignal = pinSignal.map { ($0 as! String).isNotEmpty }
bidDetailsPreviewView.bidDetails = fulfillmentNav().bidDetails
/// verify if we can connect with number & pin
confirmButton.rac_command = RACCommand(enabled: pinExistsSignal) { [weak self] _ in
guard let strongSelf = self else { return RACSignal.empty() }
let phone = strongSelf.fulfillmentNav().bidDetails.newUser.phoneNumber ?? ""
let endpoint: ArtsyAPI = ArtsyAPI.Me
let loggedInProvider = strongSelf.providerForPIN(strongSelf.pin, number: phone)
return loggedInProvider.request(endpoint).filterSuccessfulStatusCodes().doNext { _ in
// If the request to ArtsyAPI.Me succeeds, we have logged in and can use this provider.
self?.fulfillmentNav().loggedInProvider = loggedInProvider
}.then {
// We want to put the data we've collected up to the server.
self?.fulfillmentNav().updateUserCredentials() ?? RACSignal.empty()
}.then {
// This looks for credit cards on the users account, and sends them on the signal
self?.checkForCreditCard() ?? RACSignal.empty()
}.doNext { (cards) in
// If the cards list doesn't exist, or its empty, then perform the segue to collect one.
// Otherwise, proceed directly to the loading view controller to place the bid.
if (cards as? [Card]).isNilOrEmpty {
self?.performSegue(.ArtsyUserviaPINHasNotRegisteredCard)
} else {
self?.performSegue(.PINConfirmedhasCard)
}
}.doError({ [weak self] (error) -> Void in
self?.showAuthenticationError()
return
})
}
}
@IBAction func forgotPINTapped(sender: AnyObject) {
let auctionID = fulfillmentNav().auctionID
let number = fulfillmentNav().bidDetails.newUser.phoneNumber ?? ""
let endpoint: ArtsyAPI = ArtsyAPI.BidderDetailsNotification(auctionID: auctionID, identifier: number)
let alertController = UIAlertController(title: "Forgot PIN", message: "We have sent your bidder details to your device.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Back", style: .Cancel) { (_) in }
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true) {}
XAppRequest(endpoint, provider: Provider.sharedProvider).filterSuccessfulStatusCodes().subscribeNext { (_) -> Void in
// Necessary to subscribe to the actual signal. This should be in a RACCommand of the button, instead.
logger.log("Sent forgot PIN request")
}
}
func providerForPIN(pin: String, number: String) -> ReactiveCocoaMoyaProvider<ArtsyAPI> {
let newEndpointsClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in
let endpoint: Endpoint<ArtsyAPI> = Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(200, {target.sampleData}), method: target.method, parameters: target.parameters)
let auctionID = self.fulfillmentNav().auctionID
return endpoint.endpointByAddingParameters(["auction_pin": pin, "number": number, "sale_id": auctionID])
}
return ReactiveCocoaMoyaProvider(endpointClosure: newEndpointsClosure, endpointResolver: endpointResolver(), stubBehavior: Provider.APIKeysBasedStubBehaviour)
}
func showAuthenticationError() {
confirmButton.flashError("Wrong PIN")
pinTextField.flashForError()
keypadContainer.resetCommand.execute(nil)
}
func checkForCreditCard() -> RACSignal {
let endpoint: ArtsyAPI = ArtsyAPI.MyCreditCards
let authProvider = self.fulfillmentNav().loggedInProvider!
return authProvider.request(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(Card.self)
}
}
private extension ConfirmYourBidPINViewController {
@IBAction func dev_loggedInTapped(sender: AnyObject) {
self.performSegue(.PINConfirmedhasCard)
}
}
|
c3eaa38ff0b134523f106d9e20cfe9af
| 43.551724 | 189 | 0.674666 | false | false | false | false |
sarunw/SWAnimatedTabBarController
|
refs/heads/master
|
SWAnimatedTabBarController/SWAnimatedTabBarItem.swift
|
mit
|
1
|
//
// SWAnimatedTabBarItem.swift
// SWAnimatedTabBarController
//
// Created by Sarun Wongpatcharapakorn on 23/4/15.
// Copyright (c) 2015 Sarun Wongpatcharapakorn. All rights reserved.
//
import UIKit
@objc public protocol SWAnimatedTabBarItemDelegate {
func tabBarItem(item: SWAnimatedTabBarItem, didEnableBadge badgeEnabled: Bool)
func tabBarItem(item: SWAnimatedTabBarItem, didChangeTitle title: String?)
func tabBarItem(item: SWAnimatedTabBarItem, didChangeImage image: UIImage?)
func tabBarItem(item: SWAnimatedTabBarItem, didChangeImage image: UIImage?, title: String?)
}
public protocol SWAnimatedTabBarItemAnimation {
func playAnimation(iconView: IconView)
func selectedState(iconView: IconView)
}
public class SWItemAnimation: NSObject, SWAnimatedTabBarItemAnimation {
public func playAnimation(iconView: IconView) {
}
public func selectedState(iconView: IconView) {
}
}
// MARK: Animation
public enum SWAnimatedTabBarItemContextTransitioningImageKey {
case OldImage
case NewImage
}
public enum SWAnimatedTabBarItemContextTransitioningTitleKey {
case OldTitle
case NewTitle
}
/**
* Context used in animation
*/
public protocol SWAnimatedTabBarItemContextTransitioning {
func imageView() -> UIImageView
func textLabel() -> UILabel
func imageForKey(key: SWAnimatedTabBarItemContextTransitioningImageKey) -> UIImage?
func titleForKey(key: SWAnimatedTabBarItemContextTransitioningTitleKey) -> String?
/**
Notifies the system that the transition animation is done.
*/
func completeTransition()
}
protocol SWAnimatedTabBarItemAnimatedTransitioning {
func animatedTransition(transitionContext: SWAnimatedTabBarItemContextTransitioning)
}
protocol SWAnimatedTabBarItemTransitionDelegate: class {
func animationControllerForChangedTabBarItem(
tabBarItem: SWAnimatedTabBarItem) -> SWAnimatedTabBarItemAnimatedTransitioning?
}
public class SWAnimatedTabBarItem: UITabBarItem {
weak var delegate: SWAnimatedTabBarItemDelegate?
weak var transitionDelegate: SWAnimatedTabBarItemTransitionDelegate?
@IBOutlet public weak var animation: SWItemAnimation?
@IBInspectable public var badgeEnabled: Bool = false {
didSet {
self.delegate?.tabBarItem(self, didEnableBadge: badgeEnabled)
}
}
@IBInspectable public var sw_title: String? {
didSet {
self.delegate?.tabBarItem(self, didChangeTitle: sw_title)
}
}
@IBInspectable public var sw_image: UIImage? {
didSet {
self.delegate?.tabBarItem(self, didChangeImage: sw_image)
}
}
public func setAnimated(image: UIImage?, title: String?) {
let templateImage = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
// self.sw_title = title
// self.sw_image = templateImage
self.delegate?.tabBarItem(self, didChangeImage: templateImage, title: title)
// Prevent delegate to fire individually
let delegate = self.delegate
self.delegate = nil
self.sw_title = title
self.sw_image = templateImage
self.delegate = delegate
}
public func setAnimatedBadgeHidden(hidden: Bool) {
self.badgeEnabled = !hidden
}
public func setAnimatedTitle(title: String?) {
self.sw_title = title
}
public func setAnimatedImage(image: UIImage?) {
let templateImage = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
self.sw_image = templateImage
}
// TODO: wait until Apple fix this to use this
// override var badgeValue: String? {
// didSet {
// self.delegate?.tabBarItem(self, didSetBadgeValue: badgeValue)
// // HAX: swift bug causing recursive
// // It cleary indicate here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html
// // If you assign a value to a property within its own didSet observer, the new value that you assign will replace the one that was just set.
// //badgeValue = nil
// }
// }
}
public extension UIViewController {
public var sw_animatedTabBarItem: SWAnimatedTabBarItem? {
if let customItem = self.tabBarItem as? SWAnimatedTabBarItem {
return customItem
} else {
return nil
}
}
}
|
89b8e986c764649d86b63a42dcef0546
| 29.469799 | 155 | 0.695154 | false | false | false | false |
alessiobrozzi/firefox-ios
|
refs/heads/master
|
Sync/Synchronizers/Downloader.swift
|
mpl-2.0
|
2
|
/* 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 XCGLogger
import Deferred
private let log = Logger.syncLogger
class BatchingDownloader<T: CleartextPayloadJSON> {
let client: Sync15CollectionClient<T>
let collection: String
let prefs: Prefs
var batch: [Record<T>] = []
func store(_ records: [Record<T>]) {
self.batch += records
}
func retrieve() -> [Record<T>] {
let ret = self.batch
self.batch = []
return ret
}
var _advance: (() -> Void)?
func advance() {
guard let f = self._advance else {
return
}
self._advance = nil
f()
}
init(collectionClient: Sync15CollectionClient<T>, basePrefs: Prefs, collection: String) {
self.client = collectionClient
self.collection = collection
let branchName = "downloader." + collection + "."
self.prefs = basePrefs.branch(branchName)
log.info("Downloader configured with prefs '\(self.prefs.getBranchPrefix())'.")
}
static func resetDownloaderWithPrefs(_ basePrefs: Prefs, collection: String) {
// This leads to stupid paths like 'profile.sync.synchronizer.history..downloader.history..'.
// Sorry, but it's out in the world now...
let branchName = "downloader." + collection + "."
let prefs = basePrefs.branch(branchName)
let lm = prefs.timestampForKey("lastModified")
let bt = prefs.timestampForKey("baseTimestamp")
log.debug("Resetting downloader prefs \(prefs.getBranchPrefix()). Previous values: \(lm), \(bt).")
prefs.removeObjectForKey("nextOffset")
prefs.removeObjectForKey("offsetNewer")
prefs.removeObjectForKey("baseTimestamp")
prefs.removeObjectForKey("lastModified")
}
/**
* Clients should provide the same set of parameters alongside an `offset` as was
* provided with the initial request. The only thing that varies in our batch fetches
* is `newer`, so we track the original value alongside.
*/
var nextFetchParameters: (String, Timestamp)? {
get {
let o = self.prefs.stringForKey("nextOffset")
let n = self.prefs.timestampForKey("offsetNewer")
guard let offset = o, let newer = n else {
return nil
}
return (offset, newer)
}
set (value) {
if let (offset, newer) = value {
self.prefs.setString(offset, forKey: "nextOffset")
self.prefs.setTimestamp(newer, forKey: "offsetNewer")
} else {
self.prefs.removeObjectForKey("nextOffset")
self.prefs.removeObjectForKey("offsetNewer")
}
}
}
// Set after each batch, from record timestamps.
var baseTimestamp: Timestamp {
get {
return self.prefs.timestampForKey("baseTimestamp") ?? 0
}
set (value) {
self.prefs.setTimestamp(value, forKey: "baseTimestamp")
}
}
// Only set at the end of a batch, from headers.
var lastModified: Timestamp {
get {
return self.prefs.timestampForKey("lastModified") ?? 0
}
set (value) {
self.prefs.setTimestamp(value, forKey: "lastModified")
}
}
/**
* Call this when a significant structural server change has been detected.
*/
func reset() -> Success {
self.baseTimestamp = 0
self.lastModified = 0
self.nextFetchParameters = nil
self.batch = []
self._advance = nil
return succeed()
}
func go(_ info: InfoCollections, limit: Int) -> Deferred<Maybe<DownloadEndState>> {
guard let modified = info.modified(self.collection) else {
log.debug("No server modified time for collection \(self.collection).")
return deferMaybe(.noNewData)
}
log.debug("Modified: \(modified); last \(self.lastModified).")
if modified == self.lastModified {
log.debug("No more data to batch-download.")
return deferMaybe(.noNewData)
}
// If the caller hasn't advanced after the last batch, strange things will happen --
// potentially looping indefinitely. Warn.
if self._advance != nil && !self.batch.isEmpty {
log.warning("Downloading another batch without having advanced. This might be a bug.")
}
return self.downloadNextBatchWithLimit(limit, infoModified: modified)
}
func advanceTimestampTo(_ timestamp: Timestamp) {
log.debug("Advancing downloader lastModified from \(self.lastModified) to \(timestamp).")
self.lastModified = timestamp
}
// We're either fetching from our current base timestamp with no offset,
// or the timestamp we were using when we last saved an offset.
func fetchParameters() -> (String?, Timestamp) {
if let (offset, since) = self.nextFetchParameters {
return (offset, since)
}
return (nil, max(self.lastModified, self.baseTimestamp))
}
func downloadNextBatchWithLimit(_ limit: Int, infoModified: Timestamp) -> Deferred<Maybe<DownloadEndState>> {
let (offset, since) = self.fetchParameters()
log.debug("Fetching newer=\(since), offset=\(offset).")
let fetch = self.client.getSince(since, sort: SortOption.OldestFirst, limit: limit, offset: offset)
func handleFailure(_ err: MaybeErrorType) -> Deferred<Maybe<DownloadEndState>> {
log.debug("Handling failure.")
guard let badRequest = err as? BadRequestError<[Record<T>]>, badRequest.response.metadata.status == 412 else {
// Just pass through the failure.
return deferMaybe(err)
}
// Conflict. Start again.
log.warning("Server contents changed during offset-based batching. Stepping back.")
self.nextFetchParameters = nil
return deferMaybe(.interrupted)
}
func handleSuccess(_ response: StorageResponse<[Record<T>]>) -> Deferred<Maybe<DownloadEndState>> {
log.debug("Handling success.")
let nextOffset = response.metadata.nextOffset
let responseModified = response.value.last?.modified
// Queue up our metadata advance. We wait until the consumer has fetched
// and processed this batch; they'll call .advance() on success.
self._advance = {
// Shift to the next offset. This might be nil, in which case… fine!
// Note that we preserve the previous 'newer' value from the offset or the original fetch,
// even as we update baseTimestamp.
self.nextFetchParameters = nextOffset == nil ? nil : (nextOffset!, since)
// If there are records, advance to just before the timestamp of the last.
// If our next fetch with X-Weave-Next-Offset fails, at least we'll start here.
//
// This approach is only valid if we're fetching oldest-first.
if let newBase = responseModified {
log.debug("Advancing baseTimestamp to \(newBase) - 1")
self.baseTimestamp = newBase - 1
}
if nextOffset == nil {
// If we can't get a timestamp from the header -- and we should always be able to --
// we fall back on the collection modified time in i/c, as supplied by the caller.
// In any case where there is no racing writer these two values should be the same.
// If they differ, the header should be later. If it's missing, and we use the i/c
// value, we'll simply redownload some records.
// All bets are off if we hit this case and are filtering somehow… don't do that.
let lm = response.metadata.lastModifiedMilliseconds
log.debug("Advancing lastModified to \(lm) ?? \(infoModified).")
self.lastModified = lm ?? infoModified
}
}
log.debug("Got success response with \(response.metadata.records ?? 0) records.")
// Store the incoming records for collection.
self.store(response.value)
return deferMaybe(nextOffset == nil ? .complete : .incomplete)
}
return fetch.bind { result in
guard let response = result.successValue else {
return handleFailure(result.failureValue!)
}
return handleSuccess(response)
}
}
}
public enum DownloadEndState: String {
case complete // We're done. Records are waiting for you.
case incomplete // applyBatch was called, and we think there are more records.
case noNewData // There were no records.
case interrupted // We got a 412 conflict when fetching the next batch.
}
|
3755c633aadc1387dbd1b189c877efc4
| 39.367965 | 122 | 0.600536 | false | false | false | false |
SuperAwesomeLTD/sa-kws-app-demo-ios
|
refs/heads/master
|
KWSDemo/CountryRowViewModel.swift
|
gpl-3.0
|
1
|
//
// TableRowViewModel.swift
// KWSDemo
//
// Created by Gabriel Coman on 09/12/2016.
// Copyright © 2016 Gabriel Coman. All rights reserved.
//
import UIKit
class CountryRowViewModel: NSObject, ViewModel {
private var countryISOCode: String?
private var countryName: String?
private var countryFlag: UIImage?
init(isoCode: String) {
super.init ()
self.countryISOCode = isoCode
self.countryName = Locale.current.localizedString(forRegionCode: self.countryISOCode!)
let flag = UIImage (named: "\(self.countryISOCode!.lowercased()).png")
if let flag = flag {
self.countryFlag = flag
}
}
func getISOCode () -> String {
if let code = countryISOCode {
return code.uppercased()
} else {
return "page_country_row_default_country_iso".localized
}
}
func getCountryName () -> String {
if let name = countryName {
return name.capitalized
} else {
return "page_country_row_default_country_name".localized
}
}
func getFlag () -> UIImage {
if let flag = countryFlag {
return flag
} else {
return UIImage (named: ("page_country_row_default_country_flag".localized + ".png"))!
}
}
}
|
8d6d1e8a50913f5f0ea36b15d2b109b4
| 24.481481 | 97 | 0.573401 | false | false | false | false |
andersio/ReactiveCocoa
|
refs/heads/master
|
ReactiveCocoa.playground/Pages/SignalProducer.xcplaygroundpage/Contents.swift
|
mit
|
1
|
/*:
> # IMPORTANT: To use `ReactiveCocoa.playground`, please:
1. Retrieve the project dependencies using one of the following terminal commands from the ReactiveCocoa project root directory:
- `script/bootstrap`
**OR**, if you have [Carthage](https://github.com/Carthage/Carthage) installed
- `carthage checkout`
1. Open `ReactiveCocoa.xcworkspace`
1. Build `Result-Mac` scheme
1. Build `ReactiveCocoa-Mac` scheme
1. Finally open the `ReactiveCocoa.playground`
1. Choose `View > Show Debug Area`
*/
import Result
import ReactiveCocoa
import Foundation
/*:
## SignalProducer
A **signal producer**, represented by the [`SignalProducer`](https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/ReactiveCocoa/Swift/SignalProducer.swift) type, creates
[signals](https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/ReactiveCocoa/Swift/Signal.swift) and performs side effects.
They can be used to represent operations or tasks, like network
requests, where each invocation of `start()` will create a new underlying
operation, and allow the caller to observe the result(s). The
`startWithSignal()` variant gives access to the produced signal, allowing it to
be observed multiple times if desired.
Because of the behavior of `start()`, each signal created from the same
producer may see a different ordering or version of events, or the stream might
even be completely different! Unlike a plain signal, no work is started (and
thus no events are generated) until an observer is attached, and the work is
restarted anew for each additional observer.
Starting a signal producer returns a [disposable](#disposables) that can be used to
interrupt/cancel the work associated with the produced signal.
Just like signals, signal producers can also be manipulated via primitives
like `map`, `filter`, etc.
Every signal primitive can be “lifted” to operate upon signal producers instead,
using the `lift` method.
Furthermore, there are additional primitives that control _when_ and _how_ work
is started—for example, `times`.
*/
/*:
### `Subscription`
A SignalProducer represents an operation that can be started on demand. Starting the operation returns a Signal on which the result(s) of the operation can be observed. This behavior is sometimes also called "cold".
This means that a subscriber will never miss any values sent by the SignalProducer.
*/
scopedExample("Subscription") {
let producer = SignalProducer<Int, NoError> { observer, _ in
print("New subscription, starting operation")
observer.sendNext(1)
observer.sendNext(2)
}
let subscriber1 = Observer<Int, NoError>(next: { print("Subscriber 1 received \($0)") })
let subscriber2 = Observer<Int, NoError>(next: { print("Subscriber 2 received \($0)") })
print("Subscriber 1 subscribes to producer")
producer.start(subscriber1)
print("Subscriber 2 subscribes to producer")
// Notice, how the producer will start the work again
producer.start(subscriber2)
}
/*:
### `empty`
A producer for a Signal that will immediately complete without sending
any values.
*/
scopedExample("`empty`") {
let emptyProducer = SignalProducer<Int, NoError>.empty
let observer = Observer<Int, NoError>(
failed: { _ in print("error not called") },
completed: { print("completed called") },
next: { _ in print("next not called") }
)
emptyProducer.start(observer)
}
/*:
### `never`
A producer for a Signal that never sends any events to its observers.
*/
scopedExample("`never`") {
let neverProducer = SignalProducer<Int, NoError>.never
let observer = Observer<Int, NoError>(
failed: { _ in print("error not called") },
completed: { print("completed not called") },
next: { _ in print("next not called") }
)
neverProducer.start(observer)
}
/*:
### `buffer`
Creates a queue for events that replays them when new signals are
created from the returned producer.
When values are put into the returned observer (observer), they will be
added to an internal buffer. If the buffer is already at capacity,
the earliest (oldest) value will be dropped to make room for the new
value.
Signals created from the returned producer will stay alive until a
terminating event is added to the queue. If the queue does not contain
such an event when the Signal is started, all values sent to the
returned observer will be automatically forwarded to the Signal’s
observers until a terminating event is received.
After a terminating event has been added to the queue, the observer
will not add any further events. This _does not_ count against the
value capacity so no buffered values will be dropped on termination.
*/
scopedExample("`buffer`") {
let (producer, observer) = SignalProducer<Int, NoError>.buffer(1)
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
var values: [Int] = []
producer.start { event in
switch event {
case let .Next(value):
values.append(value)
default:
break
}
}
print(values)
observer.sendNext(4)
print(values)
}
/*:
### `startWithSignal`
Creates a Signal from the producer, passes it into the given closure,
then starts sending events on the Signal when the closure has returned.
The closure will also receive a disposable which can be used to
interrupt the work associated with the signal and immediately send an
`Interrupted` event.
*/
scopedExample("`startWithSignal`") {
var started = false
var value: Int?
SignalProducer<Int, NoError>(value: 42)
.on(next: {
value = $0
})
.startWithSignal { signal, disposable in
print(value)
}
print(value)
}
/*:
### `startWithNext`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when `next` events are
received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal, and prevent any future callbacks from being invoked.
*/
scopedExample("`startWithNext`") {
SignalProducer<Int, NoError>(value: 42)
.startWithNext { value in
print(value)
}
}
/*:
### `startWithCompleted`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when a `completed` event is
received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal.
*/
scopedExample("`startWithCompleted`") {
SignalProducer<Int, NoError>(value: 42)
.startWithCompleted {
print("completed called")
}
}
/*:
### `startWithFailed`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when a `failed` event is
received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal.
*/
scopedExample("`startWithFailed`") {
SignalProducer<Int, NSError>(error: NSError(domain: "example", code: 42, userInfo: nil))
.startWithFailed { error in
print(error)
}
}
/*:
### `startWithInterrupted`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when an `interrupted` event
is received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal.
*/
scopedExample("`startWithInterrupted`") {
let disposable = SignalProducer<Int, NoError>.never
.startWithInterrupted {
print("interrupted called")
}
disposable.dispose()
}
/*:
### `lift`
Lifts an unary Signal operator to operate upon SignalProducers instead.
In other words, this will create a new SignalProducer which will apply
the given Signal operator to _every_ created Signal, just as if the
operator had been applied to each Signal yielded from start().
*/
scopedExample("`lift`") {
var counter = 0
let transform: Signal<Int, NoError> -> Signal<Int, NoError> = { signal in
counter = 42
return signal
}
SignalProducer<Int, NoError>(value: 0)
.lift(transform)
.startWithNext { _ in
print(counter)
}
}
/*:
### `map`
Maps each value in the producer to a new value.
*/
scopedExample("`map`") {
SignalProducer<Int, NoError>(value: 1)
.map { $0 + 41 }
.startWithNext { value in
print(value)
}
}
/*:
### `mapError`
Maps errors in the producer to a new error.
*/
scopedExample("`mapError`") {
SignalProducer<Int, NSError>(error: NSError(domain: "mapError", code: 42, userInfo: nil))
.mapError { Error.Example($0.description) }
.startWithFailed { error in
print(error)
}
}
/*:
### `filter`
Preserves only the values of the producer that pass the given predicate.
*/
scopedExample("`filter`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.filter { $0 > 3}
.startWithNext { value in
print(value)
}
}
/*:
### `take`
Returns a producer that will yield the first `count` values from the
input producer.
*/
scopedExample("`take`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.take(2)
.startWithNext { value in
print(value)
}
}
/*:
### `observeOn`
Forwards all events onto the given scheduler, instead of whichever
scheduler they originally arrived upon.
*/
scopedExample("`observeOn`") {
let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
let completion = { print("is main thread? \(NSThread.currentThread().isMainThread)") }
if #available(OSX 10.10, *) {
baseProducer
.observeOn(QueueScheduler(qos: QOS_CLASS_DEFAULT, name: "test"))
.startWithCompleted(completion)
}
baseProducer
.startWithCompleted(completion)
}
/*:
### `collect()`
Returns a producer that will yield an array of values until it completes.
*/
scopedExample("`collect()`") {
SignalProducer<Int, NoError> { observer, disposable in
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
observer.sendCompleted()
}
.collect()
.startWithNext { value in
print(value)
}
}
/*:
### `collect(count:)`
Returns a producer that will yield an array of values until it reaches a certain count.
*/
scopedExample("`collect(count:)`") {
SignalProducer<Int, NoError> { observer, disposable in
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
observer.sendCompleted()
}
.collect(count: 2)
.startWithNext { value in
print(value)
}
}
/*:
### `collect(predicate:)` matching values inclusively
Returns a producer that will yield an array of values based on a predicate
which matches the values collected.
When producer completes any remaining values will be sent, the last values
array may not match `predicate`. Alternatively, if were not collected any
values will sent an empty array of values.
*/
scopedExample("`collect(predicate:)` matching values inclusively") {
SignalProducer<Int, NoError> { observer, disposable in
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
observer.sendCompleted()
}
.collect { values in values.reduce(0, combine: +) == 3 }
.startWithNext { value in
print(value)
}
}
/*:
### `collect(predicate:)` matching values exclusively
Returns a producer that will yield an array of values based on a predicate
which matches the values collected and the next value.
When producer completes any remaining values will be sent, the last values
array may not match `predicate`. Alternatively, if were not collected any
values will sent an empty array of values.
*/
scopedExample("`collect(predicate:)` matching values exclusively") {
SignalProducer<Int, NoError> { observer, disposable in
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
observer.sendCompleted()
}
.collect { values, next in next == 3 }
.startWithNext { value in
print(value)
}
}
/*:
### `combineLatestWith`
Combines the latest value of the receiver with the latest value from
the given producer.
The returned producer will not send a value until both inputs have sent at
least one value each. If either producer is interrupted, the returned producer
will also be interrupted.
*/
scopedExample("`combineLatestWith`") {
let producer1 = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
let producer2 = SignalProducer<Int, NoError>(values: [ 1, 2 ])
producer1
.combineLatestWith(producer2)
.startWithNext { value in
print("\(value)")
}
}
/*:
### `skip`
Returns a producer that will skip the first `count` values, then forward
everything afterward.
*/
scopedExample("`skip`") {
let producer1 = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
producer1
.skip(2)
.startWithNext { value in
print(value)
}
}
/*:
### `materialize`
Treats all Events from the input producer as plain values, allowing them to be
manipulated just like any other value.
In other words, this brings Events “into the monad.”
When a Completed or Failed event is received, the resulting producer will send
the Event itself and then complete. When an Interrupted event is received,
the resulting producer will send the Event itself and then interrupt.
*/
scopedExample("`materialize`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.materialize()
.startWithNext { value in
print(value)
}
}
/*:
### `sampleOn`
Forwards the latest value from `self` whenever `sampler` sends a Next
event.
If `sampler` fires before a value has been observed on `self`, nothing
happens.
Returns a producer that will send values from `self`, sampled (possibly
multiple times) by `sampler`, then complete once both input producers have
completed, or interrupt if either input producer is interrupted.
*/
scopedExample("`sampleOn`") {
let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
let sampledOnProducer = SignalProducer<Int, NoError>(values: [ 1, 2 ])
.map { _ in () }
baseProducer
.sampleOn(sampledOnProducer)
.startWithNext { value in
print(value)
}
}
/*:
### `combinePrevious`
Forwards events from `self` with history: values of the returned producer
are a tuple whose first member is the previous value and whose second member
is the current value. `initial` is supplied as the first member when `self`
sends its first value.
*/
scopedExample("`combinePrevious`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.combinePrevious(42)
.startWithNext { value in
print("\(value)")
}
}
/*:
### `scan`
Aggregates `self`'s values into a single combined value. When `self` emits
its first value, `combine` is invoked with `initial` as the first argument and
that emitted value as the second argument. The result is emitted from the
producer returned from `scan`. That result is then passed to `combine` as the
first argument when the next value is emitted, and so on.
*/
scopedExample("`scan`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.scan(0, +)
.startWithNext { value in
print(value)
}
}
/*:
### `reduce`
Like `scan`, but sends only the final value and then immediately completes.
*/
scopedExample("`reduce`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.reduce(0, +)
.startWithNext { value in
print(value)
}
}
/*:
### `skipRepeats`
Forwards only those values from `self` which do not pass `isRepeat` with
respect to the previous value. The first value is always forwarded.
*/
scopedExample("`skipRepeats`") {
SignalProducer<Int, NoError>(values: [ 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4 ])
.skipRepeats(==)
.startWithNext { value in
print(value)
}
}
/*:
### `skipWhile`
Does not forward any values from `self` until `predicate` returns false,
at which point the returned signal behaves exactly like `self`.
*/
scopedExample("`skipWhile`") {
SignalProducer<Int, NoError>(values: [ 3, 3, 3, 3, 1, 2, 3, 4 ])
.skipWhile { $0 > 2 }
.startWithNext { value in
print(value)
}
}
/*:
### `takeUntilReplacement`
Forwards events from `self` until `replacement` begins sending events.
Returns a producer which passes through `Next`, `Failed`, and `Interrupted`
events from `self` until `replacement` sends an event, at which point the
returned producer will send that event and switch to passing through events
from `replacement` instead, regardless of whether `self` has sent events
already.
*/
scopedExample("`takeUntilReplacement`") {
let (replacementSignal, incomingReplacementObserver) = Signal<Int, NoError>.pipe()
let baseProducer = SignalProducer<Int, NoError> { incomingObserver, _ in
incomingObserver.sendNext(1)
incomingObserver.sendNext(2)
incomingObserver.sendNext(3)
incomingReplacementObserver.sendNext(42)
incomingObserver.sendNext(4)
incomingReplacementObserver.sendNext(42)
}
let producer = baseProducer.takeUntilReplacement(replacementSignal)
producer.startWithNext { value in
print(value)
}
}
/*:
### `takeLast`
Waits until `self` completes and then forwards the final `count` values
on the returned producer.
*/
scopedExample("`takeLast`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.takeLast(2)
.startWithNext { value in
print(value)
}
}
/*:
### `ignoreNil`
Unwraps non-`nil` values and forwards them on the returned signal, `nil`
values are dropped.
*/
scopedExample("`ignoreNil`") {
SignalProducer<Int?, NoError>(values: [ nil, 1, 2, nil, 3, 4, nil ])
.ignoreNil()
.startWithNext { value in
print(value)
}
}
/*:
### `zipWith`
Zips elements of two producers into pairs. The elements of any Nth pair
are the Nth elements of the two input producers.
*/
scopedExample("`zipWith`") {
let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
let zippedProducer = SignalProducer<Int, NoError>(values: [ 42, 43 ])
baseProducer
.zipWith(zippedProducer)
.startWithNext { value in
print("\(value)")
}
}
/*:
### `times`
Repeats `self` a total of `count` times. Repeating `1` times results in
an equivalent signal producer.
*/
scopedExample("`times`") {
var counter = 0
SignalProducer<(), NoError> { observer, disposable in
counter += 1
observer.sendCompleted()
}
.times(42)
.start()
print(counter)
}
/*:
### `retry`
Ignores failures up to `count` times.
*/
scopedExample("`retry`") {
var tries = 0
SignalProducer<Int, NSError> { observer, disposable in
if tries == 0 {
tries += 1
observer.sendFailed(NSError(domain: "retry", code: 0, userInfo: nil))
} else {
observer.sendNext(42)
observer.sendCompleted()
}
}
.retry(1)
.startWithNext { value in
print(value)
}
}
/*:
### `then`
Waits for completion of `producer`, *then* forwards all events from
`replacement`. Any failure sent from `producer` is forwarded immediately, in
which case `replacement` will not be started, and none of its events will be
be forwarded. All values sent from `producer` are ignored.
*/
scopedExample("`then`") {
let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
let thenProducer = SignalProducer<Int, NoError>(value: 42)
baseProducer
.then(thenProducer)
.startWithNext { value in
print(value)
}
}
/*:
### `replayLazily`
Creates a new `SignalProducer` that will multicast values emitted by
the underlying producer, up to `capacity`.
This means that all clients of this `SignalProducer` will see the same version
of the emitted values/errors.
The underlying `SignalProducer` will not be started until `self` is started
for the first time. When subscribing to this producer, all previous values
(up to `capacity`) will be emitted, followed by any new values.
If you find yourself needing *the current value* (the last buffered value)
you should consider using `PropertyType` instead, which, unlike this operator,
will guarantee at compile time that there's always a buffered value.
This operator is not recommended in most cases, as it will introduce an implicit
relationship between the original client and the rest, so consider alternatives
like `PropertyType`, `SignalProducer.buffer`, or representing your stream using
a `Signal` instead.
This operator is only recommended when you absolutely need to introduce
a layer of caching in front of another `SignalProducer`.
This operator has the same semantics as `SignalProducer.buffer`.
*/
scopedExample("`replayLazily`") {
let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4, 42 ])
.replayLazily(2)
baseProducer.startWithNext { value in
print(value)
}
baseProducer.startWithNext { value in
print(value)
}
baseProducer.startWithNext { value in
print(value)
}
}
/*:
### `flatMap(.Latest)`
Maps each event from `self` to a new producer, then flattens the
resulting producers (into a producer of values), according to the
semantics of the given strategy.
If `self` or any of the created producers fail, the returned producer
will forward that failure immediately.
*/
scopedExample("`flatMap(.Latest)`") {
SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
.flatMap(.Latest) { SignalProducer(value: $0 + 3) }
.startWithNext { value in
print(value)
}
}
/*:
### `flatMapError`
Catches any failure that may occur on the input producer, mapping to a new producer
that starts in its place.
*/
scopedExample("`flatMapError`") {
SignalProducer<Int, NSError>(error: NSError(domain: "flatMapError", code: 42, userInfo: nil))
.flatMapError { SignalProducer<Int, NSError>(value: $0.code) }
.startWithNext { value in
print(value)
}
}
/*:
### `sampleWith`
Forwards the latest value from `self` with the value from `sampler` as a tuple,
only when `sampler` sends a Next event.
If `sampler` fires before a value has been observed on `self`, nothing happens.
Returns a producer that will send values from `self` and `sampler`,
sampled (possibly multiple times) by `sampler`, then complete once both
input producers have completed, or interrupt if either input producer is interrupted.
*/
scopedExample("`sampleWith`") {
let producer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ])
let sampler = SignalProducer<String, NoError>(values: [ "a", "b" ])
let result = producer.sampleWith(sampler)
result.startWithNext { left, right in
print("\(left) \(right)")
}
}
/*:
### `logEvents`
Logs all events that the receiver sends.
By default, it will print to the standard output.
*/
scopedExample("`log events`") {
let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4, 42 ])
baseProducer
.logEvents(identifier: "Playground is fun!")
.start()
}
|
02a9703f8c4f72bad4fd8ed25292586a
| 29.452261 | 217 | 0.664851 | false | false | false | false |
kfinn/puppies
|
refs/heads/master
|
Puppies/GifView.swift
|
mit
|
1
|
//
// GifView.swift
// Puppies
//
// Created by Kevin Finn on 11/16/14.
// Copyright (c) 2014 Heptarex. All rights reserved.
//
import UIKit
let animatedImageCache = NSCache()
class GifView: UIView {
var gif : Gif? {
didSet {
self.gifView.animatedImage = nil;
self.gifView.image = UIImage(named: "puppy.jpg");
if let requestGif = gif? {
if let cached = animatedImageCache.objectForKey(gif!) as? FLAnimatedImage {
self.gifView.animatedImage = cached
} else {
fetchImage();
}
}
setNeedsLayout()
}
}
private func fetchImage() {
if let requestGif = gif {
NSURLSession.sharedSession().dataTaskWithURL(requestGif.url) {
(data, response, error) in
if let animatedImage = FLAnimatedImage(animatedGIFData: data) {
animatedImageCache.setObject(animatedImage, forKey: requestGif)
if requestGif == self.gif {
self.gifView.animatedImage = animatedImage
}
} else {
NSLog("request failed: \(error.localizedDescription)")
}
}.resume()
}
}
var hasConstraints = false
override func updateConstraints() {
if !hasConstraints {
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-0-[gif]-0-|", options: .allZeros, metrics: nil, views: ["gif":gifView]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[gif]-0-|", options: .allZeros, metrics: nil, views: ["gif":gifView]))
}
super.updateConstraints()
}
let gifView: FLAnimatedImageView = {
let imageView = FLAnimatedImageView()
imageView.contentMode = .ScaleAspectFit
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
return imageView
}()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
gifView.frame = bounds;
addSubview(gifView)
// setTranslatesAutoresizingMaskIntoConstraints(false)
setNeedsUpdateConstraints()
}
override init(frame: CGRect) {
super.init(frame: frame)
gifView.frame = bounds;
addSubview(gifView)
// setTranslatesAutoresizingMaskIntoConstraints(false)
setNeedsUpdateConstraints()
}
}
|
5c2838f2403d244381df02fdb9bce30d
| 30.987342 | 151 | 0.578947 | false | false | false | false |
dcutting/song
|
refs/heads/master
|
Tests/SongTests/Parser/AssignParserTests.swift
|
mit
|
1
|
import XCTest
import Song
class AssignParserTests: XCTestCase {
func test_shouldParse() {
"x = 5".makes(.assign(variable: .name("x"), value: .int(5)))
"x=5".makes(.assign(variable: .name("x"), value: .int(5)))
"_ = 5".makes(.assign(variable: .ignore, value: .int(5)))
"double = |x| x * 2".makes(.assign(variable: .name("double"), value:
.function(Function(name: nil,
patterns: [.name("x")],
when: .yes,
body: .call("*", [.name("x"), .int(2)])))))
}
func test_shouldNotParse() {
"2 = 5".fails()
}
}
|
2d1fefb0a80ea511535e0f1093d261cc
| 32.1 | 76 | 0.468278 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.