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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LinkRober/RBRefresh
|
refs/heads/master
|
RBRefresh/TestViewController.swift
|
mit
|
1
|
//
// TestViewController.swift
// RBRefresh
//
// Created by 夏敏 on 20/01/2017.
// Copyright © 2017 夏敏. All rights reserved.
//
import UIKit
class TestViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
lazy var tableview:UITableView = {
let tableview = UITableView.init(frame: CGRect(x:0,y:0,width:self.view.frame.size.width,height:self.view.frame.size.height - 64), style: .plain)
return tableview
}()
var type:Type = .Normal
var datasource = [1,2,3,4,5]
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = []
self.tableview.delegate = self
self.tableview.dataSource = self
self.tableview.tableFooterView = UIView()
view.addSubview(self.tableview)
if type == .Normal {
self.tableview.rb_addHeaderRefreshBlock({
DispatchQueue.main.asyncAfter(deadline:.now() + 1) {
self.datasource.removeAll()
self.tableview.reloadData()
for _ in 0 ..< 10 {
self.datasource.append(self.randNumber())
}
self.tableview.rb_resetNoMoreData()
self.tableview.rb_endHeaderRefresh()
self.tableview.reloadData()
}
}, animator:RBNormalHeader.init(frame: CGRect(x:0,y:0,width:0,height:50)))
}else if type == .Gif{
self.tableview.rb_addHeaderRefreshBlock({
DispatchQueue.main.asyncAfter(deadline:.now() + 1) {
self.datasource.removeAll()
self.tableview.reloadData()
for _ in 0 ..< 10 {
self.datasource.append(self.randNumber())
}
self.tableview.rb_resetNoMoreData()
self.tableview.rb_endHeaderRefresh()
self.tableview.reloadData()
}
}, animator:RBGifHeader.init(frame: CGRect(x:0,y:0,width:0,height:80)))
} else if type == .BallRoateChase {
self.tableview.rb_addHeaderRefreshBlock({
DispatchQueue.main.asyncAfter(deadline:.now() + 1) {
self.datasource.removeAll()
self.tableview.reloadData()
for _ in 0 ..< 10 {
self.datasource.append(self.randNumber())
}
self.tableview.rb_resetNoMoreData()
self.tableview.rb_endHeaderRefresh()
self.tableview.reloadData()
}
}, animator:RBBallRoateChaseHeader.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:50)))
} else if type == .BallClipRotate {
self.tableview.rb_addHeaderRefreshBlock({
DispatchQueue.main.asyncAfter(deadline:.now() + 1) {
self.datasource.removeAll()
self.tableview.reloadData()
for _ in 0 ..< 10 {
self.datasource.append(self.randNumber())
}
self.tableview.rb_resetNoMoreData()
self.tableview.rb_endHeaderRefresh()
self.tableview.reloadData()
}
}, animator:RBBallClipRoateHeader.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:50)))
}else if type == .BallScale {
self.tableview.rb_addHeaderRefreshBlock({
DispatchQueue.main.asyncAfter(deadline:.now() + 1) {
self.datasource.removeAll()
self.tableview.reloadData()
for _ in 0 ..< 10 {
self.datasource.append(self.randNumber())
}
self.tableview.rb_resetNoMoreData()
self.tableview.rb_endHeaderRefresh()
self.tableview.reloadData()
}
}, animator:RBBallScaleHeader.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:50)))
}
self.tableview.rb_addFooterRefreshBlock({
OperationQueue().addOperation {
sleep(1)
OperationQueue.main.addOperation {
self.tableview.rb_endFooterRefresh()
self.datasource.append(contentsOf: [24,25].map({ (n:Int) -> Int in
return self.randNumber()
}))
self.tableview.reloadData()
}
}
}, animator: RBNormalFooter.init(frame: CGRect(x:0,y:0,width:0,height:50)))
self.tableview.rb_beginHeaderRefresh()
}
func randNumber() -> Int {
return Int(arc4random_uniform(100))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell.init(style: .default, reuseIdentifier: "")
cell.textLabel?.text = "\(datasource[indexPath.row])"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
|
d98e5a8457fec9ce3b900a7a52638f99
| 37.317568 | 152 | 0.536766 | false | false | false | false |
frograin/FluidValidator
|
refs/heads/master
|
Pod/Classes/Core/LocalizationHelper.swift
|
mit
|
1
|
//
// LocalizationHelper.swift
// TestValidator
//
// Created by FrogRain on 31/01/16.
// Copyright © 2016 FrogRain. All rights reserved.
//
import Foundation
class LocalizationHelper {
class func localizeThis(_ key:String) -> String {
let mainBundle = Bundle.main
var localizedString = NSLocalizedString(key, tableName: "object_validator_custom", bundle: mainBundle, comment:"")
if(localizedString != key) {
return localizedString
}
guard let frameworkPath = Bundle(for: LocalizationHelper.self).resourcePath else {
return key
}
guard let path = URL(string: frameworkPath)?.appendingPathComponent("FluidValidator.bundle").path else {
return key
}
guard let bundle = Bundle(path: path) else {
return key
}
localizedString = NSLocalizedString(key, tableName: "object_validator", bundle: bundle, comment:"")
if(localizedString != key) {
return localizedString
}
return key
}
}
|
c68758a07bf24719f0461860f5ee5484
| 28.648649 | 122 | 0.608933 | false | false | false | false |
nicemohawk/nmf-ios
|
refs/heads/master
|
nmf/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// nmf
//
// Created by Daniel Pagan on 3/16/16.
// Copyright © 2017 Nelsonville Music Festival. All rights reserved.
//
import UIKit
import TwitterKit
import BBBadgeBarButtonItem
import Pushwoosh
import Reachability
import Kingfisher
import SwiftSDK
//#if CONFIGURATION_Debug
//import SimulatorStatusMagic
//#endif
let scheduleUpdateInterval: TimeInterval = 1*60 // seconds
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, PushNotificationDelegate {
let APP_ID = Secrets.secrets()["APP_ID"] as! String
let SECRET_KEY = Secrets.secrets()["SECRET_KEY"] as! String
let SERVER_URL = "https://api.backendless.com"
// let VERSION_NUM = "v1"
let backendless = Backendless.shared
var window: UIWindow?
var lastScheduleFetched = Date.distantPast
let reachability = try! Reachability()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch
backendless.hostUrl = SERVER_URL
backendless.initApp(applicationId: APP_ID, apiKey: SECRET_KEY)
backendless.data.of(Artist.self).mapToTable(tableName: "Artists")
backendless.data.of(ScheduleItem.self).mapToTable(tableName: "Schedule")
// setup image cache
ImageCache.default.diskStorage.config.expiration = StorageExpiration.days(30)
// DataStore.sharedInstance.updateScheduleItems { _ in
// return
// }
DataStore.sharedInstance.updateArtistItems { error in
guard error == nil else {
return
}
DataStore.sharedInstance.removeOutOfDateArtists()
if self.reachability.connection == .wifi {
ImagePrefetcher.init(resources: DataStore.sharedInstance.artistItems, options: nil, progressBlock: nil, completionHandler: nil).start()
}
}
// setup twitter kit
Twitter.sharedInstance().start(withConsumerKey: Secrets.secrets()["TWITTERKIT_KEY"] as! String, consumerSecret: Secrets.secrets()["TWITTERKIT_SECRET"] as! String)
// setup push notes
#if CONFIGURATION_Release
PushNotificationManager.initialize(withAppCode: (Secrets.secrets()["PW_APP_CODE"] as! String), appName: "NMF")
#endif
#if CONFIGURATION_Debug
PushNotificationManager.initialize(withAppCode: (Secrets.secrets()["PW_DEV_APP_CODE"] as! String), appName: "NMF-dev")
#endif
PushNotificationManager.push().delegate = self
PushNotificationManager.push().showPushnotificationAlert = true
PushNotificationManager.push().handlePushReceived(launchOptions)
PushNotificationManager.push().sendAppOpen()
PushNotificationManager.push().registerForPushNotifications()
UINavigationBar.appearance().barStyle = .blackOpaque
// #if CONFIGURATION_Debug
// // for nice screen shots only
// SDStatusBarManager.sharedInstance().enableOverrides()
// #endif
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.
DataStore.sharedInstance.saveData()
}
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.
if DataStore.sharedInstance.scheduleItems.first?.day != nil,
lastScheduleFetched > Date(timeIntervalSinceNow: -scheduleUpdateInterval) {
// if app hasn't been used within the last scheduleUpdateInterval seconds, update it, otherwise return
return
}
DataStore.sharedInstance.updateScheduleItems() { error in
guard let tabController = self.window?.rootViewController as? UITabBarController,
let navController = tabController.selectedViewController as? UINavigationController,
let scheduleViewController = navController.visibleViewController as? ScheduleTableViewController else {
return
}
if error == nil {
DataStore.sharedInstance.removeOutOfDateScheduleItems()
scheduleViewController.sortScheduleItems(starredOnly: scheduleViewController.showingStarredOnly)
scheduleViewController.tableView.reloadData()
self.lastScheduleFetched = Date()
}
scheduleViewController.scrollToNearestCell()
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
DataStore.sharedInstance.saveData()
}
// MARK: - Push notifications
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
PushNotificationManager.push().handlePushRegistration(deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
PushNotificationManager.push().handlePushRegistrationFailure(error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
PushNotificationManager.push().handlePushReceived(userInfo)
guard let tabController = window?.rootViewController as? UITabBarController,
let navController = tabController.viewControllers?.compactMap({ $0 as? UINavigationController }).filter({ $0.viewControllers.first is ScheduleTableViewController}).first,
let scheduleController = navController.viewControllers.first as? ScheduleTableViewController else {
return
}
if let button = scheduleController.navigationItem.leftBarButtonItem as? BBBadgeBarButtonItem {
button.badgeValue = "!"
}
}
func onPushAccepted(_ pushManager: PushNotificationManager!, withNotification pushNotification: [AnyHashable: Any]!, onStart: Bool) {
print("Push notification accepted: \(String(describing: pushNotification))");
guard let tabController = window?.rootViewController as? UITabBarController,
let navController = tabController.viewControllers?.compactMap({ $0 as? UINavigationController }).filter({ $0.viewControllers.first is ScheduleTableViewController}).first,
let scheduleController = navController.viewControllers.first as? ScheduleTableViewController else {
return
}
tabController.selectedViewController = navController
navController.popToRootViewController(animated: true)
scheduleController.notificationsAction(self)
}
}
|
68c301fe8367b1307d53e3ea7b25060c
| 43.939891 | 285 | 0.698322 | false | false | false | false |
daxrahusen/Eindproject
|
refs/heads/master
|
Social Wall/CommentController.swift
|
apache-2.0
|
1
|
//
// CommentControllerViewController.swift
// Social Wall
//
// Created by Dax Rahusen on 17/01/2017.
// Copyright © 2017 Dax. All rights reserved.
//
import UIKit
import Firebase
class CommentController: UIViewController {
// define optional message objects
var message: Message?
// construct a UITextView as a computed property
let textView: UITextView = {
let tx = UITextView()
tx.isScrollEnabled = false
tx.isEditable = false
tx.text = "Please fill in a comment..."
tx.textColor = .lightGray
tx.font = UIFont.boldSystemFont(ofSize: 16)
return tx
}()
// construct a UITextView as a computed property
lazy var composeTextView: UITextView = {
let tf = UITextView()
tf.isScrollEnabled = false
tf.layer.borderWidth = 1
tf.layer.borderColor = UIColor.lightGray.cgColor
tf.layer.cornerRadius = 8
tf.delegate = self
return tf
}()
// construct a UILabel as a computed property
let composeCountLabel: UILabel = {
let label = UILabel()
label.text = "140"
label.textColor = .black
label.textAlignment = .right
return label
}()
// construct a ProgressHUD as a computed property
let progresHUB: ProgressHUD = {
let hub = ProgressHUD(text: "Saving comment")
hub.hide()
return hub
}()
var controller = UIAlertController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// set the value indicates whether the view controller
// should automatically adjust its scroll view insets.
automaticallyAdjustsScrollViewInsets = false
setupViews()
}
// define optional DetailWallControllerDelegate
weak var delegate: DetailWallControllerDelegate?
func doneButtonClicked(sender: UIBarButtonItem) {
progresHUB.show()
if let id = message?.id {
FirebaseService.db.setCommentWith(content: composeTextView.text, and: id, completion: { (succeed, comment) in
if succeed {
DispatchQueue.main.async {
self.progresHUB.hide()
if let comment = comment {
// call the delegate function in the DetailWallController
self.delegate?.commentHasSend(comment: comment)
let _ = self.navigationController?.popViewController(animated: true)
}
}
} else {
self.controller.showAlertControllerWith(title: "Error!", and: "Something went wrong with commenting the message", sumbitText: "Oke", cancelText: nil, inView: self, completion: nil)
self.progresHUB.hide()
}
})
}
}
// function which adds and lays out the views on the viewcontrollers view
private func setupViews() {
view.addSubview(textView)
view.addSubview(composeTextView)
view.addSubview(composeCountLabel)
view.addSubview(progresHUB)
view.addConstraintsWithFormat(format: "H:|-8-[v0]-8-|", views: textView)
view.addConstraintsWithFormat(format: "H:|-8-[v0]-8-|", views: composeTextView)
view.addConstraintsWithFormat(format: "H:[v0(140)]-8-|", views: composeCountLabel)
view.addConstraintsWithFormat(format: "V:|-70-[v0(30)]-8-[v1(100)]-8-[v2(24)]", views: textView, composeTextView, composeCountLabel)
}
}
//MARK: - UITextViewDelegate
extension CommentController: UITextViewDelegate {
// function which checks the character range of the given textview
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// make sure the user can't type something when the characters are more that 140
return textView.text.characters.count + (text.characters.count - range.length) <= 140
}
// function which gets called when text is changed in the given textview
func textViewDidChange(_ textView: UITextView) {
// change the labels text by the remaining characters that the user can type in
composeCountLabel.text = "\(140 - textView.text.characters.count)"
// check if there is text
if textView.text.characters.count > 0 {
// show the done button on the navigationcontroller
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonClicked(sender:)))
} else {
navigationItem.rightBarButtonItem = nil
}
}
}
|
0a4099170a6903e81d06977b1bde74c6
| 34 | 200 | 0.601408 | false | false | false | false |
bizz84/SwiftyStoreKit
|
refs/heads/master
|
Sources/SwiftyStoreKit/SwiftyStoreKit+Types.swift
|
mit
|
1
|
//
// SwiftyStoreKit+Types.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import StoreKit
// MARK: Purchases
/// The Purchased protocol allows different purchase flows to be handled by common code in simple cases
///
/// For example you could route through to
///
/// func didPurchase<P:Purchased>(item:P) { ... }
///
/// for example
/// - SwiftyStoreKit.completeTransactions (in .purchased and .restored cases)
/// - SwiftyStoreKit.restorePurchases (for results.restoredPurchases)
/// - SwiftyStoreKit.purchaseProducd (in .success case)
public protocol Purchased {
var productId: String { get }
var quantity: Int { get }
var originalPurchaseDate: Date { get }
}
extension Purchase: Purchased {
public var originalPurchaseDate: Date {
guard let date = originalTransaction?.transactionDate ?? transaction.transactionDate else {
fatalError("there should always be a transaction date, so this should not happen...")
}
return date
}
}
extension PurchaseDetails: Purchased {
public var originalPurchaseDate: Date {
guard let date = originalTransaction?.transactionDate ?? transaction.transactionDate else {
fatalError("there should always be a transaction date, so this should not happen...")
}
return date
}
}
// Restored product
public struct Purchase {
public let productId: String
public let quantity: Int
public let transaction: PaymentTransaction
public let originalTransaction: PaymentTransaction?
public let needsFinishTransaction: Bool
public init(productId: String, quantity: Int, transaction: PaymentTransaction, originalTransaction: PaymentTransaction?, needsFinishTransaction: Bool) {
self.productId = productId
self.quantity = quantity
self.transaction = transaction
self.originalTransaction = originalTransaction
self.needsFinishTransaction = needsFinishTransaction
}
}
/// Purchased product
public struct PurchaseDetails {
public let productId: String
public let quantity: Int
public let product: SKProduct
public let transaction: PaymentTransaction
public let originalTransaction: PaymentTransaction?
public let needsFinishTransaction: Bool
public init(productId: String, quantity: Int, product: SKProduct, transaction: PaymentTransaction, originalTransaction: PaymentTransaction?, needsFinishTransaction: Bool) {
self.productId = productId
self.quantity = quantity
self.product = product
self.transaction = transaction
self.originalTransaction = originalTransaction
self.needsFinishTransaction = needsFinishTransaction
}
}
/// Conform to this protocol to provide custom receipt validator
public protocol ReceiptValidator {
func validate(receiptData: Data, completion: @escaping (VerifyReceiptResult) -> Void)
}
/// Payment transaction
public protocol PaymentTransaction {
var transactionDate: Date? { get }
var transactionState: SKPaymentTransactionState { get }
var transactionIdentifier: String? { get }
var downloads: [SKDownload] { get }
}
/// Add PaymentTransaction conformance to SKPaymentTransaction
extension SKPaymentTransaction: PaymentTransaction { }
/// Products information
public struct RetrieveResults {
public let retrievedProducts: Set<SKProduct>
public let invalidProductIDs: Set<String>
public let error: Error?
public init(retrievedProducts: Set<SKProduct>, invalidProductIDs: Set<String>, error: Error?) {
self.retrievedProducts = retrievedProducts
self.invalidProductIDs = invalidProductIDs
self.error = error
}
}
/// Purchase result
public enum PurchaseResult {
case success(purchase: PurchaseDetails)
case deferred(purchase: PurchaseDetails)
case error(error: SKError)
}
/// Restore purchase results
public struct RestoreResults {
public let restoredPurchases: [Purchase]
public let restoreFailedPurchases: [(SKError, String?)]
public init(restoredPurchases: [Purchase], restoreFailedPurchases: [(SKError, String?)]) {
self.restoredPurchases = restoredPurchases
self.restoreFailedPurchases = restoreFailedPurchases
}
}
public typealias ShouldAddStorePaymentHandler = (_ payment: SKPayment, _ product: SKProduct) -> Bool
public typealias UpdatedDownloadsHandler = (_ downloads: [SKDownload]) -> Void
// MARK: Receipt verification
/// Info for receipt returned by server
public typealias ReceiptInfo = [String: AnyObject]
/// Fetch receipt result
public enum FetchReceiptResult {
case success(receiptData: Data)
case error(error: ReceiptError)
}
/// Verify receipt result
public enum VerifyReceiptResult {
case success(receipt: ReceiptInfo)
case error(error: ReceiptError)
}
/// Result for Consumable and NonConsumable
public enum VerifyPurchaseResult {
case purchased(item: ReceiptItem)
case notPurchased
}
/// Verify subscription result
public enum VerifySubscriptionResult {
case purchased(expiryDate: Date, items: [ReceiptItem])
case expired(expiryDate: Date, items: [ReceiptItem])
case notPurchased
}
public enum SubscriptionType: Hashable {
case autoRenewable
case nonRenewing(validDuration: TimeInterval)
}
public struct ReceiptItem: Purchased, Codable {
/// The product identifier of the item that was purchased. This value corresponds to the `productIdentifier` property of the `SKPayment` object stored in the transaction’s payment property.
public var productId: String
/// The number of items purchased. This value corresponds to the `quantity` property of the `SKPayment` object stored in the transaction’s payment property.
public var quantity: Int
/// The transaction identifier of the item that was purchased. This value corresponds to the transaction’s `transactionIdentifier` property.
public var transactionId: String
/// For a transaction that restores a previous transaction, the transaction identifier of the original transaction.
///
/// Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s `transactionIdentifier` property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field.
public var originalTransactionId: String
/// The date and time that the item was purchased. This value corresponds to the transaction’s `transactionDate` property.
public var purchaseDate: Date
/// For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s `transactionDate` property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed.
public var originalPurchaseDate: Date
/// The primary key for identifying subscription purchases.
public var webOrderLineItemId: String?
/// The expiration date for the subscription, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is **only** present for **auto-renewable** subscription receipts.
public var subscriptionExpirationDate: Date?
/// For a transaction that was canceled by Apple customer support, the time and date of the cancellation.
///
/// Treat a canceled receipt the same as if no purchase had ever been made.
public var cancellationDate: Date?
/// Indicates whether or not the subscription item is currently within a given trial period.
public var isTrialPeriod: Bool
/// Indicates whether or not the subscription item is currently within an intro offer period.
public var isInIntroOfferPeriod: Bool
/// An indicator that a subscription has been canceled due to an upgrade. This field is only present for upgrade transactions.
public var isUpgraded: Bool
public init(productId: String, quantity: Int, transactionId: String, originalTransactionId: String, purchaseDate: Date, originalPurchaseDate: Date, webOrderLineItemId: String?, subscriptionExpirationDate: Date?, cancellationDate: Date?, isTrialPeriod: Bool, isInIntroOfferPeriod: Bool, isUpgraded: Bool) {
self.productId = productId
self.quantity = quantity
self.transactionId = transactionId
self.originalTransactionId = originalTransactionId
self.purchaseDate = purchaseDate
self.originalPurchaseDate = originalPurchaseDate
self.webOrderLineItemId = webOrderLineItemId
self.subscriptionExpirationDate = subscriptionExpirationDate
self.cancellationDate = cancellationDate
self.isTrialPeriod = isTrialPeriod
self.isInIntroOfferPeriod = isInIntroOfferPeriod
self.isUpgraded = isUpgraded
}
}
/// Error when managing receipt
public enum ReceiptError: Swift.Error {
/// No receipt data
case noReceiptData
/// No data received
case noRemoteData
/// Error when encoding HTTP body into JSON
case requestBodyEncodeError(error: Swift.Error)
/// Error when proceeding request
case networkError(error: Swift.Error)
/// Error when decoding response
case jsonDecodeError(string: String?)
/// Receive invalid - bad status returned
case receiptInvalid(receipt: ReceiptInfo, status: ReceiptStatus)
}
/// Status code returned by remote server
///
/// See Table 2-1 Status codes
public enum ReceiptStatus: Int {
/// Not decodable status
case unknown = -2
/// No status returned
case none = -1
/// valid statua
case valid = 0
/// The App Store could not read the JSON object you provided.
case jsonNotReadable = 21000
/// The data in the receipt-data property was malformed or missing.
case malformedOrMissingData = 21002
/// The receipt could not be authenticated.
case receiptCouldNotBeAuthenticated = 21003
/// The shared secret you provided does not match the shared secret on file for your account.
case secretNotMatching = 21004
/// The receipt server is not currently available.
case receiptServerUnavailable = 21005
/// This receipt is valid but the subscription has expired. When this status code is returned to your server, the receipt data is also decoded and returned as part of the response.
case subscriptionExpired = 21006
/// This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.
case testReceipt = 21007
/// This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead.
case productionEnvironment = 21008
var isValid: Bool { return self == .valid}
}
// Receipt field as defined in : https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1
public enum ReceiptInfoField: String {
/// Bundle Identifier. This corresponds to the value of CFBundleIdentifier in the Info.plist file.
case bundle_id
/// The app’s version number.This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the Info.plist.
case application_version
/// The version of the app that was originally purchased. This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the Info.plist file when the purchase was originally made.
case original_application_version
/// The date when the app receipt was created.
case creation_date
/// The date that the app receipt expires. This key is present only for apps purchased through the Volume Purchase Program.
case expiration_date
/// The receipt for an in-app purchase.
case in_app
public enum InApp: String {
/// The number of items purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction’s payment property.
case quantity
/// The product identifier of the item that was purchased. This value corresponds to the productIdentifier property of the SKPayment object stored in the transaction’s payment property.
case product_id
/// The transaction identifier of the item that was purchased. This value corresponds to the transaction’s transactionIdentifier property.
case transaction_id
/// For a transaction that restores a previous transaction, the transaction identifier of the original transaction. Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s transactionIdentifier property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field.
case original_transaction_id
/// The date and time that the item was purchased. This value corresponds to the transaction’s transactionDate property.
case purchase_date
/// For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s transactionDate property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed.
case original_purchase_date
/// The expiration date for the subscription, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT. This key is only present for auto-renewable subscription receipts.
case expires_date
/// For a transaction that was canceled by Apple customer support, the time and date of the cancellation. Treat a canceled receipt the same as if no purchase had ever been made.
case cancellation_date
#if os(iOS) || os(tvOS)
/// A string that the App Store uses to uniquely identify the application that created the transaction. If your server supports multiple applications, you can use this value to differentiate between them. Apps are assigned an identifier only in the production environment, so this key is not present for receipts created in the test environment. This field is not present for Mac apps. See also Bundle Identifier.
case app_item_id
#endif
/// An arbitrary number that uniquely identifies a revision of your application. This key is not present for receipts created in the test environment.
case version_external_identifier
/// The primary key for identifying subscription purchases.
case web_order_line_item_id
}
}
#if os(OSX)
public enum ReceiptExitCode: Int32 {
/// If validation fails in OS X, call exit with a status of 173. This exit status notifies the system that your application has determined that its receipt is invalid. At this point, the system attempts to obtain a valid receipt and may prompt for the user’s iTunes credentials
case notValid = 173
}
#endif
|
f14c5e508daaa7cea1d78d31aa347c6e
| 47.172107 | 421 | 0.743932 | false | false | false | false |
tsolomko/SWCompression
|
refs/heads/develop
|
Sources/swcomp/Benchmarks/BenchmarkMetadata.swift
|
mit
|
1
|
// Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
struct BenchmarkMetadata: Codable, Equatable {
var timestamp: TimeInterval?
var osInfo: String
var swiftVersion: String
var swcVersion: String
var description: String?
private static func run(command: URL, arguments: [String] = []) throws -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.executableURL = command
task.arguments = arguments
task.standardInput = nil
try task.run()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
private static func getExecURL(for command: String) throws -> URL {
let args = ["-c", "which \(command)"]
#if os(Windows)
swcompExit(.benchmarkCannotGetSubcommandPathWindows)
#else
let output = try BenchmarkMetadata.run(command: URL(fileURLWithPath: "/bin/sh"), arguments: args)
#endif
return URL(fileURLWithPath: String(output.dropLast()))
}
private static func getOsInfo() throws -> String {
#if os(Linux)
return try BenchmarkMetadata.run(command: BenchmarkMetadata.getExecURL(for: "uname"), arguments: ["-a"])
#else
#if os(Windows)
return "Unknown Windows OS"
#else
return try BenchmarkMetadata.run(command: BenchmarkMetadata.getExecURL(for: "sw_vers"))
#endif
#endif
}
init(_ description: String?, _ preserveTimestamp: Bool) throws {
self.timestamp = preserveTimestamp ? Date.timeIntervalSinceReferenceDate : nil
self.osInfo = try BenchmarkMetadata.getOsInfo()
#if os(Windows)
self.swiftVersion = "Unknown Swift version on Windows"
#else
self.swiftVersion = try BenchmarkMetadata.run(command: BenchmarkMetadata.getExecURL(for: "swift"),
arguments: ["-version"])
#endif
self.swcVersion = _SWC_VERSION
self.description = description
}
func print() {
Swift.print("OS Info: \(self.osInfo)", terminator: "")
Swift.print("Swift version: \(self.swiftVersion)", terminator: "")
Swift.print("SWC version: \(self.swcVersion)")
if let timestamp = self.timestamp {
Swift.print("Timestamp: " +
DateFormatter.localizedString(from: Date(timeIntervalSinceReferenceDate: timestamp),
dateStyle: .short, timeStyle: .short))
}
if let description = self.description {
Swift.print("Description: \(description)")
}
Swift.print()
}
}
|
bcc7c4e01903df42ea7556ca98aa55b5
| 34.518072 | 116 | 0.602442 | false | false | false | false |
VladiMihaylenko/omim
|
refs/heads/master
|
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/UGC/UGCAddReview/UGCAddReviewController.swift
|
apache-2.0
|
2
|
@objc(MWMGCReviewSaver)
protocol UGCReviewSaver {
typealias onSaveHandler = (Bool) -> Void
func saveUgc(model: UGCAddReviewController.Model, resultHandler: @escaping onSaveHandler)
}
@objc(MWMUGCAddReviewController)
final class UGCAddReviewController: MWMTableViewController {
typealias Model = UGCReviewModel
weak var textCell: UGCAddReviewTextCell?
var reviewPosted = false
enum Sections {
case ratings
case text
}
@objc static func instance(model: Model, saver: UGCReviewSaver) -> UGCAddReviewController {
let vc = UGCAddReviewController(nibName: toString(self), bundle: nil)
vc.model = model
vc.saver = saver
return vc
}
private var model: Model! {
didSet {
sections = []
assert(!model.ratings.isEmpty)
sections.append(.ratings)
sections.append(.text)
}
}
private var sections: [Sections] = []
private var saver: UGCReviewSaver!
override func viewDidLoad() {
super.viewDidLoad()
configNavBar()
configTableView()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParentViewController && !reviewPosted {
Statistics.logEvent(kStatUGCReviewCancel)
}
}
private func configNavBar() {
title = model.title
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onDone))
}
private func configTableView() {
tableView.register(cellClass: UGCAddReviewRatingCell.self)
tableView.register(cellClass: UGCAddReviewTextCell.self)
tableView.estimatedRowHeight = 48
tableView.rowHeight = UITableViewAutomaticDimension
}
@objc private func onDone() {
guard let text = textCell?.reviewText else {
assertionFailure()
return
}
reviewPosted = true
model.text = text
saver.saveUgc(model: model, resultHandler: { (saveResult) in
guard let nc = self.navigationController else { return }
if !saveResult {
nc.popViewController(animated: true)
return
}
Statistics.logEvent(kStatUGCReviewSuccess)
let onSuccess = { Toast.toast(withText: L("ugc_thanks_message_auth")).show() }
let onError = { Toast.toast(withText: L("ugc_thanks_message_not_auth")).show() }
let onComplete = { () -> Void in nc.popToRootViewController(animated: true) }
if MWMAuthorizationViewModel.isAuthenticated() || MWMPlatform.networkConnectionType() == .none {
if MWMAuthorizationViewModel.isAuthenticated() {
onSuccess()
} else {
onError()
}
nc.popViewController(animated: true)
} else {
Statistics.logEvent(kStatUGCReviewAuthShown, withParameters: [kStatFrom: kStatAfterSave])
let authVC = AuthorizationViewController(barButtonItem: self.navigationItem.rightBarButtonItem!,
sourceComponent: .UGC,
successHandler: {_ in onSuccess()},
errorHandler: {_ in onError()},
completionHandler: {_ in onComplete()})
self.present(authVC, animated: true, completion: nil)
}
})
}
override func numberOfSections(in _: UITableView) -> Int {
return sections.count
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
switch sections[section] {
case .ratings: return model.ratings.count
case .text: return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch sections[indexPath.section] {
case .ratings:
let cell = tableView.dequeueReusableCell(withCellClass: UGCAddReviewRatingCell.self, indexPath: indexPath) as! UGCAddReviewRatingCell
cell.model = model.ratings[indexPath.row]
return cell
case .text:
let cell = tableView.dequeueReusableCell(withCellClass: UGCAddReviewTextCell.self, indexPath: indexPath) as! UGCAddReviewTextCell
cell.reviewText = model.text
textCell = cell
return cell
}
}
}
|
31eb96ec68bc5e2d91c7ea2ddf83a96e
| 31.384615 | 139 | 0.663895 | false | false | false | false |
JoeLago/MHGDB-iOS
|
refs/heads/master
|
MHGDB/Model/Component.swift
|
mit
|
1
|
//
// MIT License
// Copyright (c) Gathering Hall Studios
//
import Foundation
import GRDB
class Component: RowConvertible {
let id: Int
let name: String
let icon: String
let type: String?
let quantity: Int
required init(row: Row) {
id = row["cid"]
name = row["cname"]
icon = row["cicon_name"]
type = row["ctype"]
quantity = row["quantity"]
}
}
extension Database {
func components(itemId: Int) -> [Component] {
let query = "SELECT *,"
+ " component.name AS cname,"
+ " component.icon_name AS cicon_name,"
+ " components.type AS ctype,"
+ " component._id AS cid"
+ " FROM components"
+ " LEFT JOIN items ON components.created_item_id = items._id"
+ " LEFT JOIN items AS component ON components.component_item_id = component._id"
+ " WHERE items._id == \(itemId)"
return fetch(query)
}
}
|
705def758bd1b2e80dbae4ac499111ec
| 23.625 | 93 | 0.551269 | false | false | false | false |
Teleglobal/MHQuickBlockLib
|
refs/heads/master
|
MHQuickBlockLib/Classes/DialogServiceManager.swift
|
mit
|
1
|
//
// DialogService.swift
// Pods
//
// Created by Muhammad Adil on 10/13/16.
//
//
import Foundation
import Quickblox
import RealmSwift
open class DialogServiceManager: NSObject {
// MARK:- Manage Delegates
var joinRoomCompletionHandler: ((Error?) -> Void)?
/**
*
*
*/
open var dialogDelegates : [DialogServiceDelegate] = []
/**
*
*
*/
open func addDialogDelegate(_ dialogDelegate: DialogServiceDelegate) {
for i in 0..<dialogDelegates.count {
let object: DialogServiceDelegate = dialogDelegates[i]
if (object === dialogDelegate) {
return
}
}
dialogDelegates.append(dialogDelegate)
}
/**
*
*
*/
open func removeDialogDelegate(_ dialogDelegate: DialogServiceDelegate) {
for i in 0..<dialogDelegates.count {
let object: DialogServiceDelegate = dialogDelegates[i]
if (object === dialogDelegate) {
dialogDelegates.remove(at: i)
return
}
}
}
/**
*
*
*/
internal func removeAllDialogDelegates() {
self.dialogDelegates.removeAll()
}
/**
*
*
*/
internal func notifyDialogsUpdatedInStorage() {
for dialogDelegate in dialogDelegates {
dialogDelegate.dialogsUpdatedInStorage(dialogDelegate)
}
}
// MARK:- Public Methods
/**
*
*
*/
open func createPrivateDialogWithUser(_ userId: String,
addCustomData: Bool = true,
successBlock: ((Dialog?) -> Void)?,
errorBlock: qb_response_block_t?) {
self.createDialogOnServer([userId],
dialogType: .private,
groupName: "",
addCustomData: addCustomData,
successBlock: { (response, createdDialog) in
if (response?.isSuccess)! && response?.status == .created {
successBlock!(self.qbDialogToLocalDialog(createdDialog!))
} else {
errorBlock!(response!)
}
}) { (response) in
errorBlock!(response)
}
}
/**
*
*
*/
open func createGroupDialogWithUsers(_ userIds: [String],
groupName: String,
addCustomData: Bool = true,
successBlock: ((Dialog?) -> Void)?,
errorBlock: qb_response_block_t?) {
self.createDialogOnServer(userIds,
dialogType: .group,
groupName: groupName,
addCustomData: addCustomData,
successBlock: { (response, createdDialog) in
if (response?.isSuccess)! && response?.status == .created {
successBlock!(self.qbDialogToLocalDialog(createdDialog!))
} else {
errorBlock!(response!)
}
}) { (response) in
errorBlock!(response)
}
}
/**
*
*
*/
open func deleteDialog(_ dialogId: String) {
let dialogIds: Set<String> = [dialogId]
QBRequest.deleteDialogs(withIDs: dialogIds,
forAllUsers: true,
successBlock: { (response, deletedObjectsIDs, notFoundObjectsIDs, wrongPermissionsObjectsIDs) in
if response.isSuccess {
let realm = try! Realm()
for deletedObjectId in deletedObjectsIDs {
let predicate = NSPredicate(format: "dialogID = %@", deletedObjectId)
try! realm.write {
realm.delete(realm.objects(Dialog.self).filter(predicate))
}
}
self.notifyDialogsUpdatedInStorage()
}
}) { (response) in
}
}
/**
*
*
*/
open func inviteUsersToDialog(_ dialog: Dialog, _ userIds: [String], errorBlock: @escaping (Error?) -> Void) {
Messenger.dialogServiceManager.fetchDialogWithId(dialog.dialogID!,
qbDialogBlock: { (qbChatDialog) in
if let qbDialog = qbChatDialog {
var occupantIDs: [String] = []
for value in userIds {
if let id = Int(value) {
let occupant = NSNumber(value: id)
if !qbDialog.occupantIDs!.contains(occupant){
occupantIDs.append(value)
}
}
}
qbDialog.pushOccupantsIDs = occupantIDs
QBRequest.update(qbDialog,
successBlock: { (response, dialog) in
userIds.forEach { (userId) in
self.inviateToDialog(dialog: dialog,
occupantID: NSNumber(value: Int(userId)!),
notificationMsg: "Invited")
}
// TODO:- Update in Local DB
errorBlock(nil)
}) { (errorResponse) in
errorBlock(errorResponse.error!.error!)
}
} else {
let userInfo: [AnyHashable: Any] = [ NSLocalizedDescriptionKey : NSLocalizedString("Error",
value: "Something Went wrong. Please try again!",
comment: "")]
let error: NSError = NSError(domain: "",
code: -1,
userInfo: userInfo)
errorBlock(error)
}
}) { (error) in
if error != nil {
errorBlock(error)
}
}
}
/**
*
*
*/
open func updateDialog(_ dialogId: String, _ name: String, errorBlock: @escaping (Error?) -> Void) {
Messenger.dialogServiceManager.fetchDialogWithId(dialogId, qbDialogBlock: { (qbChatDialog) in
if let qbDialog = qbChatDialog {
qbDialog.name = name
QBRequest.update(qbDialog,
successBlock: { (response, dialog) in
// TODO:- Update in Local DB
errorBlock(nil)
}) { (errorResponse) in
errorBlock(errorResponse.error!.error!)
}
} else {
let userInfo: [AnyHashable: Any] = [ NSLocalizedDescriptionKey : NSLocalizedString("Error",
value: "Something Went wrong. Please try again!",
comment: "")]
let error: NSError = NSError(domain: "",
code: -1,
userInfo: userInfo)
errorBlock(error)
}
}) { (error) in
errorBlock(error)
}
}
// MARK:- Fetch Dialogs
/**
*
*
*/
open func fetchDialogWithId(_ dialogId: String, qbDialogBlock: @escaping (QBChatDialog?) -> Void, errorBlock: @escaping (Error?) -> Void) {
let request: ()->() = {
let responsePage = QBResponsePage(limit: 1, skip: 0)
QBRequest.dialogs(for: responsePage,
extendedRequest: ["_id":dialogId],
successBlock: { (response, dialogObjects, dialogsUsers, page) in
self.createOrUpdateLocalDialogs(dialogObjects, success: { (error) in
if error == nil {
self.notifyDialogsUpdatedInStorage()
if dialogObjects.count == 1 {
if let dialog = dialogObjects.first {
qbDialogBlock(dialog)
} else {
qbDialogBlock(nil)
}
}
}
errorBlock(error)
})
}, errorBlock: { (error : QBResponse) in
errorBlock(error.error?.error as NSError?)
})
}
request()
}
/**
* Fetch dialog with last activity date from date
*
*/
public func fetchDialogsUpdatedFromDate(
_ responsePage: QBResponsePage,
_ extendedRequest: [String : String],
_ completionBlock: ((QBResponse) -> Void)?) {
QBRequest.dialogs(for: responsePage,
extendedRequest: extendedRequest,
successBlock: { (response: QBResponse,
dialogs: [QBChatDialog]?, dialogsUsersIDs: Set<NSNumber>?, page: QBResponsePage?) -> Void in
self.createOrUpdateLocalDialogs(dialogs, success: { (error) in
responsePage.skip += dialogs!.count
self.notifyDialogsUpdatedInStorage()
if (page!.totalEntries > UInt(responsePage.skip)) {
self.fetchDialogsUpdatedFromDate(responsePage,
extendedRequest,
completionBlock)
} else {
completionBlock!(response)
}
})
},
errorBlock: { (response: QBResponse) -> Void in
completionBlock!(response) })
}
// MARK:- Public In-Memory Fetch Requests
/**
*
*
*/
private func dialogsInMemory(_ filter : String = "") -> Results<Dialog>? {
let predicate = NSPredicate(format: "name contains[c] %@ AND dialogFor = %@", filter, "provider")
let realm = try! Realm()
return realm.objects(Dialog.self).filter(predicate).sorted(byKeyPath: "updatedAt",
ascending: false)
}
/**
*
*
*/
open func dialogsInMemory(_ filter : String = "") -> [Dialog]? {
let dialogs: Results<Dialog> = self.dialogsInMemory(filter)!
return Array(dialogs)
}
/**
*
*
*/
open func dialogInMemory(_ dialogId: String) -> Dialog? {
let realm = try! Realm()
return realm.objects(Dialog.self).filter("dialogID = %@", dialogId).first
}
/**
*
*
*/
open func dialogOfUserInMemory(_ userId: String) -> Dialog? {
let realm = try! Realm()
let dialogs = realm.objects(Dialog.self).filter("type = 3")
for dialog in dialogs {
for occupant in dialog.occupantIDs {
if ((occupant.value(forKey: "value") as AnyObject).intValue == Int(userId)) {
return dialog
}
}
}
return nil
}
/**
*
*
*/
open func updateDialogMessageCountToZero(_ dialogId: String) {
let dialog = self.dialogInMemory(dialogId)
let realm = try! Realm()
try! realm.write {
dialog?.unReadMessageCount = 0
realm.add(dialog!,
update: true)
}
self.notifyDialogsUpdatedInStorage()
}
/**
*
*
*/
open func dialogOccupantIds(_ dialogId: String, withoutMe: Bool = false) -> [UInt]? {
var occupants : [UInt] = []
for occupant in (self.dialogInMemory(dialogId)?.occupantIDs)! {
if ((occupant.value(forKey: "value") as AnyObject).uintValue)! == Messenger.chatAuthServiceManager.currentUser()?.id && withoutMe == true {
continue
} else {
occupants.append(((occupant.value(forKey: "value") as AnyObject).uintValue)!)
}
}
return occupants
}
// MARK:- Private Methods (Create Dialog Local Storage)
/**
*
*
*/
internal func createOrUpdateLocalDialog(_ dialog: Dialog) {
// Get the default Realm
let realm = try! Realm()
// You only need to do this once (per thread)
// Add to the Realm inside a transaction
try! realm.write {
realm.add(dialog,
update: true)
}
// LastRequestDate.updateDialogsUpdatedAt()
}
/**
*
*
*/
@objc internal func joinRoom(_ dialogObject: QBChatDialog){
if (dialogObject.type == .group && dialogObject.isJoined() == false) {
dialogObject.join(completionBlock: { (error) in
if (error != nil) {
print((error?.localizedDescription)! as String)
}
self.joinRoomCompletionHandler?(error)
})
} else {
self.joinRoomCompletionHandler?(nil)
}
}
/**
*
*
*/
fileprivate func createOrUpdateLocalDialog(_ dialogObject: QBChatDialog, success: @escaping (Error?) -> Void) {
self.createOrUpdateLocalDialog(self.qbDialogToLocalDialog(dialogObject))
self.joinRoomCompletionHandler = success
self.joinRoom(dialogObject)
}
/**
*
*
*/
fileprivate func createOrUpdateLocalDialogs(_ dialogObjects: [QBChatDialog]?, success: @escaping (Error?) -> Void) {
for _dialog in dialogObjects! {
self.createOrUpdateLocalDialog(_dialog, success: { (error) in
success(error)
})
}
for _dialog in dialogObjects! {
DispatchQueue.global().async {
let extendedRequest = ["sort_desc" : "updated_at", "mark_as_read": "0"]
Messenger.messageServiceManager.fetchAllMessagesFromServerWithDialogId(_dialog.id!,
QBResponsePage(limit: PageLimit),
extendedRequest, {
(response) in
})
}
}
}
/**
*
*
*/
fileprivate func qbDialogToLocalDialog(_ qbDialog: QBChatDialog) -> Dialog {
let dialog = Dialog()
dialog.dialogID = qbDialog.id!
if (qbDialog.lastMessageText != nil) {
dialog.lastMessage = qbDialog.lastMessageText!
}
if (qbDialog.lastMessageDate != nil) {
dialog.lastMessageDate = qbDialog.lastMessageDate!
}
dialog.lastMessageUserID = Int(qbDialog.lastMessageUserID)
dialog.name = qbDialog.name!
if qbDialog.roomJID != nil {
dialog.roomID = qbDialog.roomJID!
}
dialog.unReadMessageCount = Int(qbDialog.unreadMessagesCount)
dialog.updatedAt = qbDialog.updatedAt
dialog.createdAt = qbDialog.createdAt
dialog.type = Int(qbDialog.type.rawValue)
for occupant in qbDialog.occupantIDs! {
dialog.occupantIDs.append(NumberObject(value: [occupant]))
}
if let data = qbDialog.data {
if (data["dialogType"] as! String).components(separatedBy: ",").contains("provider") {
dialog.dialogFor = "provider"
}
}
return dialog
}
/**
*
*
*/
internal func qbDialogFromLocalDialog(_ dialog: Dialog) -> QBChatDialog {
var dialogType: QBChatDialogType = .group
switch dialog.type {
case 1:
dialogType = .publicGroup
case 2:
dialogType = .group
default:
dialogType = .private
}
let qbDialog = QBChatDialog(dialogID: dialog.dialogID, type: dialogType)
if (dialog.lastMessage != nil) {
qbDialog.lastMessageText = dialog.lastMessage
}
if (dialog.lastMessageDate != nil) {
qbDialog.lastMessageDate = dialog.lastMessageDate! as Date
}
qbDialog.lastMessageUserID = UInt(dialog.lastMessageUserID)
qbDialog.name = dialog.name!
qbDialog.unreadMessagesCount = UInt(dialog.unReadMessageCount)
qbDialog.updatedAt = dialog.updatedAt as Date?
qbDialog.createdAt = dialog.createdAt as Date?
var occupants : [NSNumber] = []
for occupant in dialog.occupantIDs {
occupants.append(occupant.value(forKey: "value") as! NSNumber)
}
qbDialog.occupantIDs = occupants;
return qbDialog
}
// MARK:- Private Server Methods (Create Dialog On Server)
fileprivate func createDialogOnServer(_ userIds: [String],
dialogType: QBChatDialogType = .private,
groupName: String,
addCustomData: Bool = true,
successBlock: ((QBResponse?, QBChatDialog?) -> Void)?,
errorBlock: qb_response_block_t?) {
let chatDialog: QBChatDialog = QBChatDialog(dialogID: nil, type: dialogType)
let intArray = userIds.map
{
NSNumber(value: Int($0)! as Int)
}
chatDialog.occupantIDs = intArray
chatDialog.name = groupName
chatDialog.lastMessageDate = Date()
if (addCustomData) {
chatDialog.data = ["class_name" : "DialogData", "dialogType" : "provider"]
}
self.createDialog(chatDialog, successBlock: successBlock, errorBlock: errorBlock)
}
/**
*
*
*/
fileprivate func createDialog(_ chatDialog: QBChatDialog,
successBlock: ((QBResponse?, QBChatDialog?) -> Void)?,
errorBlock: qb_response_block_t?) {
QBRequest.createDialog(chatDialog, successBlock: { (response: QBResponse, createdDialog: QBChatDialog?) in
if (createdDialog != nil && response.isSuccess && response.status == .created) {
self.createOrUpdateLocalDialogs([createdDialog!],
success: { (error) in
if error == nil {
self.sendInviateMessageToDialog(createdDialog!)
self.notifyDialogsUpdatedInStorage()
successBlock!(response, createdDialog)
} else {
//errorBlock(error)
}
})
}
}) { (errorResponse: QBResponse) in
errorBlock!(errorResponse)
}
}
/**
*
*
*/
fileprivate func sendInviateMessageToDialog(_ dialog: QBChatDialog) {
dialog.occupantIDs?.forEach({ (occupantID) in
self.inviateToDialog(dialog: dialog, occupantID: occupantID, notificationMsg: "Created")
})
}
fileprivate func inviateToDialog(dialog: QBChatDialog, occupantID: NSNumber, notificationMsg: String) {
let inviteMessage: QBChatMessage = QBChatMessage()
let timestamp: TimeInterval = Date().timeIntervalSince1970
inviteMessage.customParameters["date_sent"] = timestamp
inviteMessage.customParameters["dialogKey"] = dialog.id
inviteMessage.customParameters["userId"] = Messenger.chatAuthServiceManager.currentUser()?.id
inviteMessage.recipientID = occupantID.uintValue
if dialog.type == .private {
inviteMessage.customParameters["notification_type"] = "PrivateChat"
} else if dialog.type == .group {
inviteMessage.customParameters["notification_type"] = "GroupChat"
}
inviteMessage.customParameters["msg"] = notificationMsg
QBChat.instance.sendSystemMessage(inviteMessage, completion: { (error) in
})
}
}
|
6a1bbb8aa843b3bf5fde58cb346b383c
| 36.176389 | 197 | 0.38002 | false | false | false | false |
netguru/inbbbox-ios
|
refs/heads/develop
|
Inbbbox/Source Files/Views/Custom/EmptyDataSetView.swift
|
gpl-3.0
|
1
|
//
// EmptyDataSetView.swift
// Inbbbox
//
// Created by Peter Bruz on 23/03/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
class EmptyDataSetView: UIView {
fileprivate let descriptionLabel = UILabel.newAutoLayout()
fileprivate let imageView = UIImageView.newAutoLayout()
fileprivate var didUpdateConstraints = false
override init(frame: CGRect) {
super.init(frame: frame)
imageView.image = UIImage(named: "logo-empty")
imageView.contentMode = .scaleAspectFit
addSubview(imageView)
descriptionLabel.numberOfLines = 0
descriptionLabel.textAlignment = .center
addSubview(descriptionLabel)
}
@available(*, unavailable, message: "Use init(frame:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
if !didUpdateConstraints {
didUpdateConstraints = true
imageView.autoAlignAxis(toSuperviewAxis: .vertical)
imageView.autoAlignAxis(.horizontal, toSameAxisOf: imageView.superview!, withOffset: -90)
imageView.autoSetDimensions(to: CGSize(width: 140, height: 140))
descriptionLabel.autoAlignAxis(toSuperviewAxis: .vertical)
descriptionLabel.autoPinEdge(.top, to: .bottom, of: imageView, withOffset: 40)
descriptionLabel.autoPinEdge(toSuperviewMargin: .leading)
descriptionLabel.autoPinEdge(toSuperviewMargin: .trailing)
}
super.updateConstraints()
}
func setDescriptionText(firstLocalizedString: String, attachmentImage: UIImage?,
imageOffset: CGPoint, lastLocalizedString: String) {
descriptionLabel.attributedText = {
let compoundAttributedString = NSMutableAttributedString.emptyDataSetStyledString(firstLocalizedString)
let textAttachment: NSTextAttachment = NSTextAttachment()
textAttachment.image = attachmentImage
if let image = textAttachment.image {
textAttachment.bounds = CGRect(origin: imageOffset, size: image.size)
}
let attributedStringWithImage: NSAttributedString = NSAttributedString(attachment: textAttachment)
compoundAttributedString.append(attributedStringWithImage)
let lastAttributedString = NSMutableAttributedString.emptyDataSetStyledString(lastLocalizedString)
compoundAttributedString.append(lastAttributedString)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
compoundAttributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle,
range: NSRange(location: 0, length: compoundAttributedString.length))
return compoundAttributedString
}()
}
}
|
a2ba4451b4e286cff85afc3711a6ea34
| 37.552632 | 115 | 0.690444 | false | false | false | false |
dipen30/Qmote
|
refs/heads/master
|
KodiRemote/KodiRemote/Controllers/MoviesTableViewController.swift
|
apache-2.0
|
1
|
//
// MoviesTableViewController.swift
// Kodi Remote
//
// Created by Quixom Technology on 29/12/15.
// Copyright © 2015 Quixom Technology. All rights reserved.
//
import Foundation
import Kingfisher
class MoviesTableViewController: BaseTableViewController {
var movieObjs = NSArray()
var rc: RemoteCalls!
override func viewDidLoad() {
super.viewDidLoad()
self.rc = RemoteCalls(ipaddress: global_ipaddress, port: global_port)
self.rc.jsonRpcCall("VideoLibrary.GetMovies", params: "{\"properties\":[\"genre\",\"year\",\"thumbnail\",\"runtime\", \"file\"]}"){(response: AnyObject?) in
self.generateResponse(response as! NSDictionary)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.movieObjs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MoviesTableViewCell", for: indexPath) as! MoviesTableViewCell
let movieDetails = self.movieObjs[(indexPath as NSIndexPath).row] as! NSDictionary
cell.movieLabel.text = movieDetails["label"] as? String
cell.genreLabel.text = (movieDetails["genre"] as! NSArray).componentsJoined(by: ", ")
cell.timeLabel.text = String(movieDetails["runtime"] as! Int / 60) + " min"
cell.yearLabel.text = String(movieDetails["year"] as! Int)
let thumbnail = movieDetails["thumbnail"] as! String
let url = URL(string: getThumbnailUrl(thumbnail))
cell.movieImage.contentMode = .scaleAspectFit
cell.movieImage.kf.setImage(with: url!)
return cell
}
func generateResponse(_ jsonData: AnyObject){
let total = (jsonData["limits"] as! NSDictionary)["total"] as! Int
if total != 0 {
let moviesDetails = jsonData["movies"] as! NSArray
self.movieObjs = moviesDetails
}else {
// Display No data found message
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MovieTabBarController" {
let movieTabBarC = segue.destination as! UITabBarController
let destination = movieTabBarC.viewControllers?.first as! MovieDetailsViewController
if let movieIndex = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row {
destination.movieid = (self.movieObjs[movieIndex] as! NSDictionary)["movieid"] as! Int
destination.moviefile = (self.movieObjs[movieIndex] as! NSDictionary)["file"] as! String
segue.destination.navigationItem.title = (self.movieObjs[movieIndex] as! NSDictionary)["label"] as? String
}
}
}
}
|
fc396c962daa32b8fc6563dd9709152d
| 36.841463 | 164 | 0.638414 | false | false | false | false |
sebastiangoetz/slr-toolkit
|
refs/heads/master
|
ios-client/SLR Toolkit/Logic/ProjectManager.swift
|
epl-1.0
|
1
|
import CoreData
import Foundation
import SwiftyBibtex
/// Utility functions for projects.
enum ProjectManager {
/// Reads a project's name from a .project file in its directory.
static func projectName(forProjectAt url: URL) -> String? {
guard let xmlFileURL = FileManager.default.contentsOfDirectory(at: url, matching: { $1 == ".project" }).first else { return nil }
do {
// TODO properly parse xml
let content = try String(contentsOf: xmlFileURL)
let regex = try NSRegularExpression(pattern: "<name>(.*)</name>", options: [])
let match = regex.firstMatch(in: content, options: [], range: NSRange(location: 0, length: content.utf16.count))
guard let nsRange = match?.range(at: 1) else { return nil }
guard let swiftRange = Range(nsRange, in: content) else { return nil }
return String(content[swiftRange])
} catch {
return nil
}
}
/// Writes a new name into a project's .project file.
static func setName(_ newName: String, for project: Project) -> Bool {
guard let xmlFileURL = FileManager.default.contentsOfDirectory(at: project.url, matching: { $1 == ".project" }).first else { return false }
do {
var content = try String(contentsOf: xmlFileURL)
let regex = try NSRegularExpression(pattern: "<name>(.*)</name>", options: [])
let match = regex.firstMatch(in: content, options: [], range: NSRange(location: 0, length: content.utf16.count))
guard let nsRange = match?.range(at: 1) else { return false }
guard let swiftRange = Range(nsRange, in: content) else { return false }
content.replaceSubrange(swiftRange, with: newName)
try content.write(to: xmlFileURL, atomically: true, encoding: .utf8)
// TODO show as change in UI (on commit button)
return true
} catch {
return false
}
}
/// Creates a new project and its contents.
@discardableResult static func createProjectSync(name: String, username: String, token: String, repositoryURL: String, pathInGitDirectory: String, pathInRepository: String, managedObjectContext: NSManagedObjectContext) -> Project {
let project = Project.newEntity(name: name, username: username, token: token, repositoryURL: repositoryURL, pathInGitDirectory: pathInGitDirectory, pathInRepository: pathInRepository, in: managedObjectContext)
managedObjectContext.saveAndLogError() // Workaround, otherwise a Core Data exception is thrown
createContents(for: project, managedObjectContext: managedObjectContext)
return project
}
/// Creates a new project and its contents.
static func createProjectAsync(name: String, username: String, token: String, repositoryURL: String, pathInGitDirectory: String, pathInRepository: String, managedObjectContext: NSManagedObjectContext, completion: @escaping (Project) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
completion(createProjectSync(name: name, username: username, token: token, repositoryURL: repositoryURL, pathInGitDirectory: pathInGitDirectory, pathInRepository: pathInRepository, managedObjectContext: managedObjectContext))
}
}
/// Updates a project (after new changes have been pulled) by re-creating its contents.
static func updateProject(_ project: Project, fileModificationDates: [String: Date], completion: @escaping () -> Void) {
guard fileModificationDates != project.fileModificationDates else {
completion()
return
}
DispatchQueue.global(qos: .userInitiated).async {
let managedObjectContext = PersistenceController.shared.container.viewContext
// Remember non-outstanding decisions
let decisions = project.entries.reduce(into: [String: Entry.Decision]()) { acc, entry in
if entry.decision != .outstanding {
acc[entry.citationKey] = entry.decision
}
}
// Delete all classes and entries
project.classes.filter { $0.parent == nil }.forEach { managedObjectContext.delete($0) } // Delete rule is "cascade"
project.entries.forEach { managedObjectContext.delete($0) }
let entries = createContents(for: project, managedObjectContext: managedObjectContext)
for entry in entries {
if let decision = decisions[entry.citationKey] {
entry.decision = decision
}
}
completion()
}
}
/// Commits a project's changes.
static func commitChanges(project: Project) throws -> (Int, Int) {
_ = setName(project.name, for: project)
// TODO handle multiple bib files, each entry needs to know to which file it belongs. Perhaps with a new Core Data entity that Entries can reference.
let bibFileURL = FileManager.default.contentsOfDirectory(at: project.url) { $1.hasSuffix(".bib") }.first!
let bibText = try String(contentsOf: bibFileURL)
var lines = bibText.split(omittingEmptySubsequences: false) { $0 == "\n" || $0 == "\r\n" } // TODO Switch to approach on character level
// Insert or modify "classes" lines
let classifiedEntries = project.classifiedEntries.count
for entry in project.classifiedEntries {
let entryLines = lines[(entry.rangeInFile.start.line - 1)...(entry.rangeInFile.end.line - 1)]
// Find out original indent
let indentRegex = try! NSRegularExpression(pattern: "^\\s+", options: [])
let indent: String
let secondLine = String(Array(entryLines)[1])
if let match = indentRegex.firstMatch(in: secondLine, options: [], range: NSRange(location: 0, length: secondLine.utf16.count)) {
indent = String(secondLine[Range(match.range(at: 0), in: secondLine)!])
} else {
indent = ""
}
// Generate and insert "classes" line
let classesString = indent + "classes = {\(entry.classesString)}"
if let entryLinesIndex = entryLines.firstIndex(where: { $0.trimmingCharacters(in: .whitespaces).lowercased().hasPrefix("classes") }) {
let index = entry.rangeInFile.start.line - 1 + entryLinesIndex
lines[index] = classesString + (entryLines[index].hasSuffix(",") ? "," : "")
} else {
let index = entry.rangeInFile.start.line - 1 + entryLines.count - 2
lines[index] += (entryLines[index].hasSuffix(",") ? "" : ",") + "\n" + classesString
}
entry.classesChanged = false
}
let managedObjectContext = PersistenceController.shared.container.viewContext
// Delete discarded entries
let discardedEntries = project.discardedEntries.count
project.discardedEntries.map(\.rangeInFile).sorted { $0 > $1 }.forEach { lines.remove(atOffsets: IndexSet(integersIn: ($0.start.line - 1)...($0.end.line - 1))) }
project.discardedEntries.forEach { managedObjectContext.delete($0) }
// Write changes back to file
try lines.joined(separator: "\n").write(to: bibFileURL, atomically: true, encoding: .utf8)
// Update ranges
let entries = project.entries.reduce(into: [String: Entry]()) { $0[$1.citationKey] = $1 }
for publication in parsePublications(project: project) {
if let entry = entries[publication.citationKey] {
entry.rangeInFile = publication.rangeInFile
}
}
managedObjectContext.saveAndLogError()
// Report number of changes
return (discardedEntries, classifiedEntries)
}
/// Creates a project's contents: entries and classes.
@discardableResult private static func createContents(for project: Project, managedObjectContext: NSManagedObjectContext) -> [Entry] {
let nodes = parseTaxonomy(project: project) ?? []
let classes = createTaxonomyClasses(project: project, nodes: nodes, managedObjectContext: managedObjectContext)
let publications = parsePublications(project: project)
let entries = createEntries(project: project, publications: publications, managedObjectContext: managedObjectContext)
assign(entries: entries, to: classes)
managedObjectContext.saveAndLogError()
UserDefaults.standard.set(project.objectID.uriRepresentation(), forKey: .activeProject)
return entries.map(\.0)
}
/// Parse the project's .taxonomy file.
private static func parseTaxonomy(project: Project) -> [TaxonomyParserNode]? {
guard let url = FileManager.default.contentsOfDirectory(at: project.url, matching: { $1.hasSuffix(".taxonomy") }).first else { return nil }
do {
let fileContents = try String(contentsOf: url)
return TaxonomyParser.parse(fileContents)
} catch {
print("Error reading or parsing bib file: \(error)")
return nil
}
}
/// Creates entities from parsed taxonomy class nodes.
private static func createTaxonomyClasses(project: Project, nodes: [TaxonomyParserNode], managedObjectContext: NSManagedObjectContext) -> [String: TaxonomyClass] {
var classes = [String: TaxonomyClass]()
func createTaxonomyClasses(parent: TaxonomyClass?, children: [TaxonomyParserNode]) {
for node in children {
let taxonomyClass = TaxonomyClass.newEntity(name: node.name, project: project, parent: parent, in: managedObjectContext)
classes[node.path] = taxonomyClass
createTaxonomyClasses(parent: taxonomyClass, children: node.children)
}
}
createTaxonomyClasses(parent: nil, children: nodes)
return classes
}
/// Parse the project's .bib file.
private static func parsePublications(project: Project) -> [Publication] {
let urls = FileManager.default.contentsOfDirectory(at: project.url) { $1.hasSuffix(".bib") }
return urls.reduce([Publication]()) {
do {
let fileContents = try String(contentsOf: $1).replacingOccurrences(of: "\r\n", with: "\n")
return $0 + (try SwiftyBibtex.parse(fileContents).publications)
} catch {
print("Error reading or parsing bib file: \(error)")
return $0
}
}
}
/// Transforms SwiftyBibtex Publiations into Entry entities.
private static func createEntries(project: Project, publications: [Publication], managedObjectContext: NSManagedObjectContext) -> [(Entry, Set<String>)] {
return publications.map {
return (Entry.newEntity(publication: $0, decision: $0.classes.isEmpty ? .outstanding : .keep, project: project, in: managedObjectContext), $0.classes)
}
}
/// Assigns entries to their respective classes.
private static func assign(entries: [(Entry, Set<String>)], to classes: [String: TaxonomyClass]) {
for (entry, assignedClasses) in entries {
for assignedClass in assignedClasses {
if let taxonomyClass = classes[assignedClass] {
entry.classes.insert(taxonomyClass)
}
}
}
}
}
|
a880ae24bf379d794196115e9a761254
| 50.800905 | 247 | 0.644741 | false | false | false | false |
ahmad-atef/AutoScout24_Tech_Challenge
|
refs/heads/master
|
AutoScout24 Tech_Challenge/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// AutoScout24 Tech_Challenge
//
// Created by Ahmad Atef on 5/9/17.
// Copyright © 2017 Ahmad Atef. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
InternetChecker.shared.checkForInternet { (result) in
if result != .REACHABLEVIAWIFI{
UIDecorator.shared.showMessage(title: "Warning",body: result.rawValue,alertType: .warning)
}
}
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: "AutoScout24_Tech_Challenge")
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)")
}
}
}
}
|
7ed5af33687e06d6fcd77cbc55c45ea5
| 47.505051 | 285 | 0.68055 | false | false | false | false |
ypopovych/Future
|
refs/heads/master
|
Package.swift
|
apache-2.0
|
1
|
//===--- Package.swift ----------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 PackageDescription
let package = Package(
name: "Future",
dependencies: [
.Package(url: "https://github.com/reactive-swift/Event.git", majorVersion: 0, minor: 1)
]
)
|
4d2b6cebba4565138fdaa4553b8a0f92
| 38.5 | 95 | 0.621308 | false | false | false | false |
dcoufal/DECResizeFontToFitRect
|
refs/heads/master
|
Pod/Classes/ResizeFontToFitRect.swift
|
mit
|
1
|
//
// Copyright (c) David Coufal 2015
// davidcoufal.com
// Released for general use under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
/**
This function takes a font and returns a new font (if required) that can be used to fit the given String into the given CGRect.
Only the pointSize of the font is modified.
@param font: The font to start with.
@param toRect: The CGRect to fit the string into using the font
@param forString: The string to be fitted.
@param withMaxFontSize: The maximum pointSize to be used.
@param withMinFontSize: The minimum pointSize to be used.
@param withFontSizeIncrement: The amount to increment the font pointSize by during calculations. Smaller values give a more accurate result, but take longer to calculate.
@param andStringDrawingOptions: The `NSStringDrawingOptions` to be used in the call to String.boundingRect to calculate fits.
@return A new UIFont (if needed, if no calculations can be performed the same font is returned) that will fit the String to the CGRect
*/
public func resize(
font: UIFont,
toRect rect: CGRect,
forString text: String?,
withMaxFontSize maxFontSizeIn: CGFloat,
withMinFontSize minFontSize: CGFloat,
withFontSizeIncrement fontSizeIncrement: CGFloat = 1.0,
andStringDrawingOptions stringDrawingOptions: NSStringDrawingOptions = .usesLineFragmentOrigin ) -> UIFont
{
guard maxFontSizeIn > minFontSize else {
assertionFailure("maxFontSize should be larger than minFontSize")
return font
}
guard let text = text else {
return font
}
var maxFontSize = maxFontSizeIn
let words = text.components(separatedBy: CharacterSet.whitespacesAndNewlines)
// calculate max font size based on each word
for word in words {
maxFontSize = getMaxFontSize(forWord: word,
forWidth: rect.width,
usingFont: font,
withMaxFontSize: maxFontSize,
withMinFontSize: minFontSize,
withFontSizeIncrement: fontSizeIncrement)
}
// calculate what the font size should be based on entire phrase
var tempfont = font.withSize(maxFontSize)
var currentFontSize = maxFontSize
while (currentFontSize > minFontSize) {
tempfont = font.withSize(currentFontSize)
let constraintSize = CGSize(width: rect.size.width, height: CGFloat.greatestFiniteMagnitude)
let labelSize = text.boundingRect(
with: constraintSize,
options: stringDrawingOptions,
attributes: [ .font : tempfont ],
context: nil)
if (labelSize.height <= rect.height) {
break
}
currentFontSize -= fontSizeIncrement
}
return tempfont;
}
internal func getMaxFontSize(
forWord word: String,
forWidth width: CGFloat,
usingFont font: UIFont,
withMaxFontSize maxFontSize: CGFloat,
withMinFontSize minFontSize: CGFloat,
withFontSizeIncrement fontSizeIncrement: CGFloat) -> CGFloat
{
var currentFontSize: CGFloat = maxFontSize
while (currentFontSize > minFontSize) {
let tempfont = font.withSize(currentFontSize)
let labelSize = word.size(withAttributes: [.font: tempfont])
if (labelSize.width < width) {
return currentFontSize
}
currentFontSize -= fontSizeIncrement
}
return minFontSize
}
|
47af36a5214cf7d3f6ed901bb1ac8527
| 35.742268 | 171 | 0.669753 | false | false | false | false |
IvanVorobei/RateApp
|
refs/heads/master
|
SPRateApp - project/SPRateApp/sparrow/ui/controllers/SPDialogSwipeController.swift
|
mit
|
1
|
// The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPDialogSwipeController<DialogView: UIView, BottomView: UIView>: SPStatusBarManagerViewController {
//MARK: - views
let dialogView: DialogView
let backgroundView: SPGradeWithBlurView = SPGradeWithBlurView()
let bottomView: BottomView = BottomView()
internal var contentView: UIView = UIView()
//MARK: - UI
var dialogShadowYtranslationFactor: CGFloat = 0.035
var dialogShadowBlurRadiusFactor: CGFloat = 0.026
var dialogShadowOpacity: CGFloat = 0.36
private var dialogShadowWidthRelativeFactor: CGFloat = 0.8
//MARK: - layout
//dialog view
var dialogViewMaxWidth: CGFloat = 300
var dialogViewMaxHeight: CGFloat = 300
var dialogViewWidthRelativeFactor: CGFloat = 0.8
var dialogViewHeightRelativeFactor: CGFloat = 0.8
//width divided height
var dialogViewSidesRelativeFactor: CGFloat = 1
var dialogViewPortraitYtranslationFactor: CGFloat = 0.96
var dialogViewLandscapeYtranslationFactor: CGFloat = 1
var dialogViewSize: CGSize {
var widthArea = self.view.frame.width * self.dialogViewWidthRelativeFactor
var heightArea = self.view.frame.height * self.dialogViewHeightRelativeFactor
var isPortraitLayout: Bool = UIScreen.main.bounds.width < UIScreen.main.bounds.height
if self.view.bounds != UIScreen.main.bounds {
isPortraitLayout = self.view.frame.width < self.view.frame.height
}
if isPortraitLayout {
widthArea = self.view.frame.width * self.dialogViewWidthRelativeFactor
heightArea = self.view.frame.height * self.dialogViewHeightRelativeFactor
} else {
widthArea = self.view.frame.height * self.dialogViewWidthRelativeFactor
heightArea = self.view.frame.width * self.dialogViewHeightRelativeFactor
}
widthArea.setIfMore(when: self.dialogViewMaxWidth)
heightArea.setIfMore(when: self.dialogViewMaxHeight)
var prepareWidth = widthArea
var prepareHeight = widthArea / self.dialogViewSidesRelativeFactor
if prepareHeight > heightArea {
prepareHeight = heightArea
prepareWidth = heightArea * self.dialogViewSidesRelativeFactor
}
if isPortraitLayout {
return CGSize.init(width: prepareWidth, height: prepareHeight)
} else {
return CGSize.init(width: prepareHeight, height: prepareWidth)
}
}
var dialogCenteringPoint: CGPoint {
if SPDeviceOrientation.isPortraitOrienation() {
return CGPoint(x: self.view.center.x, y: self.view.center.y * dialogViewPortraitYtranslationFactor)
} else {
return CGPoint(x: self.view.center.x, y: self.view.center.y * dialogViewLandscapeYtranslationFactor)
}
}
//bottom view
var bottomViewMaxWidth: CGFloat = 140
var bottomViewMaxHeight: CGFloat = 75
var bottomViewWidthRelativeFactor: CGFloat = 0.6
//width divided height
var bottomViewSidesRelativeFactor: CGFloat = 1.5
var bottomViewMinToDialogSpace: CGFloat = 20
var bottomViewYTranslationFactor: CGFloat = 0.1
var bottomViewSize: CGSize {
var prepareWidth: CGFloat = self.contentView.frame.width * self.bottomViewWidthRelativeFactor
if prepareWidth > bottomViewMaxWidth {
prepareWidth = bottomViewMaxWidth
}
var prepareHeight: CGFloat = prepareWidth / self.bottomViewSidesRelativeFactor
if prepareHeight > self.bottomViewMaxHeight {
prepareHeight = self.bottomViewMaxHeight
prepareWidth = self.bottomViewMaxHeight * self.bottomViewSidesRelativeFactor
}
return CGSize.init(width: prepareWidth, height: prepareHeight)
}
var bottomViewCenter: CGPoint {
let dialogHeigth = self.dialogViewSize.height
let dialogCenter = self.dialogCenteringPoint
let bottomHeight = self.bottomViewSize.height
let dialogBottomSideYpoint = dialogCenter.y + (dialogHeigth / 2)
let spaceBetweenDialogAndBottomSide = self.view.frame.height - dialogBottomSideYpoint
var prepareSpace = spaceBetweenDialogAndBottomSide * bottomViewYTranslationFactor
let minSpace = self.bottomViewMinToDialogSpace
if prepareSpace < minSpace {
prepareSpace = minSpace
}
return CGPoint(x: self.view.center.x, y: dialogBottomSideYpoint + prepareSpace + bottomHeight / 2)
}
//MARK: - animation
var spring: CGFloat = 0.5
var velocity: CGFloat = 0.85
//MARK: - delegates
weak var delegate: SPDialogSwipeControllerDelegate?
private var isShowBottomView: Bool {
return (bottomView.frame.origin.y + bottomView.frame.height) < (self.view.frame.height)
}
//MARK: - init
init(dialogView: DialogView) {
self.dialogView = dialogView
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
self.dialogView = DialogView()
super.init(coder: aDecoder)
}
//MARK: - public func
func present(on viewController: UIViewController) {
self.animator.removeAllBehaviors()
self.bottomView.alpha = 0
self.contentView.alpha = 0
self.contentView.transform = .identity
self.modalPresentationStyle = .overCurrentContext
viewController.present(self, animated: false, completion: {
finished in
self.updateLayoutAndSizes()
self.updateContentViewShadow(yTranslationFactor: self.dialogShadowYtranslationFactor, blurRadiusFactor: self.dialogShadowBlurRadiusFactor, opacity: self.dialogShadowOpacity)
self.contentView.center = CGPoint.init(
x: self.view.center.x,
y: self.view.center.y * 1.2
)
SPHideWindow.dialog.presentWith(view: self.backgroundView)
/*SPAnimation.animate(0.6, animations: {
self.updateBackground()
})*/
delay(0.21, closure: {
self.snapBehavior = UISnapBehavior(item: self.contentView, snapTo: self.dialogCenteringPoint)
self.animator.addBehavior(self.snapBehavior)
SPAnimation.animate(0.3, animations: {
self.contentView.alpha = 1
delay(0.2, closure: {
if self.delegate?.isEnableHideDialogController ?? true {
if self.isShowBottomView {
SPAnimation.animate(0.3, animations: {
self.bottomView.alpha = 1
})
}
}
})
})
})
})
}
func hide(withDialog: Bool) {
if withDialog {
SPAnimationSpring.animate(
0.4,
animations: {
self.animator.removeAllBehaviors()
self.contentView.transform = CGAffineTransform.init(scaleX: 0.9, y: 0.9)
self.contentView.alpha = 0
},
options: [.curveEaseIn, .beginFromCurrentState],
withComplection: {})
}
SPAnimation.animate(0.3, animations: {
self.bottomView.alpha = 0
})
SPAnimation.animate(SPHideWindow.dialog.duration, animations: {
self.backgroundView.setGradeAlpha(0, blurRaius: 0)
}, withComplection: {
finished in
self.dismiss(animated: false, completion: {
finished in
self.animator.removeAllBehaviors()
self.contentView.transform = .identity
self.delegate?.didHideDialogController()
})
})
}
//MARK: - ovveride func
override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
animator.removeAllBehaviors()
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
self.contentView.transform = .identity
self.updateLayoutAndSizes()
if self.isShowBottomView {
self.bottomView.alpha = 1
} else {
self.bottomView.alpha = 0
}
SPAnimationSpring.animate(0.3, animations: {
self.actionBeforeRotation()
}, spring: self.spring, velocity: self.velocity, options: UIViewAnimationOptions.curveEaseIn)
}, completion: {
finished in
SPAnimationSpring.animate(0.35, animations: {
self.actionAfterRotation()
}, spring: self.spring, velocity: self.velocity, options: UIViewAnimationOptions.curveEaseOut)
self.updateLayoutAndSizes()
})
}
override public func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.backgroundView)
self.view.addSubview(self.bottomView)
self.view.addSubview(self.contentView)
SPConstraintsAssistent.setEqualSizeConstraint(backgroundView, superVuew: self.view)
self.contentView.addSubview(self.dialogView)
self.backgroundView.setGradeAlpha(0, blurRaius: 0)
self.contentView.backgroundColor = UIColor.clear
self.contentView.alpha = 0
self.contentView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0.5)
self.dialogView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0.5)
self.bottomView.alpha = 0
self.bottomView.backgroundColor = UIColor.clear
self.contentView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0.5)
let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(self.handleGesture(sender:)))
panGesture.maximumNumberOfTouches = 1
self.contentView.addGestureRecognizer(panGesture)
animator = UIDynamicAnimator(referenceView: self.view)
}
//MARK: - inner func
internal func updateLayoutAndSizes() {
self.contentView.frame = CGRect.init(origin: CGPoint.zero, size: self.dialogViewSize)
self.contentView.center = self.dialogCenteringPoint
self.dialogView.frame = self.contentView.bounds
self.contentView.layer.cornerRadius = self.dialogView.layer.cornerRadius
self.bottomView.bounds = CGRect.init(origin: CGPoint.zero, size: self.bottomViewSize)
self.bottomView.center = self.bottomViewCenter
}
internal func actionBeforeRotation() {
self.contentView.transform = CGAffineTransform.init(scaleX: 1.1, y: 1.1)
self.updateContentViewShadow(yTranslationFactor: 0, blurRadiusFactor: 0, opacity: 0)
}
internal func actionAfterRotation() {
self.contentView.transform = CGAffineTransform.identity
self.updateContentViewShadow(yTranslationFactor: self.dialogShadowYtranslationFactor, blurRadiusFactor: self.dialogShadowBlurRadiusFactor, opacity: self.dialogShadowOpacity)
}
private func updateContentViewShadow(yTranslationFactor: CGFloat, blurRadiusFactor: CGFloat, opacity: CGFloat) {
self.contentView.setShadow(
xTranslationFactor: 0,
yTranslationFactor: yTranslationFactor,
widthRelativeFactor: self.dialogShadowWidthRelativeFactor,
heightRelativeFactor: 1,
blurRadiusFactor: blurRadiusFactor,
shadowOpacity: opacity
)
}
/*private func updateBackground() {
let blurRadius = min(self.view.frame.width, self.view.frame.width) * self.backgroundBlurFactor
self.backgroundView.setGradeAlpha(self.backgroundGrade, blurRaius: blurRadius)
}*/
//MARK: - animator
var animator = UIDynamicAnimator()
var attachmentBehavior : UIAttachmentBehavior!
var gravityBehaviour : UIGravityBehavior!
var snapBehavior : UISnapBehavior!
//MARK: - handle gesture
func handleGesture(sender: AnyObject) {
let myView = self.contentView
let location = sender.location(in: view)
let boxLocation = sender.location(in: myView)
if sender.state == UIGestureRecognizerState.began {
animator.removeAllBehaviors()
let centerOffset = UIOffsetMake(boxLocation.x - myView.bounds.midX, boxLocation.y - myView.bounds.midY);
attachmentBehavior = UIAttachmentBehavior(item: myView, offsetFromCenter: centerOffset, attachedToAnchor: location)
attachmentBehavior.frequency = 0
animator.addBehavior(attachmentBehavior)
}
else if sender.state == UIGestureRecognizerState.changed {
self.attachmentBehavior.anchorPoint = location
}
else if sender.state == UIGestureRecognizerState.ended {
animator.removeBehavior(attachmentBehavior)
snapBehavior = UISnapBehavior(item: myView, snapTo: self.dialogCenteringPoint)
animator.addBehavior(snapBehavior)
let translation = sender.translation(in: view)
if translation.y > 100 {
if delegate?.isEnableHideDialogController ?? true {
animator.removeAllBehaviors()
gravityBehaviour = UIGravityBehavior(items: [contentView])
gravityBehaviour.gravityDirection = CGVector.init(dx: 0, dy: 10)
animator.addBehavior(gravityBehaviour)
self.hide(withDialog: false)
}
}
}
}
}
protocol SPDialogSwipeControllerDelegate: class {
var isEnableHideDialogController: Bool {get}
func didHideDialogController()
}
|
b57508a7ad431dfb79a8907bd23a8bf0
| 43.5 | 185 | 0.657972 | false | false | false | false |
cubixlabs/GIST-Framework
|
refs/heads/master
|
GISTFramework/Classes/Controls/CustomUIImageView.swift
|
agpl-3.0
|
1
|
//
// CustomUIImageView.swift
// GISTFramework
//
// Created by Shoaib Abdul on 23/08/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
///THIS CLASS WAS TO REPLACE CustomImageView(inharited from UIView) but there were some unknown implementations of UIImageView (of UIKit) that are causing the bugs so keeping this class private to use in future after some fixes
private class CustomUIImageView: BaseUIImageView {
//MARK: - Properties
@IBInspectable open var respectContentRTL:Bool = GIST_CONFIG.respectRTL {
didSet {
self.imageView!.frame = self.imageViewFrame;
}
} //P.E.
private var _imageView:UIImageView?;
/// Image View Lazy instance for drawing custom image.
var imageView:UIImageView? {
get {
if (_imageView == nil) {
_imageView = UIImageView();
_imageView!.backgroundColor = UIColor.clear;
self.addSubview(_imageView!);
//??self.clipsToBounds = true;
self.sendSubviewToBack(_imageView!);
}
return _imageView!;
}
set {
_imageView = newValue;
}
} //P.E.
/**
Calculated frame of button image view.
It uses UIButton native UIView.ContentMode to calculate frames.
*/
private var imageViewFrame:CGRect {
get {
var rFrame:CGRect = CGRect();
if (self.imageView!.image != nil) {
let imgSize:CGSize = self.imageView!.image!.size;
let imgRatio:CGFloat = (imgSize.height / imgSize.width);
if ((self.contentMode != UIView.ContentMode.scaleAspectFit) && (self.contentMode != UIView.ContentMode.scaleAspectFill) && (self.contentMode != UIView.ContentMode.scaleToFill)) {
rFrame.size.width = GISTUtility.convertToRatio(imgSize.width);
rFrame.size.height = imgRatio * rFrame.width;
}
var cContentMode:UIView.ContentMode = self.contentMode;
//Respect for Right to left Handling
if ((self.respectContentRTL || self.respectRTL) && GISTUtility.isRTL) {
switch cContentMode {
case .left:
cContentMode = .right;
break;
case .right:
cContentMode = .left;
break;
case .topLeft:
cContentMode = .topRight;
break;
case .topRight:
cContentMode = .topLeft;
break;
case .bottomLeft:
cContentMode = .bottomRight;
break;
case .bottomRight:
cContentMode = .bottomLeft;
break;
default:
break;
}
}
switch (self.contentMode) {
case .top:
rFrame.origin.x = (self.frame.size.width - rFrame.size.width)/2.0;
rFrame.origin.y = 0;
break;
case .topLeft:
rFrame.origin.x = 0;
rFrame.origin.y = 0;
break;
case .topRight:
rFrame.origin.x = (self.frame.size.width - rFrame.size.width);
rFrame.origin.y = 0;
break;
case .bottom:
rFrame.origin.x = (self.frame.size.width - rFrame.size.width)/2.0;
rFrame.origin.y = (self.frame.size.height - rFrame.size.height);
break;
case .bottomLeft:
rFrame.origin.x = 0;
rFrame.origin.y = (self.frame.size.height - rFrame.size.height);
break;
case .bottomRight:
rFrame.origin.x = (self.frame.size.width - rFrame.size.width);
rFrame.origin.y = (self.frame.size.height - rFrame.size.height);
break;
case .left:
rFrame.origin.x = 0;
rFrame.origin.y = (self.frame.size.height - rFrame.size.height)/2.0;
break;
case .right:
rFrame.origin.x = (self.frame.size.width - rFrame.size.width);
rFrame.origin.y = (self.frame.size.height - rFrame.size.height)/2.0;
break;
case .scaleToFill:
rFrame.origin = CGPoint.zero;
rFrame.size = self.frame.size;
break;
case .scaleAspectFit:
if (imgSize.width > imgSize.height) {
rFrame.size.width = self.frame.size.width;
rFrame.size.height = imgRatio * rFrame.width;
} else {
rFrame.size.height = self.frame.size.height;
rFrame.size.width = rFrame.height / imgRatio;
}
rFrame.origin = CGPoint(x: (self.frame.size.width - rFrame.size.width)/2.0,y: (self.frame.size.height - rFrame.size.height)/2.0);
break;
case .scaleAspectFill:
if (imgSize.width < imgSize.height) {
rFrame.size.width = self.frame.size.width;
rFrame.size.height = imgRatio * rFrame.size.width;
} else {
rFrame.size.height = self.frame.size.height;
rFrame.size.width = rFrame.size.height / imgRatio;
}
rFrame.origin = CGPoint(x: (self.frame.size.width - rFrame.size.width)/2.0,y: (self.frame.size.height - rFrame.size.height)/2.0);
break;
default:
rFrame.origin = CGPoint(x: (self.frame.size.width - rFrame.size.width)/2.0,y: (self.frame.size.height - rFrame.size.height)/2.0);
break;
}
} else {
rFrame.size = self.frame.size;
rFrame.origin = CGPoint(x: (self.frame.size.width - rFrame.size.width)/2.0,y: (self.frame.size.height - rFrame.size.height)/2.0);
}
return rFrame;
}
} //P.E.
/// Overriden propert to get content mode changes.
override var contentMode:UIView.ContentMode {
get {
return super.contentMode;
}
set {
super.contentMode = newValue;
}
} //P.E.
/**
Overriden property for image.
It overrides the native behavior of UIImageView and sets image in the custom image view.
*/
override var image: UIImage? {
get {
return self.imageView!.image;
}
set {
if (self.respectRTL && GISTUtility.isRTL) {
self.imageView!.image = newValue?.mirrored();
} else {
self.imageView!.image = newValue;
}
self.imageView!.frame = self.imageViewFrame;
}
} //F.E.
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
override open func awakeFromNib() {
super.awakeFromNib();
if let cImg:UIImage = super.image {
//Cleaning Up
super.image = UIImage();
self.image = UIImage(cgImage:cImg.cgImage!, scale: cImg.scale, orientation:cImg.imageOrientation);
}
} //F.E.
/// Overridden methed to update layout.
override func layoutSubviews() {
super.layoutSubviews();
self.imageView!.frame = self.imageViewFrame;
} //F.E
} //CLS END
|
ba7f1fab3662e75c0461dc087f91e1f5
| 36.275109 | 227 | 0.464035 | false | false | false | false |
wangkai678/WKDouYuZB
|
refs/heads/master
|
WKDouYuZB/WKDouYuZB/Classes/Home/Controller/FunnyViewController.swift
|
mit
|
1
|
//
// FunnyViewController.swift
// WKDouYuZB
//
// Created by wangkai on 2017/5/31.
// Copyright © 2017年 wk. All rights reserved.
//
import UIKit
private let kTopMargin : CGFloat = 8
class FunnyViewController: BaseAnchorViewController {
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension FunnyViewController{
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsetsMake(kTopMargin, 0, 0, 0)
}
}
extension FunnyViewController{
override func loadData() {
baseVM = funnyVM
funnyVM.loadFunnyData {
self.collectionView.reloadData()
self.loadDataFinished()
}
}
}
|
4f8348cfc8afe8298e42bcf61c73133d
| 21.560976 | 87 | 0.669189 | false | false | false | false |
lanjing99/iOSByTutorials
|
refs/heads/master
|
iOS 8 by tutorials/Chapter 23 - Handoff/ShopSnap-Starter/ShopSnap/SplitViewController.swift
|
mit
|
1
|
/*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class SplitViewController: UISplitViewController, UISplitViewControllerDelegate {
// MARK: View Life Cycle
override func viewDidLoad() {
delegate = self
preferredDisplayMode = .AllVisible
super.viewDidLoad()
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
// Regular layout: it is a master-detail where master is on the left
// and detail is on the right.
if traitCollection.horizontalSizeClass == .Regular {
let navController = viewControllers.first as! UINavigationController
let listViewController = navController.viewControllers.first as! ListViewController
let detailViewController = viewControllers.last as! DetailViewController
detailViewController.delegate = listViewController
}
super.traitCollectionDidChange(previousTraitCollection)
}
// MARK: UISplitViewControllerDelegate
func splitViewController(splitViewController: UISplitViewController!, collapseSecondaryViewController secondaryViewController: UIViewController!, ontoPrimaryViewController primaryViewController: UIViewController!) -> Bool {
// If the secondary view controller is Detail View Controller...
if secondaryViewController.isKindOfClass(DetailViewController.self) {
// If Detail View Controller is editing something, default behavior is OK, so return NO.
let detailViewController = secondaryViewController as! DetailViewController
if detailViewController.item?.isEmpty == false {
detailViewController.startEditing()
return false
}
}
// Otherwise we handle the collapse.
if primaryViewController.isKindOfClass(UINavigationController.self) {
// If there is modally presented view controller, pop.
if primaryViewController.presentedViewController != nil {
(primaryViewController as! UINavigationController).popToRootViewControllerAnimated(true)
}
}
// Return YES because we handled the collapse.
return true;
}
// MARK: Helper
func viewControllerForViewing () -> UIViewController {
let navController = viewControllers.first as! UINavigationController
let listViewController = navController.viewControllers.first as! ListViewController
// If in Compact layout, cancel everything, go to the root of the navigation stack.
if traitCollection.horizontalSizeClass == .Compact {
navController.popToViewController(listViewController, animated: true)
}
return listViewController
}
func viewControllerForEditing () -> UIViewController {
if traitCollection.horizontalSizeClass == .Regular {
// If it is the Regular layout, find DetailViewController.
let detailViewController = viewControllers.last as! DetailViewController
return detailViewController
} else {
let navController = viewControllers.first as! UINavigationController
// Otherwise, is DetailViewController already active?
var lastViewController: AnyObject? = navController.viewControllers.last
if lastViewController is DetailViewController {
// Pass it on.
let detailViewController = lastViewController as! DetailViewController
return detailViewController
} else {
// Make DetailViewController active via ListViewController.
let listViewController = navController.viewControllers.first as! ListViewController
listViewController.performSegueWithIdentifier(AddItemSegueIdentifier, sender: nil)
let detailViewController = navController.viewControllers.last as! DetailViewController
return detailViewController
}
}
}
override func restoreUserActivityState(activity: NSUserActivity) {
let activityType = activity.activityType
if activityType == ActivityTypeView {
viewControllerForViewing().restoreUserActivityState(activity)
}else{
viewControllerForEditing().restoreUserActivityState(activity)
}
}
}
|
83014aa84067c190ccc802aa5a229aea
| 35.405594 | 225 | 0.739531 | false | false | false | false |
jmgc/swift
|
refs/heads/master
|
test/SILOptimizer/sil_combine_protocol_conf.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend %s -O -wmo -emit-sil -Xllvm -sil-disable-pass=DeadFunctionElimination | %FileCheck %s
// case 1: class protocol -- should optimize
internal protocol SomeProtocol : class {
func foo(x:SomeProtocol) -> Int
func foo_internal() -> Int
}
internal class SomeClass: SomeProtocol {
func foo_internal() ->Int {
return 10
}
func foo(x:SomeProtocol) -> Int {
return x.foo_internal()
}
}
// case 2: non-class protocol -- should optimize
internal protocol SomeNonClassProtocol {
func bar(x:SomeNonClassProtocol) -> Int
func bar_internal() -> Int
}
internal class SomeNonClass: SomeNonClassProtocol {
func bar_internal() -> Int {
return 20
}
func bar(x:SomeNonClassProtocol) -> Int {
return x.bar_internal()
}
}
// case 3: class conforming to protocol has a derived class -- should not optimize
internal protocol DerivedProtocol {
func foo() -> Int
}
internal class SomeDerivedClass: DerivedProtocol {
func foo() -> Int {
return 20
}
}
internal class SomeDerivedClassDerived: SomeDerivedClass {
}
// case 3: public protocol -- should not optimize
public protocol PublicProtocol {
func foo() -> Int
}
internal class SomePublicClass: PublicProtocol {
func foo() -> Int {
return 20
}
}
// case 4: Chain of protocols P1->P2->C -- optimize
internal protocol MultiProtocolChain {
func foo() -> Int
}
internal protocol RefinedMultiProtocolChain : MultiProtocolChain {
func bar() -> Int
}
internal class SomeMultiClass: RefinedMultiProtocolChain {
func foo() -> Int {
return 20
}
func bar() -> Int {
return 30
}
}
// case 5: Generic conforming type -- should not optimize
internal protocol GenericProtocol {
func foo() -> Int
}
internal class GenericClass<T> : GenericProtocol {
var items = [T]()
func foo() -> Int {
return items.count
}
}
// case 6: two classes conforming to protocol
internal protocol MultipleConformanceProtocol {
func foo() -> Int
}
internal class Klass1: MultipleConformanceProtocol {
func foo() -> Int {
return 20
}
}
internal class Klass2: MultipleConformanceProtocol {
func foo() -> Int {
return 30
}
}
internal class Other {
let x:SomeProtocol
let y:SomeNonClassProtocol
let z:DerivedProtocol
let p:PublicProtocol
let q:MultiProtocolChain
let r:GenericProtocol
let s:MultipleConformanceProtocol
init(x:SomeProtocol, y:SomeNonClassProtocol, z:DerivedProtocol, p:PublicProtocol, q:MultiProtocolChain, r:GenericProtocol, s:MultipleConformanceProtocol) {
self.x = x;
self.y = y;
self.z = z;
self.p = p;
self.q = q;
self.r = r;
self.s = s;
}
// CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF : $@convention(method) (@guaranteed Other) -> Int {
// CHECK: bb0
// CHECK: debug_value
// CHECK: integer_literal
// CHECK: [[R1:%.*]] = ref_element_addr %0 : $Other, #Other.z
// CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*DerivedProtocol to $*@opened("{{.*}}") DerivedProtocol
// CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") DerivedProtocol, #DerivedProtocol.foo : <Self where Self : DerivedProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") DerivedProtocol : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W1]]<@opened("{{.*}}") DerivedProtocol>([[O1]]) : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R2:%.*]] = ref_element_addr %0 : $Other, #Other.p
// CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*PublicProtocol to $*@opened("{{.*}}") PublicProtocol
// CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") PublicProtocol, #PublicProtocol.foo : <Self where Self : PublicProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") PublicProtocol : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W2]]<@opened("{{.*}}") PublicProtocol>([[O2]]) : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R3:%.*]] = ref_element_addr %0 : $Other, #Other.r
// CHECK: [[O3:%.*]] = open_existential_addr immutable_access [[R3]] : $*GenericProtocol to $*@opened("{{.*}}") GenericProtocol
// CHECK: [[W3:%.*]] = witness_method $@opened("{{.*}}") GenericProtocol, #GenericProtocol.foo : <Self where Self : GenericProtocol> (Self) -> () -> Int, [[O3]] : $*@opened("{{.*}}") GenericProtocol : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W3]]<@opened("{{.*}}") GenericProtocol>([[O3]]) : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R4:%.*]] = ref_element_addr %0 : $Other, #Other.s
// CHECK: [[O4:%.*]] = open_existential_addr immutable_access %36 : $*MultipleConformanceProtocol to $*@opened("{{.*}}") MultipleConformanceProtocol
// CHECK: [[W4:%.*]] = witness_method $@opened("{{.*}}") MultipleConformanceProtocol, #MultipleConformanceProtocol.foo : <Self where Self : MultipleConformanceProtocol> (Self) -> () -> Int, %37 : $*@opened("{{.*}}") MultipleConformanceProtocol : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W4]]<@opened("{{.*}}") MultipleConformanceProtocol>(%37) : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: struct
// CHECK: return
// CHECK: } // end sil function '$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF'
@inline(never) func doWorkClass () ->Int {
return self.x.foo(x:self.x) // optimize
+ self.y.bar(x:self.y) // optimize
+ self.z.foo() // do not optimize
+ self.p.foo() // do not optimize
+ self.q.foo() // optimize
+ self.r.foo() // do not optimize
+ self.s.foo() // do not optimize
}
}
// case 1: struct -- optimize
internal protocol PropProtocol {
var val: Int { get set }
}
internal struct PropClass: PropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
// case 2: generic struct -- do not optimize
internal protocol GenericPropProtocol {
var val: Int { get set }
}
internal struct GenericPropClass<T>: GenericPropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
// case 3: nested struct -- optimize
internal protocol NestedPropProtocol {
var val: Int { get }
}
struct Outer {
struct Inner : NestedPropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
}
// case 4: generic nested struct -- do not optimize
internal protocol GenericNestedPropProtocol {
var val: Int { get }
}
struct GenericOuter<T> {
struct GenericInner : GenericNestedPropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
}
internal class OtherClass {
var arg1: PropProtocol
var arg2: GenericPropProtocol
var arg3: NestedPropProtocol
var arg4: GenericNestedPropProtocol
init(arg1:PropProtocol, arg2:GenericPropProtocol, arg3: NestedPropProtocol, arg4: GenericNestedPropProtocol) {
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
self.arg4 = arg4
}
// CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF : $@convention(method) (@guaranteed OtherClass) -> Int {
// CHECK: bb0([[ARG:%.*]] :
// CHECK: debug_value
// CHECK: [[R1:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg1
// CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*PropProtocol to $*@opened("{{.*}}") PropProtocol
// CHECK: [[U1:%.*]] = unchecked_addr_cast [[O1]] : $*@opened("{{.*}}") PropProtocol to $*PropClass
// CHECK: [[S1:%.*]] = struct_element_addr [[U1]] : $*PropClass, #PropClass.val
// CHECK: [[S11:%.*]] = struct_element_addr [[S1]] : $*Int, #Int._value
// CHECK: load [[S11]]
// CHECK: [[R2:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg2
// CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*GenericPropProtocol to $*@opened("{{.*}}") GenericPropProtocol
// CHECK: [[T1:%.*]] = alloc_stack $@opened
// CHECK: copy_addr [[O2]] to [initialization] [[T1]]
// CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") GenericPropProtocol, #GenericPropProtocol.val!getter : <Self where Self : GenericPropProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") GenericPropProtocol : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W2]]<@opened("{{.*}}") GenericPropProtocol>([[T1]]) : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R4:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg3
// CHECK: [[O4:%.*]] = open_existential_addr immutable_access [[R4]] : $*NestedPropProtocol to $*@opened("{{.*}}") NestedPropProtocol
// CHECK: [[U4:%.*]] = unchecked_addr_cast [[O4]] : $*@opened("{{.*}}") NestedPropProtocol to $*Outer.Inner
// CHECK: [[S4:%.*]] = struct_element_addr [[U4]] : $*Outer.Inner, #Outer.Inner.val
// CHECK: [[S41:%.*]] = struct_element_addr [[S4]] : $*Int, #Int._value
// CHECK: load [[S41]]
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R5:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg4
// CHECK: [[O5:%.*]] = open_existential_addr immutable_access [[R5]] : $*GenericNestedPropProtocol to $*@opened("{{.*}}") GenericNestedPropProtocol
// CHECK: [[T2:%.*]] = alloc_stack $@opened
// CHECK: copy_addr [[O5]] to [initialization] [[T2]]
// CHECK: [[W5:%.*]] = witness_method $@opened("{{.*}}") GenericNestedPropProtocol, #GenericNestedPropProtocol.val!getter : <Self where Self : GenericNestedPropProtocol> (Self) -> () -> Int, [[O5:%.*]] : $*@opened("{{.*}}") GenericNestedPropProtocol : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W5]]<@opened("{{.*}}") GenericNestedPropProtocol>([[T2]]) : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: struct
// CHECK: return
// CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF'
@inline(never) func doWorkStruct () -> Int{
return self.arg1.val // optimize
+ self.arg2.val // do not optimize
+ self.arg3.val // optimize
+ self.arg4.val // do not optimize
}
}
// case 1: enum -- optimize
internal protocol AProtocol {
var val: Int { get }
mutating func getVal() -> Int
}
internal enum AnEnum : AProtocol {
case avalue
var val: Int {
switch self {
case .avalue:
return 10
}
}
mutating func getVal() -> Int { return self.val }
}
// case 2: generic enum -- do not optimize
internal protocol AGenericProtocol {
var val: Int { get }
mutating func getVal() -> Int
}
internal enum AGenericEnum<T> : AGenericProtocol {
case avalue
var val: Int {
switch self {
case .avalue:
return 10
}
}
mutating func getVal() -> Int {
return self.val
}
}
internal class OtherKlass {
var arg1: AProtocol
var arg2: AGenericProtocol
init(arg1:AProtocol, arg2:AGenericProtocol) {
self.arg1 = arg1
self.arg2 = arg2
}
// CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF : $@convention(method) (@guaranteed OtherKlass) -> Int {
// CHECK: bb0([[ARG:%.*]] :
// CHECK: debug_value
// CHECK: integer_literal
// CHECK: [[R1:%.*]] = ref_element_addr [[ARG]] : $OtherKlass, #OtherKlass.arg2
// CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*AGenericProtocol to $*@opened("{{.*}}") AGenericProtocol
// CHECK: [[T1:%.*]] = alloc_stack $@opened
// CHECK: copy_addr [[O1]] to [initialization] [[T1]]
// CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") AGenericProtocol, #AGenericProtocol.val!getter : <Self where Self : AGenericProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") AGenericProtocol : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W1]]<@opened("{{.*}}") AGenericProtocol>([[T1]]) : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: struct
// CHECK: return
// CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF'
@inline(never) func doWorkEnum() -> Int {
return self.arg1.val // optimize
+ self.arg2.val // do not optimize
}
}
// Don't assert on this following example.
public struct SomeValue {}
public protocol MyVariableProtocol : class {
}
extension MyVariableProtocol where Self: MyBaseClass {
@inline(never)
public var myVariable : SomeValue {
print(self)
return SomeValue()
}
}
public class MyBaseClass : MyVariableProtocol {}
fileprivate protocol NonClassProto {
var myVariable : SomeValue { get }
}
fileprivate class ConformerClass : MyBaseClass, NonClassProto {}
@inline(never)
private func repo(_ c: NonClassProto) {
let p : NonClassProto = c
print(p.myVariable)
}
public func entryPoint() {
let c = ConformerClass()
repo(c)
}
|
e28eb3b450d830238f3975a55072c1a0
| 36.548469 | 386 | 0.656091 | false | false | false | false |
xuech/OMS-WH
|
refs/heads/master
|
OMS-WH/Utilities/Libs/Reflect/Reflect.swift
|
mit
|
1
|
//
// Reflect.swift
// Reflect
//
// Created by 冯成林 on 15/8/19.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
class Reflect: NSObject, NSCoding{
lazy var mirror: Mirror = {Mirror(reflecting: self)}()
required override init(){}
public convenience required init?(coder aDecoder: NSCoder) {
self.init()
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
assert(type.check(), "[Charlin Feng]: Property '\(name)' type can not be a '\(type.realType.rawValue)' Type,Please use 'NSNumber' instead!")
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
self.setValue(aDecoder.decodeObject(forKey: name), forKeyPath: name)
}
}else{
self.setValue(aDecoder.decodeObject(forKey: name), forKeyPath: name)
}
}
}
public func encode(with aCoder: NSCoder){
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
aCoder.encode(value, forKey: name)
}
}else{
if type.isArray {
if type.isReflect {
aCoder.encode(value as? NSArray, forKey: name)
}else {
aCoder.encode(value, forKey: name)
}
}else {
var v = "\(value)".replacingOccurrencesOfString(target: "Optional(", withString: "").replacingOccurrencesOfString(target: ")", withString: "")
v = v.replacingOccurrencesOfString(target: "\"", withString: "")
aCoder.encode(v, forKey: name)
}
}
}
}
func parseOver(){}
}
|
41778badd3256624ea032bd9909127e4
| 26.912088 | 162 | 0.470866 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
算法学习/LeetCode/LeetCode/Backtrack/Permute.swift
|
mit
|
1
|
//
// Permute.swift
// LeetCode
//
// Created by jourhuang on 2021/3/29.
// Copyright © 2021 伯驹 黄. All rights reserved.
//
import Foundation
// https://leetcode.cn/problems/permutations/
class Permute {
var result: [[Int]] = []
func permute(_ nums: [Int]) -> [[Int]] {
var path: [Int] = []
var used = Array(repeating: false, count: nums.count)
backtrack(nums, &path, &used)
return result
}
func backtrack(_ nums: [Int], _ path: inout [Int], _ used: inout [Bool]) {
if path.count == nums.count {
result.append(path)
return
}
for (i, n) in nums.enumerated() {
if used[i] { continue }
used[i] = true
path.append(n)
backtrack(nums, &path, &used)
path.removeLast()
used[i] = false
}
}
}
|
e5ba874a9e2115dc16190560c332b510
| 21.384615 | 78 | 0.512027 | false | false | false | false |
ShenYj/Demos
|
refs/heads/master
|
自定义刷新控件/自定义刷新控件/JSRefresh.swift
|
mit
|
1
|
//
// JSRefresh.swift
// 自定义刷新控件
//
// Created by ShenYj on 16/7/1.
// Copyright © 2016年 ___ShenYJ___. All rights reserved.
//
import UIKit
// 自定义刷新控件的高度
let REFRESH_HEIGHT: CGFloat = 50
// 设置自定义刷新控件的背景色
let REFRESH_BACKGROUND_COLOR: UIColor = UIColor.orangeColor()
// 屏幕宽度
let SCREEN_WIDTH = UIScreen.mainScreen().bounds.width
// 自定义刷新控件文字状态字体大小
let STATUS_LABEL_FONT_SIZE: CGFloat = 15
// 自定义刷新控件文字字体颜色
let STATUS_LABEL_FONT_COLOR: UIColor = UIColor.purpleColor()
// 刷新控件的状态
enum JSRefreshType: Int {
case Normal = 0 // 正常
case Pulling = 1 // 下拉中
case Refreshing = 2 // 刷新中
}
class JSRefresh: UIControl {
// 被观察对象
var scrollerView: UIScrollView?
// MARK: - 懒加载控件
private lazy var statusLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(STATUS_LABEL_FONT_SIZE)
label.textColor = STATUS_LABEL_FONT_COLOR
label.textAlignment = .Center
return label
}()
// 记录刷新控件状态,初始为正常状态
var refreshStatus: JSRefreshType = .Normal{
didSet{
switch refreshStatus {
case .Normal:
statusLabel.text = "\(refreshStatus)"
// 让自定义控件的上方间距恢复
UIView.animateWithDuration(0.25, animations: {
self.scrollerView?.contentInset.top -= REFRESH_HEIGHT
})
case .Pulling:
statusLabel.text = "\(refreshStatus)"
case .Refreshing:
statusLabel.text = "\(refreshStatus)"
//刷新中状态让自定义刷新控件保留显示
UIView.animateWithDuration(0.25, animations: {
self.scrollerView?.contentInset.top += REFRESH_HEIGHT
}, completion: { (finished) in
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
})
}
}
}
override init(frame: CGRect) {
super.init(frame: CGRect(x: 0, y: -REFRESH_HEIGHT, width: SCREEN_WIDTH, height: REFRESH_HEIGHT))
// 设置视图
setupUI()
}
// MARK: - 设置视图
private func setupUI () {
// 设置背景色
backgroundColor = REFRESH_BACKGROUND_COLOR
// 添加控件
addSubview(statusLabel)
// 添加约束
statusLabel.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
}
// MARK: - 监听该类将要添加到哪个父控件上
override func willMoveToSuperview(newSuperview: UIView?) {
/*
这里需要监测父控件的ContentOffSet判断状态
因为其控制器可能会使用TableView的代理方法,代理为一对一,考虑到封装性,不推荐使用代理,所以这里使用KVO
KVO的使用基本上都是三步:
1.注册观察者
addObserver:forKeyPath:options:context:
2.观察者中实现
observeValueForKeyPath:ofObject:change:context:
3.移除观察者
removeObserver:forKeyPath:
*/
// 判断是否有值,是否可以滚动
guard let scrollerView = newSuperview as? UIScrollView else {
return
}
self.scrollerView = scrollerView
// 注册观察者
scrollerView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
}
// 观察者实现
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
// 获取所监听的scrollView的Y轴偏移量
let contentOffSetY = self.scrollerView!.contentOffset.y
// 判断ScrollView是否正在拖动
if scrollerView!.dragging {
// 如果 scrollerView!.dragging == true 代表当前正在拖动ScrollView
if contentOffSetY > -(REFRESH_HEIGHT+64) && refreshStatus == .Pulling {
// contentOffSet.y > -(自定义刷新控件高度+64) && 当前状态为下拉中 --> 正常状态
refreshStatus = .Normal
} else if contentOffSetY <= -(REFRESH_HEIGHT+64) && refreshStatus == .Normal {
// contentOffSet.y <= -(自定义刷新控件高度+64) && 当前状态为正常 --> 下拉状态
refreshStatus = .Pulling
}
// 未拖动ScrollView时
} else {
// 停止拖动并松手,而且状态为下拉中 --> 刷新
if refreshStatus == .Pulling {
refreshStatus = .Refreshing
}
}
}
// MARK: - 结束刷新
func endRefreshing() -> Void {
// 将状态改为正常
refreshStatus = .Normal
}
deinit{
// 移除观察者
self.scrollerView?.removeObserver(self, forKeyPath: "contentOffset")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
3a309b9e675b26009e557e209960bd20
| 28.112299 | 213 | 0.544636 | false | false | false | false |
ikesyo/Swiftz
|
refs/heads/master
|
SwiftzTests/StringExtSpec.swift
|
bsd-3-clause
|
3
|
//
// StringExtSpec.swift
// Swiftz
//
// Created by Robert Widmann on 1/19/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
class StringExtSpec : XCTestCase {
func testProperties() {
property("unlines • lines === ('\n' • id)") <- forAll { (x : String) in
let l = x.lines()
let u = String.unlines(l)
return u == (x + "\n")
}
property("Strings of Equatable elements obey reflexivity") <- forAll { (l : String) in
return l == l
}
property("Strings of Equatable elements obey symmetry") <- forAll { (x : String, y : String) in
return (x == y) == (y == x)
}
property("Strings of Equatable elements obey transitivity") <- forAll { (x : String, y : String, z : String) in
if (x == y) && (y == z) {
return x == z
}
return Discard()
}
property("Strings of Equatable elements obey negation") <- forAll { (x : String, y : String) in
return (x != y) == !(x == y)
}
property("Strings of Comparable elements obey reflexivity") <- forAll { (l : String) in
return l == l
}
property("String obeys the Functor identity law") <- forAll { (x : String) in
return (x.fmap(identity)) == identity(x)
}
property("String obeys the Functor composition law") <- forAll { (f : ArrowOf<Character, Character>, g : ArrowOf<Character, Character>, x : String) in
return ((f.getArrow • g.getArrow) <^> x) == (x.fmap(g.getArrow).fmap(f.getArrow))
}
property("String obeys the Applicative identity law") <- forAll { (x : String) in
return (Array.pure(identity) <*> x) == x
}
// Swift unroller can't handle our scale.
// property("String obeys the first Applicative composition law") <- forAll { (fl : ArrayOf<ArrowOf<Character, Character>>, gl : ArrayOf<ArrowOf<Character, Character>>, x : String) in
// let f = fl.getArray.map({ $0.getArrow })
// let g = gl.getArray.map({ $0.getArrow })
// return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x))
// }
//
// property("String obeys the second Applicative composition law") <- forAll { (fl : ArrayOf<ArrowOf<Character, Character>>, gl : ArrayOf<ArrowOf<Character, Character>>, x : String) in
// let f = fl.getArray.map({ $0.getArrow })
// let g = gl.getArray.map({ $0.getArrow })
// return (pure(curry(•)) <*> f <*> g <*> x) == (f <*> (g <*> x))
// }
property("String obeys the Monoidal left identity law") <- forAll { (x : String) in
return (x + String.mempty) == x
}
property("String obeys the Monoidal right identity law") <- forAll { (x : String) in
return (String.mempty + x) == x
}
property("cons behaves") <- forAll { (c : Character, s : String) in
return String.cons(c, tail: s) == String(c) + s
}
property("replicate behaves") <- forAll { (n : UInt, x : Character) in
return String.replicate(n, value: x) == List.replicate(n, value: String(x)).reduce({ $0 + $1 }, initial: "")
}
property("map behaves") <- forAll { (xs : String) in
return xs.map(identity) == xs.fmap(identity)
}
property("map behaves") <- forAll { (xs : String) in
let fs : Character -> String = { String.replicate(2, value: $0) }
return (xs >>- fs) == Array(xs.characters).map(fs).reduce("", combine: +)
}
property("filter behaves") <- forAll { (xs : String, pred : ArrowOf<Character, Bool>) in
return xs.filter(pred.getArrow).reduce({ $0.0 && pred.getArrow($0.1) }, initial: true)
}
property("isPrefixOf behaves") <- forAll { (s1 : String, s2 : String) in
if s1.isPrefixOf(s2) {
return s1.stripPrefix(s2) != nil
}
if s2.isPrefixOf(s1) {
return s2.stripPrefix(s1) != nil
}
return Discard()
}
property("isSuffixOf behaves") <- forAll { (s1 : String, s2 : String) in
if s1.isSuffixOf(s2) {
return s1.stripSuffix(s2) != nil
}
if s2.isSuffixOf(s1) {
return s2.stripSuffix(s1) != nil
}
return Discard()
}
}
}
|
a1c4dd273c9394493a5433e484cb303d
| 30.844262 | 185 | 0.611583 | false | false | false | false |
AdySan/HomeKit-Demo
|
refs/heads/master
|
BetterHomeKit/UsersViewController.swift
|
mit
|
4
|
//
// UsersViewController.swift
// BetterHomeKit
//
// Created by Khaos Tian on 8/6/14.
// Copyright (c) 2014 Oltica. All rights reserved.
//
import UIKit
import HomeKit
class UsersViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var usersTableView: UITableView!
lazy var usersArray = [HMUser]()
override func viewDidLoad() {
super.viewDidLoad()
fetchUsers()
// Do any additional setup after loading the view.
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.usersTableView.setEditing(false, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetchUsers() {
usersArray.removeAll(keepCapacity: false)
if let currentHome = Core.sharedInstance.currentHome {
for user in currentHome.users as! [HMUser]{
usersArray.append(user)
}
}
usersTableView.reloadData()
}
@IBAction func addUser(sender: AnyObject) {
/*let alert = UIAlertController(title: "New User", message: "Enter the iCloud address of user you want to add. (The users list will get updated once user accept the invitation.)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(nil)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler:
{
[weak self]
(action:UIAlertAction!) in
let textField = alert.textFields?[0] as UITextField
Core.sharedInstance.currentHome?.addUserWithCompletionHandler {
user, error in
if error != nil {
NSLog("Add user failed: \(error)")
} else {
self?.fetchUsers()
}
}
}))*/
Core.sharedInstance.currentHome?.addUserWithCompletionHandler {
user, error in
if error != nil {
NSLog("Add user failed: \(error)")
if error.code == 41 {
var alert = UIAlertController(title: "Failed", message: "Failed to add user to home. Normally this happens because not all accessories are reachable. Please try again after all accessories are reachable.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
} else {
self.fetchUsers()
}
}
/*dispatch_async(dispatch_get_main_queue(),
{
self.presentViewController(alert, animated: true, completion: nil)
})*/
}
@IBAction func dismissVC(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usersArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("userCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = usersArray[indexPath.row].name
cell.detailTextLabel?.text = "User"
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
let userID = usersArray[indexPath.row]
Core.sharedInstance.currentHome?.removeUser(userID) {
[weak self]
error in
if error != nil {
NSLog("Failed removing user, error:\(error)")
} else {
self?.fetchUsers()
}
}
}
}
}
|
ce65b452d1ffc6c136f3462f8c6c5f80
| 37.478632 | 271 | 0.608618 | false | false | false | false |
Elm-Tree-Island/Shower
|
refs/heads/master
|
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/DynamicPropertySpec.swift
|
gpl-3.0
|
4
|
import ReactiveSwift
import Result
import Nimble
import Quick
import ReactiveCocoa
private let initialPropertyValue = "InitialValue"
private let subsequentPropertyValue = "SubsequentValue"
private let finalPropertyValue = "FinalValue"
private let initialOtherPropertyValue = "InitialOtherValue"
private let subsequentOtherPropertyValue = "SubsequentOtherValue"
private let finalOtherPropertyValue = "FinalOtherValue"
class DynamicPropertySpec: QuickSpec {
override func spec() {
describe("DynamicProperty with optional value") {
var object: ObservableObject!
var property: DynamicProperty<NSNumber?>!
beforeEach {
object = ObservableObject()
expect(object.rac_optional_value) == 0
property = DynamicProperty<NSNumber?>(object: object, keyPath: "rac_optional_value")
}
afterEach {
object = nil
}
let propertyValue: () -> NSNumber? = {
if let value: Any = property?.value {
return value as? NSNumber
} else {
return nil
}
}
it("should read the underlying object") {
expect(propertyValue()) == 0
object.rac_optional_value = nil
expect(propertyValue()).to(beNil())
}
it("should write the underlying object") {
property.value = nil
expect(object.rac_optional_value).to(beNil())
expect(propertyValue()).to(beNil())
}
it("should yield a producer that sends the current value and then the changes for the key path of the underlying object") {
var values: [NSNumber?] = []
property.producer.startWithValues { value in
values.append(value)
}
expect(values).to(equal([0]))
property.value = nil
expect(values).to(equal([0, nil]))
object.rac_optional_value = 2
expect(values).to(equal([0, nil, 2]))
object.rac_optional_value = nil
expect(values).to(equal([0, nil, 2, nil]))
print(values)
}
}
describe("DynamicProperty") {
var object: ObservableObject!
var property: DynamicProperty<Int>!
let propertyValue: () -> Int? = {
if let value: Any = property?.value {
return value as? Int
} else {
return nil
}
}
beforeEach {
object = ObservableObject()
expect(object.rac_value) == 0
property = DynamicProperty<Int>(object: object, keyPath: "rac_value")
}
afterEach {
object = nil
}
it("should read the underlying object") {
expect(propertyValue()) == 0
object.rac_value = 1
expect(propertyValue()) == 1
}
it("should write the underlying object") {
property.value = 1
expect(object.rac_value) == 1
expect(propertyValue()) == 1
}
it("should yield a producer that sends the current value and then the changes for the key path of the underlying object") {
var values: [Int] = []
property.producer.startWithValues { value in
values.append(value)
}
expect(values) == [ 0 ]
property.value = 1
expect(values) == [ 0, 1 ]
object.rac_value = 2
expect(values) == [ 0, 1, 2 ]
}
it("should yield a producer that sends the current value and then the changes for the key path of the underlying object, even if the value actually remains unchanged") {
var values: [Int] = []
property.producer.startWithValues { value in
values.append(value)
}
expect(values) == [ 0 ]
property.value = 0
expect(values) == [ 0, 0 ]
object.rac_value = 0
expect(values) == [ 0, 0, 0 ]
}
it("should yield a signal that emits subsequent values for the key path of the underlying object") {
var values: [Int] = []
property.signal.observeValues { value in
expect(value).notTo(beNil())
values.append(value)
}
expect(values) == []
property.value = 1
expect(values) == [ 1 ]
object.rac_value = 2
expect(values) == [ 1, 2 ]
}
it("should yield a signal that emits subsequent values for the key path of the underlying object, even if the value actually remains unchanged") {
var values: [Int] = []
property.signal.observeValues { value in
values.append(value)
}
expect(values) == []
property.value = 0
expect(values) == [ 0 ]
object.rac_value = 0
expect(values) == [ 0, 0 ]
}
it("should have a completed producer when the underlying object deallocates") {
var completed = false
property = {
// Use a closure so this object has a shorter lifetime.
let object = ObservableObject()
let property = DynamicProperty<Int>(object: object, keyPath: "rac_value")
property.producer.startWithCompleted {
completed = true
}
expect(completed) == false
expect(property.value).notTo(beNil())
return property
}()
expect(completed).toEventually(beTruthy())
}
it("should have a completed signal when the underlying object deallocates") {
var completed = false
property = {
// Use a closure so this object has a shorter lifetime.
let object = ObservableObject()
let property = DynamicProperty<Int>(object: object, keyPath: "rac_value")
property.signal.observeCompleted {
completed = true
}
expect(completed) == false
expect(property.value).notTo(beNil())
return property
}()
expect(completed).toEventually(beTruthy())
}
it("should not be retained by its underlying object"){
weak var dynamicProperty: DynamicProperty<Int>? = property
property = nil
expect(dynamicProperty).to(beNil())
}
it("should support un-bridged reference types") {
let dynamicProperty = DynamicProperty<UnbridgedObject>(object: object, keyPath: "rac_reference")
dynamicProperty.value = UnbridgedObject("foo")
expect(object.rac_reference.value) == "foo"
}
it("should support un-bridged value types") {
let dynamicProperty = DynamicProperty<UnbridgedValue>(object: object, keyPath: "rac_unbridged")
dynamicProperty.value = .changed
expect(object.rac_unbridged as? UnbridgedValue) == UnbridgedValue.changed
}
it("should expose a lifetime that ends upon the deinitialization of its underlying object") {
var isEnded = false
property!.lifetime.ended.observeCompleted {
isEnded = true
}
expect(isEnded) == false
property = nil
expect(isEnded) == false
object = nil
expect(isEnded) == true
}
}
describe("binding") {
describe("to a dynamic property") {
var object: ObservableObject!
var property: DynamicProperty<Int>!
beforeEach {
object = ObservableObject()
expect(object.rac_value) == 0
property = DynamicProperty<Int>(object: object, keyPath: "rac_value")
}
afterEach {
object = nil
}
it("should bridge values sent on a signal to Objective-C") {
let (signal, observer) = Signal<Int, NoError>.pipe()
property <~ signal
observer.send(value: 1)
expect(object.rac_value) == 1
}
it("should bridge values sent on a signal producer to Objective-C") {
let producer = SignalProducer<Int, NoError>(value: 1)
property <~ producer
expect(object.rac_value) == 1
}
it("should bridge values from a source property to Objective-C") {
let source = MutableProperty(1)
property <~ source
expect(object.rac_value) == 1
}
it("should bridge values sent on a signal to Objective-C, even if the view has deinitialized") {
let (signal, observer) = Signal<Int, NoError>.pipe()
property <~ signal
property = nil
observer.send(value: 1)
expect(object.rac_value) == 1
}
it("should bridge values sent on a signal producer to Objective-C, even if the view has deinitialized") {
let producer = SignalProducer<Int, NoError>(value: 1)
property <~ producer
property = nil
expect(object.rac_value) == 1
}
it("should bridge values from a source property to Objective-C, even if the view has deinitialized") {
let source = MutableProperty(1)
property <~ source
property = nil
expect(object.rac_value) == 1
}
}
}
}
}
private class ObservableObject: NSObject {
@objc dynamic var rac_value: Int = 0
@objc dynamic var rac_optional_value: NSNumber? = 0
@objc dynamic var rac_reference: UnbridgedObject = UnbridgedObject("")
@objc dynamic var rac_unbridged: Any = UnbridgedValue.starting
}
private class UnbridgedObject: NSObject {
let value: String
init(_ value: String) {
self.value = value
}
}
private enum UnbridgedValue {
case starting
case changed
}
|
87ee2458a67b401ec4e03b7aa1723cb6
| 24.902141 | 172 | 0.659032 | false | false | false | false |
jianghongbing/APIReferenceDemo
|
refs/heads/master
|
Swift/Syntax/NestedTypes.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
//嵌套类型,某一个类型中再定义其他类型
struct Rect {
struct Point {
var x: Double
var y: Double
}
struct Size {
var width: Double
var height: Double
}
var x = 0.0
var y = 0.0
var width = 0.0
var height = 0.0
init(origin: Point, size: Size) {
x = origin.x
y = origin.y
width = size.width
height = size.height
}
}
//引用嵌套类型
let origin = Rect.Point(x: 10, y: 10)
let size = Rect.Size(width: 100, height: 100)
let rect = Rect(origin: origin, size: size)
class User {
enum UserType: String{
case teacher = "Teacher"
case student = "Student"
}
var name: String
var userId: String
let userType: UserType
init(name: String, userId: String, userType: UserType) {
self.name = name
self.userId = userId
self.userType = userType
}
}
let userType = User.UserType.student
let user = User(name: "xiaoming", userId: "001", userType: userType)
let type = user.userType.rawValue
|
5b892b1133780cc3cc8f9cacc9929588
| 21.142857 | 68 | 0.595392 | false | false | false | false |
Rush42/SwiftCron
|
refs/heads/master
|
Sources/CronExpression.swift
|
mit
|
2
|
import Foundation
/*
* * * * *
| | | | |
| | | | ---- Weekday
| | | ------ Month
| | -------- Day
| ---------- Hour
------------ Minute
* * * * * *
| | | | | |
| | | | | ---- Year
| | | | ------ Weekday
| | | -------- Month
| | ---------- Day
| ------------ Hour
-------------- Minute
*/
public class CronExpression {
var cronRepresentation: CronRepresentation
public convenience init?(cronString: String) {
guard let cronRepresentation = CronRepresentation(cronString: cronString) else {
return nil
}
self.init(cronRepresentation: cronRepresentation)
}
public convenience init?(minute: CronFieldTranslatable = CronRepresentation.DefaultValue, hour: CronFieldTranslatable = CronRepresentation.DefaultValue, day: CronFieldTranslatable = CronRepresentation.DefaultValue, month: CronFieldTranslatable = CronRepresentation.DefaultValue, weekday: CronFieldTranslatable = CronRepresentation.DefaultValue, year: CronFieldTranslatable = CronRepresentation.DefaultValue) {
let cronRepresentation = CronRepresentation(minute: minute.cronFieldRepresentation, hour: hour.cronFieldRepresentation, day: day.cronFieldRepresentation, month: month.cronFieldRepresentation, weekday: weekday.cronFieldRepresentation, year: year.cronFieldRepresentation)
self.init(cronRepresentation: cronRepresentation)
}
private init?(cronRepresentation theCronRepresentation: CronRepresentation) {
cronRepresentation = theCronRepresentation
let parts = cronRepresentation.cronParts
for index: Int in 0 ..< parts.count {
let field = CronField(rawValue: index)!
if field.getFieldChecker().validate(parts[index]) == false {
NSLog("\(#function): Invalid cron field value \(parts[index]) at position \(index)")
return nil
}
}
}
public var stringRepresentation: String {
return cronRepresentation.cronString
}
// MARK: - Description
public var shortDescription: String {
return CronDescriptionBuilder.buildDescription(cronRepresentation, length: .short)
}
public var longDescription: String {
return CronDescriptionBuilder.buildDescription(cronRepresentation, length: .long)
}
// MARK: - Get Next Run Date
public func getNextRunDateFromNow(adjustingForTimeZone outputTimeZone: TimeZone = .current) -> Date? {
return getNextRunDate(Date(), adjustingForTimeZone: outputTimeZone)
}
public func getNextRunDate(_ date: Date, adjustingForTimeZone outputTimeZone: TimeZone = .current) -> Date? {
guard let nextRun = getNextRunDate(date, skip: 0) else { return nil }
return adjust(date: nextRun, for: outputTimeZone)
}
func adjust(date: Date, for timeZone: TimeZone) -> Date {
let currentTZOffset = TimeZone.current.secondsFromGMT(for: date)
let outputTZOffset = timeZone.secondsFromGMT(for: date)
let tzDifference = TimeInterval(currentTZOffset - outputTZOffset)
return date.addingTimeInterval(tzDifference)
}
func getNextRunDate(_ date: Date, skip: Int) -> Date? {
guard matchIsTheoreticallyPossible(date) else {
return nil
}
var timesToSkip = skip
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .weekday], from: date)
components.second = 0
var nextRun = calendar.date(from: components)!
// MARK: Issue 3: Instantiate enum instances with the right value
let allFieldsInExpression: Array<CronField> = [.minute, .hour, .day, .month, .weekday, .year]
// Set a hard limit to bail on an impossible date
iteration: for _: Int in 0 ..< 1000 {
var satisfied = false
currentFieldLoop: for cronField: CronField in allFieldsInExpression {
// MARK: Issue 3: just call cronField.isSatisfiedBy, or getNextApplicableDate as specified in Issue 2
let part = cronRepresentation[cronField.rawValue]
let fieldChecker = cronField.getFieldChecker()
if part.contains(CronRepresentation.ListIdentifier) == false {
satisfied = fieldChecker.isSatisfiedBy(nextRun, value: part)
} else {
for listPart: String in part.components(separatedBy: CronRepresentation.ListIdentifier) {
satisfied = fieldChecker.isSatisfiedBy(nextRun, value: listPart)
if satisfied {
break
}
}
}
// If the field is not satisfied, then start over
if satisfied == false {
nextRun = fieldChecker.increment(nextRun, toMatchValue: part)
continue iteration
}
// Skip this match if needed
if timesToSkip > 0 {
_ = CronField(rawValue: 0)!.getFieldChecker().increment(nextRun, toMatchValue: part)
timesToSkip -= 1
}
continue currentFieldLoop
}
return satisfied ? nextRun : nil
}
return nil
}
private func matchIsTheoreticallyPossible(_ date: Date) -> Bool {
// TODO: Handle lists and steps
guard let year = Int(cronRepresentation.year) else {
return true
}
var components = DateComponents()
components.year = year
if let month = Int(cronRepresentation.month) {
components.month = month
if month < 1 {
return false
}
}
let day = Int(cronRepresentation.day) ?? Calendar.current.date(from: components)!.getLastDayOfMonth()
//{
components.day = day
if day < 1 {
return false
}
//}
let dateFromComponents = Calendar.current.date(from: components)!
return date.compare(dateFromComponents) == .orderedAscending || date.compare(dateFromComponents) == .orderedSame
}
}
|
80b9fb78f62ea725acdcec6c8aef5de9
| 32.981366 | 410 | 0.697679 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Mac/MainWindow/NNW3/NNW3OpenPanelAccessoryViewController.swift
|
mit
|
1
|
//
// NNW3OpenPanelAccessoryViewController.swift
// NetNewsWire
//
// Created by Brent Simmons on 10/14/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
import Account
final class NNW3OpenPanelAccessoryViewController: NSViewController {
@IBOutlet weak var accountPopUpButton: NSPopUpButton!
var selectedAccount: Account? {
accountPopUpButton.selectedItem?.representedObject as? Account
}
init() {
super.init(nibName: "NNW3OpenPanelAccessoryView", bundle: nil)
}
// MARK: - NSViewController
required init?(coder: NSCoder) {
preconditionFailure("NNW3OpenPanelAccessoryViewController.init(coder) not implemented by design.")
}
override func viewDidLoad() {
accountPopUpButton.removeAllItems()
let menu = NSMenu()
accountPopUpButton.menu = menu
for account in AccountManager.shared.sortedActiveAccounts {
let menuItem = NSMenuItem()
menuItem.title = account.nameForDisplay
menuItem.representedObject = account
menu.addItem(menuItem)
if account.accountID == AppDefaults.shared.importOPMLAccountID {
accountPopUpButton.select(menuItem)
}
}
}
}
|
ce733ec6af378d0f9ed6921121053143
| 23.12766 | 100 | 0.761905 | false | false | false | false |
idmean/CodaLess
|
refs/heads/master
|
CodaLess/CodaLessPrefrencesWindowController.swift
|
gpl-3.0
|
1
|
//
// CodaLessPrefrencesWindowController.swift
// CodaLess
//
// Created by Theo on 05/12/14.
// Copyright (c) 2014 Theo Weidmann. All rights reserved.
//
import Cocoa
import AppKit
class CodaLessPrefrencesWindowController: NSWindowController, NSTextFieldDelegate {
let userDefaults = UserDefaults.standard
@IBOutlet weak var minifyButton: NSButton!
@IBOutlet weak var pathField: NSTextField!
@IBOutlet weak var version: NSTextField!
@IBOutlet weak var progress: NSProgressIndicator!
override func windowDidLoad() {
super.windowDidLoad()
minifyButton.state = userDefaults.bool(forKey: "cleanCSS") ? 1 : 0
if let format = userDefaults.string(forKey: "cssPath") {
pathField.stringValue = format
}
if !FileManager.default.fileExists(atPath: "/usr/local/bin/node") {
self.version.textColor = NSColor.red
version.stringValue = "Node not in place"
}
else if !FileManager.default.fileExists(atPath: "/usr/local/lib/node_modules/less/bin/lessc"){
self.version.textColor = NSColor.red
version.stringValue = "Less not in place"
}
else {
progress.startAnimation(self)
DispatchQueue.global(qos: .background).async {
let task = Process()
task.launchPath = "/usr/local/bin/node"
task.arguments = ["/usr/local/lib/node_modules/less/bin/lessc", "-v"]
let outputPipe = Pipe()
task.standardOutput = outputPipe
task.terminationHandler = { (task: Process!) in
let string = NSString(data: outputPipe.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue)
if string != nil && string!.length != 0 {
DispatchQueue.main.async {
let version = string!.substring(with: NSRange(location: 6,length: 5))
self.progress.stopAnimation(self)
if EDSemver(string: version).isLessThan(EDSemver(string: "2.2.0")) {
self.version.textColor = NSColor.red
self.version.stringValue = "Less Version: \(version). Please update or click the ?."
}
else {
self.version.stringValue = "Less Version: " + version
}
return
}
}
else {
self.progress.stopAnimation(self)
self.version.stringValue = "Less version could not be determined"
return
}
}
task.launch()
}
}
}
@IBAction func minifyChanged(_ sender: AnyObject) {
userDefaults.set(minifyButton.state == 1, forKey: "cleanCSS")
}
@IBAction func openHelp(_ sender: AnyObject) {
NSWorkspace.shared().open(URL(string: "https://github.com/idmean/CodaLess")!)
}
override func controlTextDidChange(_ obj: Notification) {
userDefaults.set(pathField.stringValue, forKey: "cssPath")
}
}
|
c32360c0f763dcfb6447171922cf2c7a
| 37.866667 | 143 | 0.525157 | false | false | false | false |
Quick/Nimble
|
refs/heads/main
|
Bootstrap/Pods/Nimble/Sources/Nimble/Utils/AsyncAwait.swift
|
apache-2.0
|
2
|
#if !os(WASI)
import CoreFoundation
import Dispatch
import Foundation
private let timeoutLeeway = DispatchTimeInterval.milliseconds(1)
private let pollLeeway = DispatchTimeInterval.milliseconds(1)
internal struct AsyncAwaitTrigger {
let timeoutSource: DispatchSourceTimer
let actionSource: DispatchSourceTimer?
let start: () async throws -> Void
}
/// Factory for building fully configured AwaitPromises and waiting for their results.
///
/// This factory stores all the state for an async expectation so that Await doesn't
/// doesn't have to manage it.
internal class AsyncAwaitPromiseBuilder<T> {
let awaiter: Awaiter
let waitLock: WaitLock
let trigger: AsyncAwaitTrigger
let promise: AwaitPromise<T>
internal init(
awaiter: Awaiter,
waitLock: WaitLock,
promise: AwaitPromise<T>,
trigger: AsyncAwaitTrigger) {
self.awaiter = awaiter
self.waitLock = waitLock
self.promise = promise
self.trigger = trigger
}
func timeout(_ timeoutInterval: DispatchTimeInterval, forcefullyAbortTimeout: DispatchTimeInterval) -> Self {
/// = Discussion =
///
/// There's a lot of technical decisions here that is useful to elaborate on. This is
/// definitely more lower-level than the previous NSRunLoop based implementation.
///
///
/// Why Dispatch Source?
///
///
/// We're using a dispatch source to have better control of the run loop behavior.
/// A timer source gives us deferred-timing control without having to rely as much on
/// a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.)
/// which is ripe for getting corrupted by application code.
///
/// And unlike `dispatch_async()`, we can control how likely our code gets prioritized to
/// executed (see leeway parameter) + DISPATCH_TIMER_STRICT.
///
/// This timer is assumed to run on the HIGH priority queue to ensure it maintains the
/// highest priority over normal application / test code when possible.
///
///
/// Run Loop Management
///
/// In order to properly interrupt the waiting behavior performed by this factory class,
/// this timer stops the main run loop to tell the waiter code that the result should be
/// checked.
///
/// In addition, stopping the run loop is used to halt code executed on the main run loop.
trigger.timeoutSource.schedule(
deadline: DispatchTime.now() + timeoutInterval,
repeating: .never,
leeway: timeoutLeeway
)
trigger.timeoutSource.setEventHandler {
guard self.promise.asyncResult.isIncomplete() else { return }
let timedOutSem = DispatchSemaphore(value: 0)
let semTimedOutOrBlocked = DispatchSemaphore(value: 0)
semTimedOutOrBlocked.signal()
DispatchQueue.main.async {
if semTimedOutOrBlocked.wait(timeout: .now()) == .success {
timedOutSem.signal()
semTimedOutOrBlocked.signal()
self.promise.resolveResult(.timedOut)
}
}
// potentially interrupt blocking code on run loop to let timeout code run
let now = DispatchTime.now() + forcefullyAbortTimeout
let didNotTimeOut = timedOutSem.wait(timeout: now) != .success
let timeoutWasNotTriggered = semTimedOutOrBlocked.wait(timeout: .now()) == .success
if didNotTimeOut && timeoutWasNotTriggered {
self.promise.resolveResult(.blockedRunLoop)
}
}
return self
}
/// Blocks for an asynchronous result.
///
/// @discussion
/// This function cannot be nested. This is because this function (and it's related methods)
/// coordinate through the main run loop. Tampering with the run loop can cause undesirable behavior.
///
/// This method will return an AwaitResult in the following cases:
///
/// - The main run loop is blocked by other operations and the async expectation cannot be
/// be stopped.
/// - The async expectation timed out
/// - The async expectation succeeded
/// - The async expectation raised an unexpected exception (objc)
/// - The async expectation raised an unexpected error (swift)
///
/// The returned AwaitResult will NEVER be .incomplete.
@MainActor
func wait(_ fnName: String = #function, file: FileString = #file, line: UInt = #line) async -> PollResult<T> {
waitLock.acquireWaitingLock(
fnName,
file: file,
line: line)
defer {
self.waitLock.releaseWaitingLock()
}
do {
try await self.trigger.start()
} catch let error {
self.promise.resolveResult(.errorThrown(error))
}
self.trigger.timeoutSource.resume()
while self.promise.asyncResult.isIncomplete() {
await Task.yield()
}
self.trigger.timeoutSource.cancel()
if let asyncSource = self.trigger.actionSource {
asyncSource.cancel()
}
return promise.asyncResult
}
}
extension Awaiter {
func performBlock<T>(
file: FileString,
line: UInt,
_ closure: @escaping (@escaping (T) -> Void) async throws -> Void
) async -> AsyncAwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
var completionCount = 0
let trigger = AsyncAwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) {
try await closure { result in
completionCount += 1
if completionCount < 2 {
promise.resolveResult(.completed(result))
} else {
fail("waitUntil(..) expects its completion closure to be only called once",
file: file, line: line)
}
}
}
return AsyncAwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
func poll<T>(_ pollInterval: DispatchTimeInterval, closure: @escaping () throws -> T?) async -> AsyncAwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
let asyncSource = createTimerSource(asyncQueue)
let trigger = AsyncAwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) {
let interval = pollInterval
asyncSource.schedule(deadline: .now(), repeating: interval, leeway: pollLeeway)
asyncSource.setEventHandler {
do {
if let result = try closure() {
promise.resolveResult(.completed(result))
}
} catch let error {
promise.resolveResult(.errorThrown(error))
}
}
asyncSource.resume()
}
return AsyncAwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
}
internal func pollBlock(
pollInterval: DispatchTimeInterval,
timeoutInterval: DispatchTimeInterval,
file: FileString,
line: UInt,
fnName: String = #function,
expression: @escaping () throws -> Bool) async -> PollResult<Bool> {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let result = await awaiter.poll(pollInterval) { () throws -> Bool? in
if try expression() {
return true
}
return nil
}
.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval.divided)
.wait(fnName, file: file, line: line)
return result
}
#endif // #if !os(WASI)
|
71eb79b55b70a657031067095c700a0b
| 37.341121 | 129 | 0.602925 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/Classes/Services/NotificationSyncMediator.swift
|
gpl-2.0
|
1
|
import Foundation
import CocoaLumberjack
import WordPressKit
/// Notes:
///
/// You may have noticed this is a *Mediator*, not a service. Reason we're adopting a different name here,
/// briefly, is because this entity needs to be aware of other instances, in order to successfully
/// prevent race conditions / data duplication.
///
/// IE multiple SyncService's running concurrently, with no shared MOC / Locks, may end up retrieving and
/// inserting the same set of notifications. Which leads to loss of data integrity.
///
/// Details in #6220.
///
// MARK: - Notifications
//
let NotificationSyncMediatorDidUpdateNotifications = "NotificationSyncMediatorDidUpdateNotifications"
// MARK: - NotificationSyncMediator
//
final class NotificationSyncMediator {
/// Returns the Main Managed Context
///
fileprivate let contextManager: CoreDataStack
/// Sync Service Remote
///
fileprivate let remote: NotificationSyncServiceRemote
/// Maximum number of Notes to Sync
///
fileprivate let maximumNotes = 100
/// Main CoreData Context
///
fileprivate var mainContext: NSManagedObjectContext {
return contextManager.mainContext
}
/// Shared serial operation queue among all instances.
///
/// This queue is used to ensure notification operations (like syncing operations) invoked from various places of
/// the app are performed sequentially, to prevent potential data corruption.
private static let operationQueue = {
let queue = OperationQueue()
queue.name = "org.wordpress.NotificationSyncMediator"
queue.maxConcurrentOperationCount = 1
return queue
}()
/// Designed Initializer
///
convenience init?() {
let manager = ContextManager.sharedInstance()
guard let dotcomAPI = try? WPAccount.lookupDefaultWordPressComAccount(in: manager.mainContext)?.wordPressComRestApi else {
return nil
}
self.init(manager: manager, dotcomAPI: dotcomAPI)
}
/// Initializer: Useful for Unit Testing
///
/// - Parameters:
/// - manager: ContextManager Instance
/// - wordPressComRestApi: The WordPressComRestApi that should be used.
///
init?(manager: CoreDataStack, dotcomAPI: WordPressComRestApi) {
guard dotcomAPI.hasCredentials() else {
return nil
}
contextManager = manager
remote = NotificationSyncServiceRemote(wordPressComRestApi: dotcomAPI)
}
/// Syncs the latest *maximumNotes*:
///
/// - Note: This method should only be used on the main thread.
///
/// - Latest 100 hashes are retrieved (++efficiency++)
/// - Only those Notifications that were remotely changed (Updated / Inserted) will be retrieved
/// - Local collection will be updated. Old notes will be purged!
///
func sync(_ completion: ((Error?, Bool) -> Void)? = nil) {
assert(Thread.isMainThread)
remote.loadHashes(withPageSize: maximumNotes) { error, remoteHashes in
guard let remoteHashes = remoteHashes else {
completion?(error, false)
return
}
self.deleteLocalMissingNotes(from: remoteHashes) {
self.determineUpdatedNotes(with: remoteHashes) { outdatedNoteIds in
guard outdatedNoteIds.isEmpty == false else {
completion?(nil, false)
return
}
self.remote.loadNotes(noteIds: outdatedNoteIds) { error, remoteNotes in
guard let remoteNotes = remoteNotes else {
completion?(error, false)
return
}
self.updateLocalNotes(with: remoteNotes) {
self.notifyNotificationsWereUpdated()
completion?(nil, true)
}
}
}
}
}
}
/// Sync's Notification matching the specified ID, and updates the local entity.
///
/// - Note: This method should only be used on the main thread.
///
/// - Parameters:
/// - noteId: Notification ID of the note to be downloaded.
/// - completion: Closure to be executed on completion.
///
func syncNote(with noteId: String, completion: ((Error?, Notification?) -> Void)? = nil) {
assert(Thread.isMainThread)
remote.loadNotes(noteIds: [noteId]) { error, remoteNotes in
guard let remoteNotes = remoteNotes else {
completion?(error, nil)
return
}
self.updateLocalNotes(with: remoteNotes) {
let predicate = NSPredicate(format: "(notificationId == %@)", noteId)
let note = self.mainContext.firstObject(ofType: Notification.self, matching: predicate)
completion?(nil, note)
}
}
}
/// Marks a Notification as Read.
///
/// - Note: This method should only be used on the main thread.
///
/// - Parameters:
/// - notification: The notification that was just read.
/// - completion: Callback to be executed on completion.
///
func markAsRead(_ notification: Notification, completion: ((Error?)-> Void)? = nil) {
mark([notification], asRead: true, completion: completion)
}
/// Marks an array of notifications as Read.
///
/// - Note: This method should only be used on the main thread.
///
/// - Parameters:
/// - notifications: Notifications that were marked as read.
/// - completion: Callback to be executed on completion.
///
func markAsRead(_ notifications: [Notification], completion: ((Error?)-> Void)? = nil) {
mark(notifications, asRead: true, completion: completion)
}
/// Marks a Notification as Unead.
///
/// - Note: This method should only be used on the main thread.
///
/// - Parameters:
/// - notification: The notification that should be marked unread.
/// - completion: Callback to be executed on completion.
///
func markAsUnread(_ notification: Notification, completion: ((Error?)-> Void)? = nil) {
mark([notification], asRead: false, completion: completion)
}
private func mark(_ notifications: [Notification], asRead read: Bool = true, completion: ((Error?)-> Void)? = nil) {
assert(Thread.isMainThread)
let noteIDs = notifications.map {
$0.notificationId
}
remote.updateReadStatusForNotifications(noteIDs, read: read) { error in
if let error = error {
DDLogError("Error marking notifications as \(Self.readState(for: read)): \(error)")
// Ideally, we'd want to revert to the previous status if this
// fails, but if the note is visible, the UI layer will keep
// trying to mark this note and fail.
//
// While not a perfect UX, the easy way out is to pretend it
// worked, but invalidate the cache so it can be reverted in the
// next successful sync.
//
// https://github.com/wordpress-mobile/WordPress-iOS/issues/7216
NotificationSyncMediator()?.invalidateCacheForNotifications(noteIDs)
}
completion?(error)
}
let objectIDs = notifications.map {
$0.objectID
}
updateReadStatus(
read,
forNotesWithObjectIDs: objectIDs
)
}
private static func readState(for read: Bool) -> String {
read ? "read" : "unread"
}
/// Invalidates the cache for a notification, marks it as read and syncs it.
///
/// - Parameters:
/// - noteID: The notification id to mark as read.
/// - completion: Callback to be executed on completion.
///
func markAsReadAndSync(_ noteID: String, completion: ((Error?) -> Void)? = nil) {
invalidateCacheForNotification(noteID)
remote.updateReadStatus(noteID, read: true) { error in
if let error = error {
DDLogError("Error marking note as read: \(error)")
}
self.syncNote(with: noteID) { (_, _) in
completion?(error)
}
}
}
/// Updates the Backend's Last Seen Timestamp. Used to calculate the Badge Count!
///
/// - Note: This method should only be used on the main thread.
///
/// - Parameters:
/// - timestamp: Timestamp of the last seen notification.
/// - completion: Callback to be executed on completion.
///
func updateLastSeen(_ timestamp: String, completion: ((Error?) -> Void)? = nil) {
assert(Thread.isMainThread)
remote.updateLastSeen(timestamp) { error in
if let error = error {
DDLogError("Error while Updating Last Seen Timestamp: \(error)")
}
completion?(error)
}
}
/// Deletes the note with the given ID from Core Data.
///
func deleteNote(noteID: String) {
Self.operationQueue.addOperation(AsyncBlockOperation { [contextManager] done in
contextManager.performAndSave { context in
let predicate = NSPredicate(format: "(notificationId == %@)", noteID)
for orphan in context.allObjects(ofType: Notification.self, matching: predicate) {
context.deleteObject(orphan)
}
} completion: {
done()
}
})
}
/// Invalidates the local cache for the notification with the specified ID.
///
func invalidateCacheForNotification(_ noteID: String) {
invalidateCacheForNotifications([noteID])
}
/// Invalidates the local cache for all the notifications with specified ID's in the array.
///
func invalidateCacheForNotifications(_ noteIDs: [String]) {
Self.operationQueue.addOperation(AsyncBlockOperation { [contextManager] done in
contextManager.performAndSave { context in
let predicate = NSPredicate(format: "(notificationId IN %@)", noteIDs)
let notifications = context.allObjects(ofType: Notification.self, matching: predicate)
notifications.forEach { $0.notificationHash = nil }
} completion: {
done()
}
})
}
}
// MARK: - Private Helpers
//
private extension NotificationSyncMediator {
/// Given a collection of RemoteNotification Hashes, this method will determine the NotificationID's
/// that are either missing in our database, or have been remotely updated.
///
/// - Parameters:
/// - remoteHashes: Collection of Notification Hashes
/// - completion: Callback to be executed on completion
///
func determineUpdatedNotes(with remoteHashes: [RemoteNotification], completion: @escaping (([String]) -> Void)) {
Self.operationQueue.addOperation(AsyncBlockOperation { [contextManager] done in
contextManager.performAndSave { context in
let remoteIds = remoteHashes.map { $0.notificationId }
let predicate = NSPredicate(format: "(notificationId IN %@)", remoteIds)
var localHashes = [String: String]()
for note in context.allObjects(ofType: Notification.self, matching: predicate) {
localHashes[note.notificationId] = note.notificationHash ?? ""
}
let outdatedIds = remoteHashes
.filter { remote in
let localHash = localHashes[remote.notificationId]
return localHash == nil || localHash != remote.notificationHash
}
.map { $0.notificationId }
DispatchQueue.main.async {
completion(outdatedIds)
}
done()
}
})
}
/// Given a collection of remoteNotes, this method will insert missing local ones, and update the ones
/// that can be found.
///
/// - Parameters:
/// - remoteNotes: Collection of Remote Notes
/// - completion: Callback to be executed on completion
///
func updateLocalNotes(with remoteNotes: [RemoteNotification], completion: (() -> Void)? = nil) {
Self.operationQueue.addOperation(AsyncBlockOperation { [contextManager] done in
contextManager.performAndSave { context in
for remoteNote in remoteNotes {
let predicate = NSPredicate(format: "(notificationId == %@)", remoteNote.notificationId)
let localNote = context.firstObject(ofType: Notification.self, matching: predicate) ?? context.insertNewObject(ofType: Notification.self)
localNote.update(with: remoteNote)
}
} completion: {
done()
DispatchQueue.main.async {
completion?()
}
}
})
}
/// Deletes the collection of local notifications that cannot be found in a given collection of
/// remote hashes.
///
/// - Parameter remoteHashes: Collection of remoteNotifications.
///
func deleteLocalMissingNotes(from remoteHashes: [RemoteNotification], completion: @escaping (() -> Void)) {
Self.operationQueue.addOperation(AsyncBlockOperation { [contextManager] done in
contextManager.performAndSave { context in
let remoteIds = remoteHashes.map { $0.notificationId }
let predicate = NSPredicate(format: "NOT (notificationId IN %@)", remoteIds)
for orphan in context.allObjects(ofType: Notification.self, matching: predicate) {
context.deleteObject(orphan)
}
} completion: {
done()
DispatchQueue.main.async {
completion()
}
}
})
}
/// Updates the Read status, of a given Notification, as specified.
///
/// Note: This method uses *saveContextAndWait* in order to prevent animation glitches when pushing
/// Notification Details.
///
/// - Parameters:
/// - status: New *read* value
/// - noteObjectID: CoreData ObjectID
///
func updateReadStatus(_ status: Bool, forNoteWithObjectID noteObjectID: NSManagedObjectID) {
updateReadStatus(status, forNotesWithObjectIDs: [noteObjectID])
}
/// Updates the Read status, of an array of Notifications, as specified.
///
/// Note: This method uses *saveContextAndWait* in order to prevent animation glitches when pushing
/// Notification Details.
///
/// - Parameters:
/// - status: New *read* value
/// - notesObjectIDs: CoreData ObjectIDs
///
func updateReadStatus(_ status: Bool, forNotesWithObjectIDs notesObjectIDs: [NSManagedObjectID]) {
let predicate = NSPredicate(format: "SELF IN %@", notesObjectIDs)
let notes = mainContext.allObjects(ofType: Notification.self, matching: predicate)
notes.forEach { $0.read = status }
contextManager.saveContextAndWait(mainContext)
}
/// Posts a `NotificationSyncMediatorDidUpdateNotifications` Notification, so that (potential listeners)
/// may react upon new content.
///
func notifyNotificationsWereUpdated() {
let notificationCenter = NotificationCenter.default
notificationCenter.post(name: Foundation.Notification.Name(rawValue: NotificationSyncMediatorDidUpdateNotifications), object: nil)
}
}
|
b98661c891fe41c9e4a7617ae0ed5450
| 35.764434 | 157 | 0.602236 | false | false | false | false |
heigong/Shared
|
refs/heads/master
|
iOS/UIBehaviorsDemo/UIBehaviorsDemo/SnapBehaviorViewController.swift
|
mit
|
1
|
//
// SnapBahaviorViewController.swift
// UIBehaviorsDemo
//
// Created by Di Chen on 8/5/15.
// Copyright (c) 2015 Di Chen. All rights reserved.
//
import Foundation
import UIKit
class SnapBehaviorViewController: UIViewController {
var squareView: UIView!
var animator: UIDynamicAnimator!
var snapBehavior: UISnapBehavior!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
createGestureRecognizer()
createSmallSquareView()
createAnimatorAndBehaviors()
}
func createSmallSquareView(){
squareView = UIView(frame: CGRectMake(0, 0, 80, 80))
squareView.backgroundColor = UIColor.greenColor()
squareView.center = view.center
view.addSubview(squareView)
}
func createGestureRecognizer(){
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
view.addGestureRecognizer(tapGestureRecognizer)
}
func createAnimatorAndBehaviors(){
animator = UIDynamicAnimator(referenceView: view)
let collision = UICollisionBehavior(items: [squareView])
collision.translatesReferenceBoundsIntoBoundary = true
snapBehavior = UISnapBehavior(item: squareView, snapToPoint: squareView.center)
// elasticity, the higher value (0-1), the less elasticity.
snapBehavior.damping = 1
animator.addBehavior(collision)
animator.addBehavior(snapBehavior)
}
func handleTap(tap: UITapGestureRecognizer){
let tapPoint = tap.locationInView(view)
animator.removeBehavior(snapBehavior)
snapBehavior = UISnapBehavior(item: squareView, snapToPoint: tapPoint)
animator.addBehavior(snapBehavior)
}
}
|
ebe09d6f07c153f439baff40ec0ba2fa
| 29.081967 | 93 | 0.672301 | false | false | false | false |
creatubbles/ctb-api-swift
|
refs/heads/develop
|
CreatubblesAPIClient/Sources/Requests/Notification/NotificationsFetchRequest.swift
|
mit
|
1
|
//
// NotificationsFetchRequest.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class NotificationsFetchRequest: Request {
override var method: RequestMethod { return .get }
override var endpoint: String { return "notifications" }
override var parameters: Dictionary<String, AnyObject> { return prepareParams() }
fileprivate let page: Int?
fileprivate let perPage: Int?
init(page: Int? = nil, perPage: Int? = nil) {
self.page = page
self.perPage = perPage
}
func prepareParams() -> Dictionary<String, AnyObject> {
var params = Dictionary<String, AnyObject>()
if let page = page {
params["page"] = page as AnyObject?
}
if let perPage = perPage {
params["per_page"] = perPage as AnyObject?
}
return params
}
}
|
389d579cc3a45666f891e921558fbf8d
| 36.301887 | 85 | 0.698533 | false | false | false | false |
MukeshKumarS/Swift
|
refs/heads/master
|
test/SourceKit/InterfaceGen/gen_swift_source.swift
|
apache-2.0
|
1
|
// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/Foo2.swift -- %S/Inputs/Foo2.swift > %t.response
// RUN: diff -u %s.response %t.response
// RUN: %sourcekitd-test -req=interface-gen-open %S/Inputs/Foo2.swift -- %S/Inputs/Foo2.swift \
// RUN: == -req=cursor -pos=18:49 | FileCheck -check-prefix=CHECK1 %s
// The cursor points to 'FooOverlayClassBase' inside the list of base classes, see 'gen_swift_source.swift.response'
// CHECK1: FooOverlayClassBase
// CHECK1: s:C4Foo219FooOverlayClassBase
// CHECK1: FooOverlayClassBase.Type
// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/UnresolvedExtension.swift -- %S/Inputs/UnresolvedExtension.swift | FileCheck -check-prefix=CHECK2 %s
// CHECK2: extension ET
// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/Foo3.swift -- %S/Inputs/Foo3.swift | FileCheck -check-prefix=CHECK3 %s
// CHECK3: public class C {
|
8e8d05ccdac2e2bb5dd30e51fa456fb6
| 53.375 | 154 | 0.735632 | false | true | false | false |
jindulys/EbloVaporServer
|
refs/heads/master
|
Sources/App/Controllers/CompanySourceController.swift
|
mit
|
1
|
//
// CompanySourceController.swift
// EbloVaporServer
//
// Created by yansong li on 2017-06-05.
//
//
import Foundation
import HTTP
import Vapor
import VaporPostgreSQL
/// Controller for Company Source
final class CompanySourceController: ResourceRepresentable {
/// Service to crawling blog.
let blogCrawlingService: BlogCrawlingService = BlogCrawlingService()
func addRoutes(drop: Droplet) {
let base = drop.grouped("companysource")
base.get("all", handler: getCompanySource)
base.get("source", handler: companySourceWebPage)
}
/// Get test blogs
func getCompanySource(request: Request) throws -> ResponseRepresentable {
return try JSON(node: CompanySource.all().makeNode())
}
/// Get all articles
func companySourceWebPage(request: Request) throws -> ResponseRepresentable {
let companySource = try CompanySource.all()
let companySourceNodes = try companySource.makeNode()
return try drop.view.make("companysource", Node(node: ["sources" : companySourceNodes]))
}
func create(request: Request) throws -> ResponseRepresentable {
var companySource = try request.companySource()
try companySource.save()
if let id = companySource.id?.int, id == 1 {
print("We have new company source")
// NOTE: We created companysource for the first time, we need to start our company parse service.
self.blogCrawlingService.startService(automaticallySaveWhenCrawlingFinished: true)
}
return companySource
}
func show(request: Request, companySource: CompanySource) throws -> ResponseRepresentable {
return companySource
}
func update(request: Request, companySource: CompanySource) throws -> ResponseRepresentable {
let new = try request.companySource()
var companySource = companySource
companySource.companyDataURLString = new.companyDataURLString
try companySource.save()
if let id = companySource.id?.int, id == 1 {
print("We have updated company source")
self.blogCrawlingService.startService(automaticallySaveWhenCrawlingFinished: true)
}
return companySource
}
func delete(request: Request, companySource: CompanySource) throws -> ResponseRepresentable {
try companySource.delete()
return JSON([:])
}
func makeResource() -> Resource<CompanySource> {
return Resource(
index: getCompanySource,
store: create,
show: show,
modify: update,
destroy: delete
)
}
}
extension Request {
func companySource() throws -> CompanySource {
guard let json = json else {
throw Abort.badRequest
}
return try CompanySource(node: json)
}
}
|
ed5952a315abcef80788ae9e81324bd7
| 29.261364 | 103 | 0.713481 | false | false | false | false |
AnarchyTools/atbuild
|
refs/heads/master
|
attools/src/atllbuild.swift
|
apache-2.0
|
1
|
// Copyright (c) 2016 Anarchy Tools Contributors.
//
// 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 atfoundation
import atpkg
/**Synthesize a module map.
- parameter name: The name of the module to synthesize
- parameter umbrellaHeader: A path to the umbrella header. The path must be relative to the exported module map file.
- parameter headers: A list of headers to import. The path must be relative to the exported module map file.
- returns String contents of the synthesized modulemap
*/
private func synthesizeModuleMap(name: String, umbrellaHeader: String?, headers: [String], link: [String]) -> String {
var s = ""
s += "module \(name) {\n"
if let u = umbrellaHeader {
s += " umbrella header \"\(u)\"\n"
}
for header in headers {
s += " header \"\(header)\"\n"
}
for l in link {
s += " link \"\(l)\"\n"
}
s += "\n"
s += "}\n"
return s
}
private struct Atbin {
let manifest: Package
let path: Path
var name: String { return manifest.name }
init(path: Path) {
self.path = path
self.manifest = try! Package(filepath: path.appending("compiled.atpkg"), overlay: [], focusOnTask: nil)
}
var linkDirective: String {
return path.appending(self.manifest.payload!).description
}
var moduleName: String {
let n = self.manifest.payload!
if n.hasSuffix(".a") {
return n.subString(toIndex: n.characters.index(n.characters.endIndex, offsetBy: -2))
}
if n.hasSuffix(".dylib") {
return n.subString(toIndex: n.characters.index(n.characters.endIndex, offsetBy: -6))
}
if n.hasSuffix(".so") {
return n.subString(toIndex: n.characters.index(n.characters.endIndex, offsetBy: -3))
}
fatalError("Unknown payload \(n)")
}
var swiftModule: Path? {
let modulePath = self.path + (Platform.targetPlatform.description + ".swiftmodule")
if FS.fileExists(path: modulePath) { return modulePath }
return nil
}
var clangModule: Path? {
let modulePath = self.path + "module.modulemap"
if FS.fileExists(path: modulePath) { return modulePath }
return nil
}
var swiftDoc: Path? {
let docPath = Path(Platform.targetPlatform.description + ".swiftDoc")
if FS.fileExists(path: docPath) { return docPath }
return nil
}
}
/**The ATllbuild tool builds a swift module via llbuild.
For more information on this tool, see `docs/attllbuild.md` */
final class ATllbuild : Tool {
/**We inject this sourcefile in xctestify=true on OSX
On Linux, the API requires you to explicitly list tests
which is not required on OSX. Injecting this file into test targets
will enforce that API on OSX as well */
private static let xcTestCaseProvider: String = { () -> String in
var s = ""
s += "import XCTest\n"
s += "public func testCase<T: XCTestCase>(_ allTests: [(String, (T) -> () throws -> Void)]) -> XCTestCase {\n"
s += " fatalError(\"Can't get here.\")\n"
s += "}\n"
s += "\n"
s += "public func XCTMain(_ testCases: [XCTestCase]) {\n"
s += " fatalError(\"Can't get here.\")\n"
s += "}\n"
s += "\n"
return s
}()
enum OutputType: String {
case Executable = "executable"
case StaticLibrary = "static-library"
case DynamicLibrary = "dynamic-library"
}
enum ModuleMapType {
case None
case Synthesized
}
/**
* Calculates the llbuild.yaml contents for the given configuration options
* - parameter swiftSources: A resolved list of swift sources
* - parameter workdir: A temporary working directory for `atllbuild` to use
* - parameter modulename: The name of the module to be built.
* - parameter executableName: The name of the executable to be built. Typically the same as the module name.
* - parameter enableWMO: Whether to use `enable-whole-module-optimization`, see https://github.com/aciidb0mb3r/swift-llbuild/blob/cfd7aa4e6e14797112922ae12ae7f3af997a41c6/docs/buildsystem.rst
* - returns: The string contents for llbuild.yaml suitable for processing by swift-build-tool
*/
private func llbuildyaml(swiftSources: [Path], cSources: [Path], workdir: Path, modulename: String, linkSDK: Bool, compileOptions: [String], cCompileOptions: [String], linkOptions: [String], outputType: OutputType, linkWithProduct:[String], linkWithAtbin:[Atbin], swiftCPath: Path, executableName: String, enableWMO: Bool) -> String {
let productPath = workdir.appending("products")
//this format is largely undocumented, but I reverse-engineered it from SwiftPM.
var yaml = "client:\n name: swift-build\n\n"
yaml += "tools: {}\n\n"
yaml += "targets:\n"
yaml += " \"\": [<atllbuild>]\n"
yaml += " atllbuild: [<atllbuild>]\n"
//this is the "compile" command
yaml += "commands:\n"
yaml += " <atllbuild-swiftc>:\n"
yaml += " tool: swift-compiler\n"
yaml += " executable: \"\(swiftCPath)\"\n"
let inputs = String.join(parts: swiftSources.map { path in path.description }, delimiter: "\", \"")
yaml += " inputs: [\"\(inputs)\"]\n"
yaml += " sources: [\"\(inputs)\"]\n"
//swiftPM wants "objects" which is just a list of %.swift.o files. We have to put them in a temp directory though.
var objects = swiftSources.map { (source) -> String in
workdir.appending("objects").appending(source.basename() + ".o").description
}
yaml += " objects: \(objects)\n"
//this crazy syntax is how llbuild specifies outputs
var llbuild_outputs = ["<atllbuild-swiftc>"]
llbuild_outputs.append(contentsOf: objects)
yaml += " outputs: \(llbuild_outputs)\n"
yaml += " enable-whole-module-optimization: \(enableWMO ? "true" : "false")\n"
yaml += " num-threads: 8\n"
switch(outputType) {
case .Executable:
break
case .StaticLibrary, .DynamicLibrary:
yaml += " is-library: true\n" //I have no idea what the effect of this is, but swiftPM does it, so I'm including it.
}
yaml += " module-name: \(modulename)\n"
let swiftModulePath = productPath.appending(modulename + ".swiftmodule")
yaml += " module-output-path: \(swiftModulePath)\n"
yaml += " temps-path: \(workdir)/llbuildtmp\n"
var args : [String] = []
args += ["-j8", "-D", "ATBUILD", "-I", workdir.appending("products").description + "/"]
if linkSDK {
if let sdkPath = Platform.targetPlatform.sdkPath {
if swiftCPath.description.contains(string: "Xcode.app") {
//evil evil hack
args += ["-sdk",sdkPath]
}
else { args += ["-sdk", sdkPath] }
}
}
args += compileOptions
yaml += " other-args: \(args)\n"
var llbuild_inputs = ["<atllbuild-swiftc>"]
//the "C" commands
for source in cSources {
let cmdName = "<atllbuild-\(source.basename().split(character: ".")[0])>"
yaml += " \(cmdName):\n"
yaml += " tool: shell\n"
yaml += " inputs: [\"\(source)\"]\n"
let c_object = workdir.appending("objects").appending(source.basename() + ".o").description
yaml += " outputs: [\"\(c_object)\"]\n"
var cargs = ["clang","-c",source.description,"-o",c_object]
cargs += cCompileOptions
yaml += " args: \(cargs)\n"
//add c_objects to our link step
objects += [c_object]
llbuild_inputs += [cmdName]
}
//and this is the "link" command
yaml += " <atllbuild>:\n"
switch(outputType) {
case .Executable:
yaml += " tool: shell\n"
//this crazy syntax is how sbt declares a dependency
llbuild_inputs += objects
var builtProducts = linkWithProduct.map { (workdir + ("products/"+$0)).description }
builtProducts += linkWithAtbin.map {$0.linkDirective}
llbuild_inputs += builtProducts
let executablePath = productPath.appending(executableName)
yaml += " inputs: \(llbuild_inputs)\n"
yaml += " outputs: [\"<atllbuild>\", \"\(executablePath)\"]\n"
//and now we have the crazy 'args'
args = [swiftCPath.description, "-o", executablePath.description]
args += objects
args += builtProducts
args += linkOptions
yaml += " args: \(args)\n"
yaml += " description: Linking executable \(executablePath)\n"
return yaml
case .StaticLibrary:
yaml += " tool: shell\n"
llbuild_inputs.append(contentsOf: objects)
yaml += " inputs: \(llbuild_inputs)\n"
let libPath = productPath.appending(modulename + ".a")
yaml += " outputs: [\"<atllbuild>\", \"\(libPath)\"]\n"
//build the crazy args, mostly consisting of an `ar` shell command
var shellCmd = "rm -rf \(libPath); ar cr '\(libPath)'"
for obj in objects {
shellCmd += " '\(obj)'"
}
let args = "[\"/bin/sh\",\"-c\",\(shellCmd)]"
yaml += " args: \(args)\n"
yaml += " description: \"Linking Library: \(libPath)\""
return yaml
case .DynamicLibrary:
yaml += " tool: shell\n"
llbuild_inputs += objects
var builtProducts = linkWithProduct.map { (workdir + ("products/"+$0)).description }
builtProducts += linkWithAtbin.map {$0.linkDirective}
llbuild_inputs += builtProducts
yaml += " inputs: \(llbuild_inputs)\n"
let libPath = productPath.appending(modulename + Platform.targetPlatform.dynamicLibraryExtension)
yaml += " outputs: [\"<atllbuild>\", \"\(libPath)\"]\n"
var args = [swiftCPath.description, "-o", libPath.description, "-emit-library"]
args += objects
args += builtProducts
args += linkOptions
yaml += " args: \(args)\n"
yaml += " description: \"Linking Library: \(libPath)\""
return yaml
}
}
enum Options: String {
case Tool = "tool"
case Name = "name"
case Dependencies = "dependencies"
case OutputType = "output-type"
case Source = "sources"
case BootstrapOnly = "bootstrap-only"
case llBuildYaml = "llbuildyaml"
case CompileOptions = "compile-options"
case CCompileOptions = "c-compile-options"
case LinkOptions = "link-options"
case LinkSDK = "link-sdk"
case LinkWithProduct = "link-with-product"
case LinkWithAtbin = "link-with-atbin"
case XCTestify = "xctestify"
case XCTestStrict = "xctest-strict"
case IncludeWithUser = "include-with-user"
case PublishProduct = "publish-product"
case UmbrellaHeader = "umbrella-header"
case ModuleMap = "module-map"
case ModuleMapLink = "module-map-link"
case WholeModuleOptimization = "whole-module-optimization"
case Framework = "framework"
case ExecutableName = "executable-name"
case Bitcode = "bitcode"
case Magic = "magic"
case DeploymentTarget = "deployment-target"
static var allOptions : [Options] {
return [
Name,
Dependencies,
OutputType,
Source,
BootstrapOnly,
llBuildYaml,
CompileOptions,
CCompileOptions,
LinkOptions,
LinkSDK,
LinkWithProduct,
LinkWithAtbin,
XCTestify,
XCTestStrict,
IncludeWithUser,
PublishProduct,
UmbrellaHeader,
ModuleMap,
ModuleMapLink,
WholeModuleOptimization,
Framework,
ExecutableName,
Bitcode,
Magic,
DeploymentTarget
]
}
}
func run(task: Task) {
//warn if we don't understand an option
var knownOptions = Options.allOptions.map({$0.rawValue})
for option in Task.Option.allOptions.map({$0.rawValue}) {
knownOptions.append(option)
}
for key in task.allKeys {
if !knownOptions.contains(key) {
print("Warning: unknown option \(key) for task \(task.qualifiedName)")
}
}
//create the working directory
let workDirectory = Path(".atllbuild")
//NSFileManager is pretty anal about throwing errors if we try to remove something that doesn't exist, etc.
//We just want to create a state where .atllbuild/objects and .atllbuild/llbuildtmp and .atllbuild/products exists.
//and in particular, without erasing the product directory, since that accumulates build products across
//multiple invocations of atllbuild.
if CommandLine.arguments.contains("--clean") {
let _ = try? FS.removeItem(path: workDirectory.appending("objects"), recursive: true)
let _ = try? FS.removeItem(path: workDirectory.appending("llbuildtmp"), recursive: true)
}
let _ = try? FS.removeItem(path: workDirectory.appending("include"), recursive: true)
let _ = try? FS.createDirectory(path: workDirectory)
let _ = try? FS.createDirectory(path: workDirectory.appending("products"))
let _ = try? FS.createDirectory(path: workDirectory.appending("objects"))
let _ = try? FS.createDirectory(path: workDirectory.appending("include"))
///MARK: parse arguments
var linkWithProduct: [String] = []
if let arr_ = task[Options.LinkWithProduct.rawValue] {
guard let arr = arr_.vector else {
fatalError("Non-vector link directive \(arr_)")
}
for product in arr {
guard var p = product.string else { fatalError("non-string product \(product)") }
if p.hasSuffix(".dynamic") {
p.replace(searchTerm: ".dynamic", replacement: Platform.targetPlatform.dynamicLibraryExtension)
}
linkWithProduct.append(p)
}
}
///DEPRECATED PRODUCT CHECK
if let arr_ = task["link-with"] {
print("Warning: link-with is deprecated; please use link-with-product or link-with-atbin")
sleep(5)
guard let arr = arr_.vector else {
fatalError("Non-vector link directive \(arr_)")
}
for product in arr {
guard var p = product.string else { fatalError("non-string product \(product)") }
if p.hasSuffix(".dynamic") {
p.replace(searchTerm: ".dynamic", replacement: Platform.targetPlatform.dynamicLibraryExtension)
}
linkWithProduct.append(p)
}
}
var linkWithAtbin: [Atbin] = []
if let arr_ = task[Options.LinkWithAtbin.rawValue] {
guard let arr = arr_.vector else {
fatalError("Non-vector link directive \(arr_)")
}
for product in arr {
guard var p = product.string else { fatalError("non-string product \(product)") }
linkWithAtbin.append(Atbin(path: task.importedPath.appending(p)))
}
}
guard case .some(.StringLiteral(let outputTypeString)) = task[Options.OutputType.rawValue] else {
fatalError("No \(Options.OutputType.rawValue) for task \(task)")
}
guard let outputType = OutputType(rawValue: outputTypeString) else {
fatalError("Unknown \(Options.OutputType.rawValue) \(outputTypeString)")
}
var compileOptions: [String] = []
if let opts = task[Options.CompileOptions.rawValue]?.vector {
for o in opts {
guard let os = o.string else { fatalError("Compile option \(o) is not a string") }
compileOptions.append(os)
}
}
var cCompileOptions: [String] = []
if let opts = task[Options.CCompileOptions.rawValue]?.vector {
for o in opts {
guard let os = o.string else { fatalError("C compile option \(o) is not a string")}
cCompileOptions.append(os)
}
}
//copy the atbin module / swiftdoc into our include directory
let includeAtbinPath = workDirectory + "include/atbin"
let _ = try? FS.createDirectory(path: includeAtbinPath, intermediate: true)
for atbin in linkWithAtbin {
if let path = atbin.swiftModule {
try! FS.copyItem(from: path, to: Path("\(includeAtbinPath)/\(atbin.moduleName).swiftmodule"))
}
}
if linkWithAtbin.count > 0 { compileOptions.append(contentsOf: ["-I",includeAtbinPath.description])}
if let includePaths = task[Options.IncludeWithUser.rawValue]?.vector {
for path_s in includePaths {
guard let path = path_s.string else { fatalError("Non-string path \(path_s)") }
compileOptions.append("-I")
compileOptions.append((userPath() + path).description)
}
}
var linkOptions: [String] = []
if let opts = task[Options.LinkOptions.rawValue]?.vector {
for o in opts {
guard let os = o.string else { fatalError("Link option \(o) is not a string") }
linkOptions.append(os)
}
}
let bitcode: Bool
//do we have an explicit bitcode setting?
if let b = task[Options.Bitcode.rawValue] {
bitcode = b.bool!
}
else {
bitcode = false
}
//separate sources
guard let sourceDescriptions = task[Options.Source.rawValue]?.vector?.flatMap({$0.string}) else { fatalError("Can't find sources for atllbuild.") }
var sources = collectSources(sourceDescriptions: sourceDescriptions, taskForCalculatingPath: task)
let cSources = sources.filter({$0.description.hasSuffix(".c")})
//todo: enable by default for iOS, but we can't due to SR-1493
if bitcode {
compileOptions.append("-embed-bitcode")
linkOptions.append(contentsOf: ["-embed-bitcode"])
if cSources.count > 0 {
print("Warning: bitcode is not supported for C sources")
}
}
//check for modulemaps
/*per http://clang.llvm.org/docs/Modules.html#command-line-parameters, pretty much
the only way to do this is to create a file called `module.modulemap`. That
potentially conflicts with other modulemaps, so we give it its own directory, namespaced
by the product name. */
func installModuleMap(moduleMapPath: Path, productName: String) {
let includePathName = workDirectory + "include/\(productName)"
let _ = try? FS.createDirectory(path: includePathName, intermediate: true)
do {
try FS.copyItem(from: moduleMapPath, to: includePathName.appending("module.modulemap"))
} catch {
fatalError("Could not copy modulemap to \(includePathName): \(error)")
}
compileOptions.append(contentsOf: ["-I", includePathName.description])
}
for product in linkWithProduct {
let productName = product.split(character: ".")[0]
let moduleMapPath = workDirectory + "products/\(productName).modulemap"
if FS.fileExists(path: moduleMapPath) {
installModuleMap(moduleMapPath: moduleMapPath, productName: productName)
}
}
for product in linkWithAtbin {
if let moduleMapPath = product.clangModule {
installModuleMap(moduleMapPath: moduleMapPath, productName: product.name)
}
}
//xctestify
if task[Options.XCTestify.rawValue]?.bool == true {
precondition(outputType == .Executable, "You must use :\(Options.OutputType.rawValue) executable with xctestify.")
//inject platform-specific flags
switch(Platform.targetPlatform) {
case .OSX:
compileOptions.append(contentsOf: ["-F", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/"])
linkOptions.append(contentsOf: ["-F", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/", "-target", "x86_64-apple-macosx10.11", "-Xlinker", "-rpath", "-Xlinker", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/", "-Xlinker", "-bundle"])
case .Linux:
break
case .iOS, .iOSGeneric:
fatalError("\(Options.XCTestify.rawValue) is not supported for iOS")
}
}
if task[Options.XCTestStrict.rawValue]?.bool == true {
switch Platform.targetPlatform {
case .OSX:
//inject XCTestCaseProvider.swift
do {
let xcTestCaseProviderPath = try FS.temporaryDirectory(prefix: "XCTestCase")
do {
try ATllbuild.xcTestCaseProvider.write(to: xcTestCaseProviderPath.appending("XCTestCaseProvider.swift"))
sources.append(xcTestCaseProviderPath.appending("XCTestCaseProvider.swift"))
} catch {
print(xcTestCaseProviderPath)
fatalError("Could not inject XCTestCaseProvider: \(error)")
}
} catch {
fatalError("Could not create temp dir for XCTestCaseProvider: \(error)")
}
case .Linux:
break
case .iOS, .iOSGeneric:
fatalError("\(Options.XCTestStrict.rawValue) is not supported for iOS")
}
}
let moduleMap: ModuleMapType
if task[Options.ModuleMap.rawValue]?.string == "synthesized" {
moduleMap = .Synthesized
}
else {
moduleMap = .None
}
guard let name = task[Options.Name.rawValue]?.string else { fatalError("No name for atllbuild task") }
let executableName: String
if let e = task[Options.ExecutableName.rawValue]?.string {
precondition(outputType == .Executable, "Must use \(Options.OutputType.rawValue) 'executable' when using \(Options.ExecutableName.rawValue)")
executableName = e
}
else { executableName = name }
if task[Options.Framework.rawValue]?.bool == true {
#if !os(OSX)
fatalError("\(Options.Framework.rawValue) is not supported on this host.")
#endif
linkOptions.append("-Xlinker")
linkOptions.append("-install_name")
linkOptions.append("-Xlinker")
switch(Platform.targetPlatform) {
case .OSX:
linkOptions.append("@rpath/\(name).framework/Versions/A/\(name)")
case .iOS(let arch):
linkOptions.append("@rpath/\(name).framework/\(name)")
default:
fatalError("\(Options.Framework.rawValue) not supported when targeting \(Platform.targetPlatform)")
}
}
let hSources = sources.filter({$0.description.hasSuffix(".h")}).map({$0.description})
let umbrellaHeader = task[Options.UmbrellaHeader.rawValue]?.string
var moduleMapLinks: [String] = []
if let links = task[Options.ModuleMapLink.rawValue]?.vector {
precondition(moduleMap == .Synthesized, ":\(Options.ModuleMap.rawValue) \"synthesized\" must be used with the \(Options.ModuleMapLink.rawValue) option")
for link in links {
guard case .StringLiteral(let l) = link else {
fatalError("Non-string \(Options.ModuleMapLink.rawValue) \(link)")
}
moduleMapLinks.append(l)
}
}
if hSources.count > 0 || umbrellaHeader != nil { //we need to import the underlying module
precondition(moduleMap == .Synthesized, ":\(Options.ModuleMap.rawValue) \"synthesized\" must be used with the \(Options.UmbrellaHeader.rawValue) option or when compiling C headers")
let umbrellaHeaderArg: String?
if umbrellaHeader != nil { umbrellaHeaderArg = "Umbrella.h" } else {umbrellaHeaderArg = nil}
//add ../../ to hsources to get out from inside workDirectory/include
let relativeHSources = hSources.map({"../../" + $0})
let s = synthesizeModuleMap(name: name, umbrellaHeader: umbrellaHeaderArg, headers: relativeHSources, link: moduleMapLinks)
do {
try s.write(to: workDirectory + "include/module.modulemap")
if let u = umbrellaHeader {
try FS.copyItem(from: task.importedPath + u, to: workDirectory + "include/Umbrella.h")
}
} catch {
fatalError("Could not synthesize module map during build: \(error)")
}
compileOptions.append("-I")
compileOptions.append(workDirectory.appending("include").description + "/")
compileOptions.append("-import-underlying-module")
}
//inject target
switch(Platform.targetPlatform) {
case .iOS(let arch):
let deploymentTarget: String
if let _deploymentTarget = task[Options.DeploymentTarget.rawValue]?.string {
deploymentTarget = _deploymentTarget
}
else {
deploymentTarget = Platform.targetPlatform.standardDeploymentTarget
}
let targetTuple = ["-target",Platform.targetPlatform.nonDeploymentTargetTargetTriple + deploymentTarget]
compileOptions.append(contentsOf: targetTuple)
linkOptions.append(contentsOf: targetTuple)
cCompileOptions.append(contentsOf: targetTuple)
cCompileOptions.append(contentsOf: ["-isysroot",Platform.targetPlatform.sdkPath!])
linkOptions.append(contentsOf: ["-Xlinker", "-syslibroot","-Xlinker",Platform.targetPlatform.sdkPath!])
case .OSX:
//we require sysroot
cCompileOptions.append(contentsOf: ["-isysroot",Platform.targetPlatform.sdkPath!])
//deployment target
let deploymentTarget: String
if let _deploymentTarget = task[Options.DeploymentTarget.rawValue]?.string {
deploymentTarget = _deploymentTarget
}
else {
deploymentTarget = Platform.targetPlatform.standardDeploymentTarget
}
let targetTuple = ["-target",Platform.targetPlatform.nonDeploymentTargetTargetTriple + deploymentTarget]
compileOptions.append(contentsOf: targetTuple)
linkOptions.append(contentsOf: targetTuple)
cCompileOptions.append(contentsOf: targetTuple)
case .Linux:
break //not required
case .iOSGeneric:
fatalError("Generic platform iOS cannot be used with atllbuild; choose a specific platform or use atbin")
}
let bootstrapOnly: Bool
if task[Options.BootstrapOnly.rawValue]?.bool == true {
bootstrapOnly = true
//update the build platform to be the one passed on the CLI
Platform.buildPlatform = Platform.targetPlatform
}
else {
bootstrapOnly = false
}
///The next task will not be bootstrapped.
defer { Platform.buildPlatform = Platform.hostPlatform }
let sdk: Bool
if task[Options.LinkSDK.rawValue]?.bool == false {
sdk = false
}
else { sdk = true }
let llbuildyamlpath : Path
if let value = task[Options.llBuildYaml.rawValue]?.string {
llbuildyamlpath = Path(value)
}
else {
llbuildyamlpath = workDirectory.appending("llbuild.yaml")
}
let swiftCPath = findToolPath(toolName: "swiftc")
var enableWMO: Bool
if let wmo = task[Options.WholeModuleOptimization.rawValue]?.bool {
enableWMO = wmo
//we can't deprecate WMO due to a bug in swift-preview-1 that prevents it from being useable in some cases on Linux
}
else { enableWMO = false }
// MARK: Configurations
if currentConfiguration.testingEnabled == true {
compileOptions.append("-enable-testing")
}
//"stripped" is implemented as "included" here, that is a bug
//see https://github.com/AnarchyTools/atbuild/issues/73
if currentConfiguration.debugInstrumentation == .Included || currentConfiguration.debugInstrumentation == .Stripped {
compileOptions.append("-g")
cCompileOptions.append("-g")
}
if currentConfiguration.optimize == true {
compileOptions.append("-O")
cCompileOptions.append("-Os")
switch(Platform.buildPlatform) {
case .Linux:
//don't enable WMO on Linux
//due to bug in swift-preview-1
break
default:
enableWMO = true
}
}
if task[Options.Magic.rawValue] != nil {
print("Warning: Magic is deprecated. Please migrate to --configuration none. If --configuration none won't work for your usecase, file a bug at https://github.com/AnarchyTools/atbuild/issues")
sleep(5)
}
if currentConfiguration.fastCompile==false && task[Options.Magic.rawValue]?.bool != false {
switch(Platform.buildPlatform) {
case .OSX:
linkOptions.append(contentsOf: ["-Xlinker","-dead_strip"])
default:
break
}
}
switch(currentConfiguration) {
case .Debug:
compileOptions.append("-DATBUILD_DEBUG")
cCompileOptions.append("-DATBUILD_DEBUG")
case .Release:
compileOptions.append("-DATBUILD_RELEASE")
cCompileOptions.append("-DATBUILD_RELEASE")
case .Benchmark:
compileOptions.append("-DATBUILD_BENCH")
cCompileOptions.append("-DATBUILD_BENCH")
case .Test:
compileOptions.append("-DATBUILD_TEST")
cCompileOptions.append("-DATBUILD_TEST")
case .None:
break //too much magic to insert an arg in this case
case .User(let str):
compileOptions.append("-DATBUILD_\(str)")
cCompileOptions.append("-DATBUILD_\(str)")
}
// MARK: emit llbuildyaml
//separate sources
let swiftSources = sources.filter({$0.description.hasSuffix(".swift")})
if hSources.count > 0 {
precondition(moduleMap == .Synthesized,"Use :\(Options.ModuleMap.rawValue) \"synthesized\" when compiling C headers")
}
let yaml = llbuildyaml(swiftSources: swiftSources,cSources: cSources, workdir: workDirectory, modulename: name, linkSDK: sdk, compileOptions: compileOptions, cCompileOptions: cCompileOptions, linkOptions: linkOptions, outputType: outputType, linkWithProduct: linkWithProduct, linkWithAtbin: linkWithAtbin, swiftCPath: swiftCPath, executableName: executableName, enableWMO: enableWMO)
let _ = try? yaml.write(to: llbuildyamlpath)
if bootstrapOnly { return }
//MARK: execute build
switch moduleMap {
case .None:
break
case .Synthesized:
// "public" modulemap
let s = synthesizeModuleMap(name: name, umbrellaHeader: nil, headers: [], link: moduleMapLinks)
do {
try s.write(to: workDirectory + "products/\(name).modulemap")
} catch {
fatalError("Could not write synthesized module map: \(error)")
}
}
let cmd = "\(findToolPath(toolName: "swift-build-tool")) -f \(llbuildyamlpath)"
anarchySystem(cmd)
if task[Options.PublishProduct.rawValue]?.bool == true {
do {
if !FS.isDirectory(path: Path("bin")) {
try FS.createDirectory(path: Path("bin"))
}
try FS.copyItem(from: workDirectory + "products/\(name).swiftmodule", to: Path("bin/\(name).swiftmodule"))
try FS.copyItem(from: workDirectory + "products/\(name).swiftdoc", to: Path("bin/\(name).swiftdoc"))
switch outputType {
case .Executable:
try FS.copyItem(from: workDirectory + "products/\(executableName)", to: Path("bin/\(executableName)"))
case .StaticLibrary:
try FS.copyItem(from: workDirectory + "products/\(name).a", to: Path("bin/\(name).a"))
case .DynamicLibrary:
try FS.copyItem(from: workDirectory + ("products/\(name)" + Platform.targetPlatform.dynamicLibraryExtension) , to: Path("bin/\(name)" + Platform.targetPlatform.dynamicLibraryExtension))
}
switch moduleMap {
case .None:
break
case .Synthesized:
try FS.copyItem(from: workDirectory + "products/\(name).modulemap", to: Path("bin/\(name).modulemap"))
}
} catch {
print("Could not publish product: \(error)")
}
}
}
}
|
10795f2e167940bd6c47f276eb7162f4
| 41.377267 | 391 | 0.58115 | false | false | false | false |
mbeloded/beaconDemo
|
refs/heads/master
|
PassKitApp/PassKitApp/Classes/UI/Widgets/BannerView/BannerView.swift
|
gpl-2.0
|
1
|
//
// BannerView.swift
// PassKitApp
//
// Created by Alexandr Chernyy on 10/3/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import UIKit
class BannerView: UIView {
@IBOutlet var bannerImage:PFImageView?
@IBOutlet var pageControl:UIPageControl?
var mall_banner_items:Array<AnyObject>!
var banner_items:Array<AnyObject> = []
var index:Int = 0
@IBOutlet weak var guest:UISwipeGestureRecognizer!
@IBOutlet weak var guest1:UISwipeGestureRecognizer!
func setupView(mall_id:String)
{
if guest != nil {
self.addGestureRecognizer(guest)
}
if guest1 != nil {
self.addGestureRecognizer(guest1)
}
mall_banner_items = CoreDataManager.sharedManager.loadData(RequestType.MALL_BANNER, key:mall_id)
for object in mall_banner_items {
var banners:Array<AnyObject> = CoreDataManager.sharedManager.loadData(RequestType.BANNER, key:(object as MallBannerModel).banner_id)
for items in banners {
banner_items.append(items)
}
}
pageControl?.numberOfPages = banner_items.count
pageControl?.pageIndicatorTintColor = UIColor.blackColor()
pageControl?.currentPageIndicatorTintColor = UIColor.lightGrayColor()
pageControl?.currentPage = index
if(banner_items.count > 0)
{
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
index++
if(index >= banner_items.count)
{
index = 0
}
pageControl?.currentPage = index
if(banner_items.count > 0)
{
//println((banner_items[0] as MallBannerModel).id)
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
}
func updateMinus() {
index--
if(index < 0)
{
index = 0
}
pageControl?.currentPage = index
if(banner_items.count > 0)
{
//println((banner_items[0] as MallBannerModel).id)
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
}
@IBAction func rightSwipeAction(sender: AnyObject) {
self.updateMinus()
}
@IBAction func leftSwipeAction(sender: AnyObject) {
self.update()
}
@IBAction func pageAction(sender:AnyObject) {
index = (sender as UIPageControl).currentPage
pageControl?.currentPage = index
if(banner_items.count > 0)
{
//println((banner_items[0] as MallBannerModel).id)
var url:NSString = (banner_items[index] as BannerModel).image!
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)");
bannerImage?.image = UIImage(named: pngPath)
}
}
}
|
a61da4465081d6cdbf333d53ba531b81
| 33.273585 | 145 | 0.615745 | false | false | false | false |
frootloops/swift
|
refs/heads/master
|
validation-test/Reflection/reflect_Int16.swift
|
apache-2.0
|
5
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Int16
// RUN: %target-run %target-swift-reflection-test %t/reflect_Int16 2>&1 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
import SwiftReflectionTest
class TestClass {
var t: Int16
init(t: Int16) {
self.t = t
}
}
var obj = TestClass(t: 123)
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int16.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=18 alignment=2 stride=18 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int16.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=10 alignment=2 stride=10 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=8
// CHECK-32: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
|
c4cfdb2a523381bac232bc38aeee946e
| 32.104167 | 124 | 0.681561 | false | true | false | false |
borland/MTGLifeCounter2
|
refs/heads/master
|
MTGLifeCounter2/PlayerViewController.swift
|
mit
|
1
|
//
// PlayerViewController.swift
// MTGLifeCounter2
//
// Created by Orion Edwards on 4/09/14.
// Copyright (c) 2014 Orion Edwards. All rights reserved.
//
import Foundation
import UIKit
enum DisplaySize {
case small, normal
}
enum PlusMinusButtonPosition { // use nil for auto
case rightLeft, // + on the right, - on the left
leftRight,
aboveBelow, // + above, - below
belowAbove
}
enum PlayerViewOrientation {
case normal, upsideDown, left, right
}
protocol PlayerViewControllerDelegate : AnyObject {
func colorDidChange(newColor:MtgColor, sender:PlayerViewController)
}
class PlayerViewController : UIViewController {
private let _tracker = LifeTotalDeltaTracker()
private var _xConstraint: NSLayoutConstraint?
private var _yConstraint: NSLayoutConstraint?
private var _currentColorPicker:RadialColorPicker?
@IBOutlet private var backgroundView: PlayerBackgroundView!
@IBOutlet private weak var lifeTotalLabel: UILabel!
@IBOutlet private weak var plusButton: UIButton!
@IBOutlet private weak var minusButton: UIButton!
// the last time layout was performed, what shape was the container (the PVC itself)
private var _lastLayoutContainerOrientation = ContainerOrientation.landscape
@IBAction private func plusButtonPressed(_ sender: AnyObject) {
lifeTotal += 1
}
@IBAction private func minusButtonPressed(_ sender: AnyObject) {
lifeTotal -= 1
}
@IBAction private func lifeTotalPanning(_ sender: UIPanGestureRecognizer) {
let translation = resolve(translation: sender.translation(in: backgroundView))
let verticalPanDivisor:CGFloat = 10.0
if translation.y < -verticalPanDivisor || translation.y > verticalPanDivisor { // vertical pan greater than threshold
lifeTotal -= Int(translation.y / verticalPanDivisor)
sender.setTranslation(CGPoint(x: 0,y: 0), in: backgroundView) // reset the recognizer
}
let horizontalPanDivisor:CGFloat = 30.0
if translation.x < -horizontalPanDivisor || translation.x > horizontalPanDivisor { // horz pan greater than threshold
let newColor = color.rawValue + Int(translation.x / horizontalPanDivisor)
if newColor < MtgColor.First().rawValue { // wrap
color = MtgColor.Last()
} else if newColor > MtgColor.Last().rawValue {
color = MtgColor.First()
} else if let x = MtgColor(rawValue: newColor) {
color = x
}
sender.setTranslation(CGPoint(x: 0,y: 0), in: backgroundView) // reset the recognizer
}
}
@IBAction private func lifeTotalWasTapped(_ sender: UITapGestureRecognizer) {
let location = sender.location(in: backgroundView)
let reference = backgroundView.frame
var up = true;
switch resolveButtonPosition(for: _lastLayoutContainerOrientation) {
case .rightLeft:
up = location.x > (reference.size.width / 2)
case .leftRight:
up = location.x < (reference.size.width / 2)
case .aboveBelow:
up = location.y < (reference.size.height / 2)
case .belowAbove:
up = location.y > (reference.size.height / 2)
}
if(up) {
plusButtonPressed(sender)
} else {
minusButtonPressed(sender)
}
}
@IBAction private func viewWasLongPressed(_ sender: UILongPressGestureRecognizer) {
if _currentColorPicker != nil {
return
}
let radialHostView = RadialHostView.locate(sender.view!)
let topView = self.view.window! // MUST be on screen or crash means a bug
let size = CGFloat(300)
let half = size/2
let location = sender.location(in: topView)
let x = min(topView.frame.width - size, max(0, location.x - half))
let y = min(topView.frame.height - size, max(20, location.y - half))
let closePicker:((RadialColorPicker) -> Void) = { picker in
self._currentColorPicker = nil
UIView.animate(
withDuration: 0.2,
animations: { picker.alpha = 0.0 },
completion: { _ in
picker.removeFromSuperview()
radialHostView?.activePicker = nil
})
}
let picker = RadialColorPicker(frame: CGRect(x: x, y: y, width: size, height: size)) { picker, color in
if let c = color { self.color = c }
closePicker(picker)
}
_currentColorPicker = picker
radialHostView?.activePicker = picker
picker.alpha = 0.0
topView.addSubview(picker)
picker.becomeFirstResponder()
UIView.animate(withDuration: 0.2) { picker.alpha = 1.0 }
}
weak var delegate:PlayerViewControllerDelegate?
var buttonPosition:PlusMinusButtonPosition? // nil means "figure it out"
var innerHorizontalOffset = CGFloat(0) {
didSet {
_xConstraint?.constant = innerHorizontalOffset
}
}
var innerVerticalOffset = CGFloat(0) {
didSet {
_yConstraint?.constant = innerHorizontalOffset
}
}
var color = MtgColor.white {
didSet {
refreshColors()
}
}
func refreshColors() {
backgroundView.setBackgroundToColors(color)
if(color == MtgColor.white) {
textColor = UIColor(red: 0.2, green:0.2, blue:0.2, alpha:1.0)
} else {
textColor = UIColor.white
}
backgroundView.addLabel(color.displayName, isUpsideDown: false, textColor: textColor)
delegate?.colorDidChange(newColor: color, sender: self)
}
var textColor:UIColor {
get {
if let x = lifeTotalLabel {
return x.textColor
}
return UIColor.white
}
set(color) {
guard let l = lifeTotalLabel, let plus = plusButton, let minus = minusButton else { return }
UIView.transition(with: l, duration: 0.25, options: .transitionCrossDissolve, animations: {
l.textColor = color
}, completion: nil)
plus.setTitleColor(color, for: UIControl.State())
minus.setTitleColor(color, for: UIControl.State())
}
}
var lifeTotal = 0 {
didSet {
_tracker.update(lifeTotal)
if let x = lifeTotalLabel {
x.text = "\(lifeTotal)"
}
}
}
func resetLifeTotal(_ lifeTotal:Int) {
_tracker.reset(lifeTotal) // do this first to avoid "+0" flash on load
self.lifeTotal = lifeTotal
}
func reset(lifeTotal:NSNumber?, color:NSNumber?) {
if let lt = lifeTotal,
let x = color,
let col = MtgColor(rawValue: x.intValue)
{
self.resetLifeTotal(lt.intValue)
self.color = col
}
}
var displaySize: DisplaySize = .normal {
didSet {
let windowSize = UIScreen.main.bounds
let screenSize = min(windowSize.width, windowSize.height)
// scale down more on an iPad because it doesn't quite work as nicely as math would like (the 4:3 ratio messes the maths up a little)
// we should probably do this based on the screen RATIO rather than size, but I don't care about iPhone 4S
let divisor:CGFloat = screenSize > 450 ? 4 : 3
let majorFontSize = screenSize / divisor
let minorFontSize = min(windowSize.width, windowSize.height) / 8 // for tracker view
if let lifeTotalLabel = lifeTotalLabel {
lifeTotalLabel.font = lifeTotalLabel.font.withSize(displaySize == .normal ? majorFontSize : majorFontSize / 1.5)
let pmFont = lifeTotalLabel.font.withSize(lifeTotalLabel.font.pointSize / 2.0)
plusButton?.titleLabel?.font = pmFont
minusButton?.titleLabel?.font = pmFont
}
_tracker.floatingViewFontSize = displaySize == .normal ? minorFontSize : minorFontSize / 1.5
}
}
var orientation: PlayerViewOrientation = .normal {
didSet {
// we only rotate the text; all the other stuff is taken care of manually, because
// if we rotate the background view by 90 degrees, auto-layout clips it and it looks broken
let xform: CGAffineTransform
switch orientation {
case .upsideDown:
xform = CGAffineTransform.identity.rotated(by: .pi)
case .left:
xform = CGAffineTransform.identity.rotated(by: .pi / 2)
case .right:
xform = CGAffineTransform.identity.rotated(by: -.pi / 2)
case .normal:
xform = CGAffineTransform.identity
}
lifeTotalLabel.transform = xform
plusButton.transform = xform
minusButton.transform = xform
_tracker.orientation = orientation
switch orientation {
case .normal:
_tracker.attachPosition = .topLeft(view.topAnchor, view.leftAnchor)
case .upsideDown:
_tracker.attachPosition = .bottomRight(view.bottomAnchor, view.rightAnchor)
case .left:
_tracker.attachPosition = .topRight(view.topAnchor, view.rightAnchor)
case .right:
_tracker.attachPosition = .bottomLeft(view.bottomAnchor, view.leftAnchor)
}
}
}
var isDiceRollWinner: Bool = false {
didSet {
if oldValue == isDiceRollWinner {
return // pointless update
}
// if true, we show our life total in yellow, to indicate we won the dice roll, until such time as someone changes a life total or brings up the color switcher
// note that diceRollWinner is NOT persisted so if we back out/in it's lost too, which is on purpose
if isDiceRollWinner {
self.textColor = UIColor.yellow
} else {
refreshColors() // put it back to non-yellow
}
}
}
override func viewDidLoad() {
// trigger all the property change callbacks
lifeTotal = self.lifeTotal + 0
orientation = self.orientation == .normal ? .normal : self.orientation
displaySize = self.displaySize == .normal ? .normal : .small
let maxColorNum = UInt32(MtgColor.Last().rawValue)
if let x = MtgColor(rawValue: Int(arc4random_uniform(maxColorNum))) {
color = x // likely to get overwritten by config load
}
_tracker.parent = backgroundView // now the tracker can use the parent
}
override func viewDidLayoutSubviews() {
_lastLayoutContainerOrientation = view.bounds.size.orientation
setConstraints(for: _lastLayoutContainerOrientation)
super.viewDidLayoutSubviews()
}
func setConstraints(for containerOrientation: ContainerOrientation) {
let constraints = backgroundView.constraints as [NSLayoutConstraint]
backgroundView.removeAllConstraints(
constraints.affectingView(plusButton),
constraints.affectingView(minusButton),
constraints.affectingView(lifeTotalLabel))
let views:[String : UIView] = ["view":backgroundView!, "plus":plusButton!, "minus":minusButton!, "lifeTotal":lifeTotalLabel!]
_xConstraint = lifeTotalLabel.centerXAnchor.constraint(equalTo: backgroundView.centerXAnchor, constant: innerHorizontalOffset)
_yConstraint = lifeTotalLabel.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor, constant: innerVerticalOffset)
backgroundView.addConstraints([_xConstraint!, _yConstraint!])
let position = resolveButtonPosition(for: containerOrientation)
switch position {
case .rightLeft, .leftRight: // +/- on the sides
let hGap:CGFloat = displaySize == .small ? 0 : 8 // in a horizontal star, pull the +/- buttons closer
let metrics = ["hGap": hGap]
let vfl = position == .rightLeft ?
"H:[minus(56)]-(hGap)-[lifeTotal]-(hGap)-[plus(56)]" :
"H:[plus(56)]-(hGap)-[lifeTotal]-(hGap)-[minus(56)]"
backgroundView.addConstraints(vfl, views: views, metrics: metrics)
backgroundView.addConstraints([
plusButton.centerYAnchor.constraint(equalTo: lifeTotalLabel.centerYAnchor),
minusButton.centerYAnchor.constraint(equalTo: lifeTotalLabel.centerYAnchor),
])
case .aboveBelow, .belowAbove: // +/- on the top/bottom
let vGap:CGFloat
switch orientation {
case .normal, .upsideDown:
vGap = -16
case .left, .right:
vGap = 0 // if the text is rotated left or right we need to move the buttons
}
let metrics = ["vGap": vGap]
let vfl = position == .aboveBelow ?
"V:[plus(56)]-(vGap)-[lifeTotal]-(vGap)-[minus(56)]" :
"V:[minus(56)]-(vGap)-[lifeTotal]-(vGap)-[plus(56)]"
backgroundView.addConstraints(vfl, views: views, metrics: metrics)
backgroundView.addConstraints([
plusButton.centerXAnchor.constraint(equalTo: lifeTotalLabel.centerXAnchor),
minusButton.centerXAnchor.constraint(equalTo: lifeTotalLabel.centerXAnchor),
])
}
backgroundView.setNeedsDisplay()
}
func resolve(translation tx: CGPoint) -> CGPoint {
switch orientation {
case .normal:
return tx
case .upsideDown:
return CGPoint(x: -tx.x, y: -tx.y)
case .left:
return CGPoint(x: -tx.y, y: -tx.x)
case .right:
return CGPoint(x: tx.y, y: tx.x)
}
}
func resolveButtonPosition(for containerOrientation: ContainerOrientation) -> PlusMinusButtonPosition {
func resolve(position:PlusMinusButtonPosition?) -> PlusMinusButtonPosition {
if let p = position {
switch p {
case .rightLeft:
return orientation == .upsideDown ? .leftRight : .rightLeft
case .leftRight:
return orientation == .upsideDown ? .rightLeft : .leftRight
case .aboveBelow:
return orientation == .upsideDown ? .belowAbove : .aboveBelow
case .belowAbove:
return orientation == .upsideDown ? .aboveBelow : .belowAbove
}
} else { // not set, figure it out based on the view's width/height
switch containerOrientation {
case .landscape: // +/- on the sides because our view is wider than it is tall
return resolve(position: .rightLeft)
default:
return resolve(position: .aboveBelow)
}
}
}
return resolve(position: buttonPosition)
}
}
class PlayerBackgroundView : UIView {
private var _color1:UIColor = UIColor.blue
private var _color2:UIColor = UIColor.blue
private var _lastLabel:UILabel? = nil
func setBackgroundToColors(_ color:MtgColor) {
_color1 = color.lookup(true)
_color2 = color.lookup(false)
self.setNeedsDisplay()
}
func addLabel(_ text:String, isUpsideDown:Bool, textColor:UIColor) {
let labelHeight = CGFloat(20)
let labelTopOffset = CGFloat(20)
let label = UILabel(frame:
CGRect(x: 0, y: labelTopOffset, width: frame.width, height: labelHeight))
label.font = UIFont.boldSystemFont(ofSize: 14.0)
label.textAlignment = .center
label.text = text
label.textColor = textColor
if let last = _lastLabel {
last.removeFromSuperview()
}
_lastLabel = label
addSubview(label)
UIView.animate(withDuration: 0.5,
delay:0,
options:UIView.AnimationOptions(),
animations:{ label.alpha = 0 },
completion:{ _ in label.removeFromSuperview() })
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.saveGState()
// gradient - linear gradient because it's simpler
var r1: CGFloat = 0, g1: CGFloat = 0, b1: CGFloat = 0, a1: CGFloat = 0
var r2: CGFloat = 0, g2: CGFloat = 0, b2: CGFloat = 0, a2: CGFloat = 0
_color1.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
_color2.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
// draw a flat background rectangle as the gradient doesn't "keep going"
context?.setFillColor(_color2.cgColor)
context?.fill(rect)
//Define the gradient ----------------------
let locations:[CGFloat] = [0.0, 1.0];
let components:[CGFloat] = [r1, g1, b1, a1,
r2, g2, b2, a2 ]
let colorSpace = CGColorSpaceCreateDeviceRGB();
let gradient = CGGradient(colorSpace: colorSpace, colorComponents: components, locations: locations, count: locations.count);
//Define Gradient Positions ---------------
//Start point
let sz = max(frame.size.width, frame.size.height) * 1.3
let startCenter = CGPoint(x: 0, y: 0)
let startRadius = CGFloat(0)
//End point
let endCenter = startCenter // must be the same for a simple circle gradient
let endRadius = CGFloat(sz)
let options = CGGradientDrawingOptions(rawValue: 0)
//Generate the Image -----------------------
context?.drawRadialGradient(gradient!, startCenter: startCenter, startRadius: startRadius, endCenter: endCenter, endRadius: endRadius, options: options)
context?.restoreGState();
}
}
|
7e3feb4691978868d77b72be3ea0f13f
| 37.08998 | 171 | 0.583754 | false | false | false | false |
toshiapp/toshi-ios-client
|
refs/heads/master
|
Toshi/Controllers/Sign In/SignInHeaderView.swift
|
gpl-3.0
|
1
|
import Foundation
import UIKit
import TinyConstraints
final class SignInHeaderView: UIView {
private lazy var titleLabel: UILabel = {
let view = UILabel()
view.text = Localized.passphrase_sign_in_title
view.textAlignment = .center
view.textColor = Theme.darkTextColor
view.font = Theme.preferredTitle1()
view.adjustsFontForContentSizeCategory = true
view.numberOfLines = 0
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
titleLabel.edges(to: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
e8e3e2dc1ffe0da81cd4ee9bad82565b
| 24.827586 | 59 | 0.626168 | false | false | false | false |
jensmeder/DarkLightning
|
refs/heads/master
|
Sources/Daemon/Sources/Daemon/USBDaemonSocket.swift
|
mit
|
1
|
/**
*
* DarkLightning
*
*
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Jens Meder
*
* 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
internal final class USBDaemonSocket: Daemon {
// MARK: Constants
private static let USBMuxDPath = "/var/run/usbmuxd"
// MARK: Members
private let handle: Memory<CFSocketNativeHandle>
private let queue: DispatchQueue
private let stream: DataStream
private let state: Memory<Int>
private let newState: Int
// MARK: Init
internal required init(socket: Memory<CFSocketNativeHandle>, queue: DispatchQueue, stream: DataStream, state: Memory<Int>, newState: Int) {
self.handle = socket
self.queue = queue
self.stream = stream
self.state = state
self.newState = newState
}
// MARK: Internal
private func addr() -> sockaddr_un {
let length = USBDaemonSocket.USBMuxDPath.withCString { Int(strlen($0)) }
var addr: sockaddr_un = sockaddr_un()
addr.sun_family = sa_family_t(AF_UNIX)
_ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in
USBDaemonSocket.USBMuxDPath.withCString {
strncpy(ptr, $0, length)
}
}
return addr
}
private func configure(socketHandle: CFSocketNativeHandle) {
var on: Int = Int(true)
setsockopt(socketHandle, SOL_SOCKET, SO_NOSIGPIPE, &on, socklen_t(MemoryLayout<Int>.size))
setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(MemoryLayout<Int>.size))
setsockopt(socketHandle, SOL_SOCKET, SO_REUSEPORT, &on, socklen_t(MemoryLayout<Int>.size))
}
// MARK: Daemon
internal func start() {
if handle.rawValue == CFSocketInvalidHandle {
let socketHandle = socket(AF_UNIX, SOCK_STREAM, 0)
if socketHandle != CFSocketInvalidHandle {
configure(socketHandle: socketHandle)
var addr = self.addr()
let result = withUnsafeMutablePointer(to: &addr) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(socketHandle, $0, socklen_t(MemoryLayout.size(ofValue: addr)))
}
}
if result != CFSocketInvalidHandle {
handle.rawValue = socketHandle
stream.open(in: queue)
}
}
}
}
func stop() {
if handle.rawValue != CFSocketInvalidHandle {
stream.close()
state.rawValue = newState
handle.rawValue = CFSocketInvalidHandle
}
}
}
|
af51b26aef38b341bc022e30fc7c7625
| 34.990385 | 143 | 0.634785 | false | false | false | false |
WhisperSystems/Signal-iOS
|
refs/heads/master
|
Signal/src/ViewControllers/Attachment Keyboard/AttachmentFormatPickerView.swift
|
gpl-3.0
|
1
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
protocol AttachmentFormatPickerDelegate: class {
func didTapCamera(withPhotoCapture: PhotoCapture?)
func didTapGif()
func didTapFile()
func didTapContact()
func didTapLocation()
}
class AttachmentFormatPickerView: UICollectionView {
weak var attachmentFormatPickerDelegate: AttachmentFormatPickerDelegate?
var itemSize: CGSize = .zero {
didSet {
guard oldValue != itemSize else { return }
updateLayout()
}
}
private let collectionViewFlowLayout = UICollectionViewFlowLayout()
private var photoCapture: PhotoCapture?
init() {
super.init(frame: .zero, collectionViewLayout: collectionViewFlowLayout)
dataSource = self
delegate = self
showsHorizontalScrollIndicator = false
contentInset = UIEdgeInsets(top: 0, leading: 6, bottom: 0, trailing: 6)
backgroundColor = .clear
register(AttachmentFormatCell.self, forCellWithReuseIdentifier: AttachmentFormatCell.reuseIdentifier)
collectionViewFlowLayout.scrollDirection = .horizontal
collectionViewFlowLayout.minimumLineSpacing = 6
updateLayout()
}
deinit {
stopCameraPreview()
}
func startCameraPreview() {
guard photoCapture == nil else { return }
let photoCapture = PhotoCapture()
self.photoCapture = photoCapture
photoCapture.startVideoCapture().done { [weak self] in
self?.reloadData()
}.retainUntilComplete()
}
func stopCameraPreview() {
photoCapture?.stopCapture().retainUntilComplete()
photoCapture = nil
}
private func updateLayout() {
AssertIsOnMainThread()
guard itemSize.height > 0, itemSize.width > 0 else { return }
collectionViewFlowLayout.itemSize = itemSize
collectionViewFlowLayout.invalidateLayout()
reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
enum AttachmentType: String, CaseIterable {
case camera
case gif
case file
case contact
case location
}
// MARK: - UICollectionViewDelegate
extension AttachmentFormatPickerView: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch AttachmentType.allCases[indexPath.row] {
case .camera:
// Since we're trying to pass on our prepared capture session to
// the camera view, nil it out so we don't try and stop it here.
let photoCapture = self.photoCapture
self.photoCapture = nil
attachmentFormatPickerDelegate?.didTapCamera(withPhotoCapture: photoCapture)
case .contact:
attachmentFormatPickerDelegate?.didTapContact()
case .file:
attachmentFormatPickerDelegate?.didTapFile()
case .gif:
attachmentFormatPickerDelegate?.didTapGif()
case .location:
attachmentFormatPickerDelegate?.didTapLocation()
}
}
}
// MARK: - UICollectionViewDataSource
extension AttachmentFormatPickerView: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection sectionIdx: Int) -> Int {
return AttachmentType.allCases.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AttachmentFormatCell.reuseIdentifier, for: indexPath) as? AttachmentFormatCell else {
owsFail("cell was unexpectedly nil")
}
let type = AttachmentType.allCases[indexPath.item]
cell.configure(type: type, cameraPreview: photoCapture?.previewView)
return cell
}
}
class AttachmentFormatCell: UICollectionViewCell {
static let reuseIdentifier = "AttachmentFormatCell"
let imageView = UIImageView()
let label = UILabel()
var attachmentType: AttachmentType?
weak var cameraPreview: CapturePreviewView?
private var hasCameraAccess: Bool {
return AVCaptureDevice.authorizationStatus(for: .video) == .authorized
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = Theme.attachmentKeyboardItemBackgroundColor
clipsToBounds = true
layer.cornerRadius = 4
contentView.addSubview(imageView)
imageView.autoHCenterInSuperview()
imageView.autoSetDimensions(to: CGSize(width: 32, height: 32))
imageView.contentMode = .scaleAspectFit
label.font = UIFont.ows_dynamicTypeFootnoteClamped.ows_semiBold()
label.textColor = Theme.attachmentKeyboardItemImageColor
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
contentView.addSubview(label)
label.autoPinEdge(.top, to: .bottom, of: imageView, withOffset: 3)
label.autoPinWidthToSuperviewMargins()
// Vertically center things
let topSpacer = UILayoutGuide()
let bottomSpacer = UILayoutGuide()
contentView.addLayoutGuide(topSpacer)
contentView.addLayoutGuide(bottomSpacer)
topSpacer.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
bottomSpacer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
topSpacer.heightAnchor.constraint(equalTo: bottomSpacer.heightAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: topSpacer.bottomAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomSpacer.topAnchor).isActive = true
}
@available(*, unavailable, message: "Unimplemented")
required public init?(coder aDecoder: NSCoder) {
notImplemented()
}
public func configure(type: AttachmentType, cameraPreview: CapturePreviewView?) {
self.attachmentType = type
self.cameraPreview = cameraPreview
let imageName: String
let text: String
switch type {
case .camera:
text = NSLocalizedString("ATTACHMENT_KEYBOARD_CAMERA", comment: "A button to open the camera from the Attachment Keyboard")
imageName = "camera-outline-32"
case .contact:
text = NSLocalizedString("ATTACHMENT_KEYBOARD_CONTACT", comment: "A button to select a contact from the Attachment Keyboard")
imageName = "contact-outline-32"
case .file:
text = NSLocalizedString("ATTACHMENT_KEYBOARD_FILE", comment: "A button to select a file from the Attachment Keyboard")
imageName = "file-outline-32"
case .gif:
text = NSLocalizedString("ATTACHMENT_KEYBOARD_GIF", comment: "A button to select a GIF from the Attachment Keyboard")
imageName = "gif-outline-32"
case .location:
text = NSLocalizedString("ATTACHMENT_KEYBOARD_LOCATION", comment: "A button to select a location from the Attachment Keyboard")
imageName = "location-outline-32"
}
// The light theme images come with a background baked in, so we don't tint them.
if Theme.isDarkThemeEnabled {
imageView.setTemplateImageName(imageName, tintColor: Theme.attachmentKeyboardItemImageColor)
} else {
imageView.setImage(imageName: imageName + "-with-background")
}
label.text = text
self.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: "format-\(type.rawValue)")
showLiveCameraIfAvailable()
}
func showLiveCameraIfAvailable() {
guard case .camera? = attachmentType, hasCameraAccess else { return }
// If we have access to the camera, we'll want to show it eventually.
// Style this in prepration for that.
imageView.setTemplateImageName("camera-outline-32", tintColor: .white)
label.textColor = .white
backgroundColor = UIColor.black.withAlphaComponent(0.4)
guard let cameraPreview = cameraPreview else { return }
contentView.insertSubview(cameraPreview, belowSubview: imageView)
cameraPreview.autoPinEdgesToSuperviewEdges()
cameraPreview.contentMode = .scaleAspectFill
}
override public func prepareForReuse() {
super.prepareForReuse()
attachmentType = nil
imageView.image = nil
label.textColor = Theme.attachmentKeyboardItemImageColor
backgroundColor = Theme.attachmentKeyboardItemBackgroundColor
if let cameraPreview = cameraPreview, cameraPreview.superview == contentView {
cameraPreview.removeFromSuperview()
}
}
}
|
3b7f343ee9cdd59a7f93b1f8f068c32e
| 33.217557 | 166 | 0.687005 | false | false | false | false |
goyuanfang/SXSwiftWeibo
|
refs/heads/master
|
103 - swiftWeibo/103 - swiftWeibo/Classes/Tools/SimpleNetwork.swift
|
mit
|
1
|
//
// SimpleNetwork.swift
// SimpleNetwork
//
// Created by apple on 15/3/2.
// Copyright (c) 2015年 heima. All rights reserved.
//
import Foundation
/// 常用的网络访问方法
enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
}
class SimpleNetwork {
// 定义闭包类型,类型别名-> 首字母一定要大写
typealias Completion = (result: AnyObject?, error: NSError?) -> ()
/**
异步加载图像
:param: urlString URLstring
:param: completion 完成时的回调
*/
func requestImage(urlString:String,_ completion:Completion){
downloadImage(urlString) {(result, error) -> () in
if error != nil{
completion(result: nil, error: error)
}
else{
/// 取到图片保存在沙盒的路径 并搞出来
let path = self.fullImageCachePath(urlString)
/// 从沙盒加载到内存,这个方法可以在不需要时自动释放
var image = UIImage(contentsOfFile: path)
dispatch_async(dispatch_get_main_queue()){ () -> Void in
completion(result: image, error: nil)
}
}
}
}
/**
下载多张图片
:param: urlString 下载地址数组
:param: completion 回调
*/
func downloadImages(urls:[String], _ completion : Completion){
/// 利用调度组统一监听一组异步任务执行完毕
let grop = dispatch_group_create()
/// 遍历链接数组进入调度组
for url in urls{
dispatch_group_enter(grop)
downloadImage(url) { (result, error) -> () in
dispatch_group_leave(grop)
}
}
/// 全部执行完毕后才会调用
dispatch_group_notify(grop, dispatch_get_main_queue()) { () -> Void in
completion(result: nil, error: nil)
}
}
/**
下载图像并且保存到沙盒
:param: urlString urlString
:param: completion 完成回调
*/
func downloadImage(urlString:String, _ completion : Completion){
var path = urlString.md5
path = cachePath!.stringByAppendingPathComponent(path)
if NSFileManager.defaultManager().fileExistsAtPath(path){
// println("\(urlString) 图片已经被缓存")
completion(result: nil, error: nil)
return
}
if let url = NSURL(string: urlString){
/// 开始下载图片
self.session!.downloadTaskWithURL(url) { (location, _, error) -> Void in
if error != nil{
completion(result: nil, error: error)
return
}
/// 复制到指定位置
NSFileManager.defaultManager().copyItemAtPath(location.path!, toPath: path, error: nil) // $$$$$
completion(result: nil, error: nil)
}.resume()
}else {
let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error": "无法创建 URL"])
completion(result: nil, error: error)
}
}
/// 获取完整的URL路径
func fullImageCachePath(urlString:String) ->String{
var path = urlString.md5
return cachePath!.stringByAppendingPathComponent(path)
}
/// MARK: - 完整的图像缓存路径
/// 完整的图像缓存路径
private lazy var cachePath:String? = {
var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last as!String
path = path.stringByAppendingPathComponent(imageCachePath)
/// 这个属性是判断是否是文件夹
var isDirectory : ObjCBool = true // $$$$$
let exists = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory)
println("打印缓存地址isDirectory: \(isDirectory) exists \(exists) path: \(path)")
/// 如果文件存在并且还不是文件夹,就直接删了
if exists && !isDirectory{
NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
}
/// 创建文件夹 withIntermediateDirectories 是否智能创建文件夹
NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil, error: nil)
return path
}()
private static var imageCachePath = "com.itheima.imagecache"
private static let errorDomain = "com.dsxlocal.error"
/// 请求 JSON
///
/// :param: method HTTP 访问方法
/// :param: urlString urlString
/// :param: params 可选参数字典
/// :param: completion 完成回调
func requestJSON(method: HTTPMethod, _ urlString: String, _ params: [String: String]?, _ completion: Completion) {
// 实例化
if let request = request(method, urlString, params){
session!.dataTaskWithRequest(request, completionHandler: { (data, _, error) -> Void in
// 如果有错误,直接回调,将错误返回
if error != nil{
completion(result: nil, error: error)
return
}
let json:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil)
// 判断反序列化是否成功
if json == nil{
let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error":"反序列化失败"])
completion(result: nil, error: error)
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(result: json, error: nil)
})
}
}).resume()
return
}
let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error":"反序列化失败"])
completion(result: nil, error: error)
}
/// 返回网络访问的请求
///
/// :param: method HTTP 访问方法
/// :param: urlString urlString
/// :param: params 可选参数字典
///
/// :returns: 可选网络请求
private func request(method:HTTPMethod, _ urlString: String, _ params:[String:String]?) ->NSURLRequest?{
if urlString.isEmpty{
return nil
}
var urlStr = urlString
var req:NSMutableURLRequest?
if method == .GET{
let query = queryString(params)
if query != nil{
urlStr += "?" + query!
}
req = NSMutableURLRequest(URL: NSURL(string: urlStr)!)
}else{
if let query = queryString(params){
req = NSMutableURLRequest(URL: NSURL(string: urlStr)!)
// MARK:- 先哥
req!.HTTPMethod = method.rawValue
// lossy 是否允许松散的转换,无所谓的
req!.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
}
}
return req
}
/// 生成查询字符串
///
/// :param: params 可选字典
///
/// :returns: 拼接完成的字符串
private func queryString(params: [String: String]?) -> String? {
// 0. 判断参数
if params == nil {
return nil
}
// 涉及到数组的使用技巧
// 1. 定义一个数组
var array = [String]()
// 2. 遍历字典
for (k, v) in params! {
let str = k + "=" + v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
array.append(str)
}
return join("&", array)
}
/// 公共的初始化函数,外部就能够调用了
init() {}
private lazy var session:NSURLSession? = {
return NSURLSession.sharedSession()
}()
}
|
a7a0e94159ee9be483d75077bf349b7e
| 28.643411 | 134 | 0.519221 | false | false | false | false |
CaiMiao/CGSSGuide
|
refs/heads/master
|
DereGuide/LiveSimulator/LSResult.swift
|
mit
|
1
|
//
// LSResult.swift
// DereGuide
//
// Created by zzk on 2017/3/31.
// Copyright © 2017年 zzk. All rights reserved.
//
import Foundation
struct LSResult {
let scores: [Int]
let remainedLives: [Int]
var average: Int {
return scores.reduce(0, +) / scores.count
}
init(scores: [Int], remainedLives: [Int]) {
self.scores = scores.sorted(by: >)
self.remainedLives = remainedLives
}
func get(percent: Int) -> Int {
let index = percent * scores.count / 100
guard index > 0 else {
return scores[0]
}
return scores[index - 1]
}
func get(percent: Double, _ fromHighToLow: Bool) -> Int {
if fromHighToLow {
let index = percent * Double(scores.count) / 100
guard floor(index) > 0 else {
return scores[0]
}
return scores[Int(floor(index)) - 1]
} else {
let reversed = Array(scores.reversed())
let index = percent * Double(scores.count) / 100
guard floor(index) > 0 else {
return reversed[0]
}
return reversed[Int(floor(index)) - 1]
}
}
var maxScore: Int {
return scores.max() ?? 0
}
var minScore: Int {
return scores.min() ?? 0
}
}
// kernel density estimation
extension LSResult {
typealias KernelFunction = (Double, Double) -> Double
struct Kernel {
static let uniform: KernelFunction = { (x: Double, h: Double) in
if abs(x) <= h {
return uniformUnchecked(x, h)
} else {
return 0
}
}
static let uniformUnchecked: KernelFunction = { (x: Double, h: Double) in
return 1 / 2 / h
}
static let gaussian: KernelFunction = { (x: Double, h: Double) in
return 1 / sqrt(2 * Double.pi) * pow(M_E, -1 / 2 * (x / h) * (x / h)) / h
}
static let triangular: KernelFunction = { (x: Double, h: Double) in
if abs(x) <= h {
return triangularUnchecked(x, h)
} else {
return 0
}
}
static let triangularUnchecked: KernelFunction = { (x: Double, h: Double) in
return (1 - abs(x / h)) / h
}
}
var reversed: [Int] {
return scores.reversed()
}
var h: Double {
return 4 * Double(maxScore - minScore) / sqrt(Double(scores.count))
}
func estimate(using kernel: KernelFunction, range: Range<Double>, bound: Range<Double>) -> Double {
let upperBound = min(range.upperBound, bound.upperBound)
let lowerBound = max(range.lowerBound, bound.lowerBound)
var result = 0.0
let h = self.h
let step = max(1, min(100, (upperBound - lowerBound) / 1000))
var current = lowerBound
// var lastIndex = 0
let scores = self.reversed
while current <= upperBound {
var k = 0.0
for score in scores {
k += kernel(Double(score) - current, h)
}
result += k / Double(scores.count) * step
current += step
}
return result
}
}
|
a66591d28a2d84b9aa81ee1bd3fce5c0
| 25.401575 | 103 | 0.502833 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/FeatureInterest/Sources/FeatureInterestData/DIKit.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import FeatureInterestDomain
extension DependencyContainer {
// MARK: - FeatureInterestData Module
public static var interestDataKit = module {
// MARK: - Data
factory { APIClient() as FeatureInterestDataAPIClient }
factory { () -> InterestAccountBalanceClientAPI in
let client: FeatureInterestDataAPIClient = DIKit.resolve()
return client as InterestAccountBalanceClientAPI
}
factory { () -> InterestAccountWithdrawClientAPI in
let client: FeatureInterestDataAPIClient = DIKit.resolve()
return client as InterestAccountWithdrawClientAPI
}
factory { () -> InterestAccountLimitsClientAPI in
let client: FeatureInterestDataAPIClient = DIKit.resolve()
return client as InterestAccountLimitsClientAPI
}
factory { () -> InterestAccountRateClientAPI in
let client: FeatureInterestDataAPIClient = DIKit.resolve()
return client as InterestAccountRateClientAPI
}
factory { () -> InterestAccountTransferClientAPI in
let client: FeatureInterestDataAPIClient = DIKit.resolve()
return client as InterestAccountTransferClientAPI
}
factory { InterestAccountWithdrawRepository() as InterestAccountWithdrawRepositoryAPI }
factory { InterestAccountOverviewRepository() as InterestAccountOverviewRepositoryAPI }
factory { InterestAccountLimitsRepository() as InterestAccountLimitsRepositoryAPI }
factory { InterestAccountTransferRepository() as InterestAccountTransferRepositoryAPI }
single { InterestAccountBalanceRepository() as InterestAccountBalanceRepositoryAPI }
factory { InterestAccountRateRepository() as InterestAccountRateRepositoryAPI }
}
}
|
f1e9cb2fab44ebb0d9d9ea394c25ea91
| 34.90566 | 95 | 0.710457 | false | false | false | false |
coderMONSTER/iosstar
|
refs/heads/master
|
iOSStar/Scenes/Deal/CustomView/GradualColorView.swift
|
gpl-3.0
|
1
|
//
// GradualColorView.swift
// 渐变色
//
// Created by J-bb on 17/5/23.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class GradualColorView: UIView {
var isShowImage = true {
didSet {
imageView.isHidden = !isShowImage
}
}
var realWidth: CGFloat = kScreenWidth - 50
var percent:CGFloat = 0.0
var completeColors:[UIColor] = []
lazy var imageView:UIImageView = {
let imageView = UIImageView(image:UIImage(named: "auction_button"))
imageView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
return imageView
}()
var isRound = false
var subLayer:CAGradientLayer?
override init(frame: CGRect) {
super.init(frame: frame)
setupSubViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubViews()
}
func setupSubViews() {
addSubview(imageView)
imageView.center = CGPoint(x: 0, y: frame.size.height / 2)
}
convenience init(frame: CGRect, percent:CGFloat, completeColors:[UIColor], backColor:UIColor) {
self.init(frame:frame)
backgroundColor = backColor
self.percent = percent
self.completeColors = completeColors
}
func addGradualColorLayer(isRound:Bool) {
self.isRound = isRound
subLayer?.removeFromSuperlayer()
var colors:[CGColor] = []
if completeColors.count == 0 {
completeColors.append(UIColor(red: 251 / 255.0, green: 153 / 255.0, blue: 56 / 255.0, alpha: 1.0))
completeColors.append(UIColor(red: 251 / 255.0, green: 106 / 255.0, blue: 56 / 255.0, alpha: 1.0))
}
for color in completeColors {
colors.append(color.cgColor)
}
let gradientLayer = CAGradientLayer()
gradientLayer.colors = colors
gradientLayer.startPoint = CGPoint(x: 0, y: 1)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.frame = CGRect(x: 0, y: 0, width: realWidth * CGFloat(percent), height: frame.size.height)
if isShowImage {
imageView.center = CGPoint(x: realWidth * CGFloat(percent), y: imageView.center.y)
layer.insertSublayer(gradientLayer, below: imageView.layer)
} else {
layer.addSublayer(gradientLayer)
}
subLayer = gradientLayer
if isRound {
subLayer?.cornerRadius = 8
}
}
func animation(percent:CGFloat, width:CGFloat) {
self.percent = percent
realWidth = width
subLayer?.frame = CGRect(x: 0, y: 0, width: width * percent, height: frame.size.height)
if isShowImage {
imageView.center = CGPoint(x: frame.size.width * percent, y: imageView.center.y)
}
}
}
class DoubleGradualView: GradualColorView {
override func addGradualColorLayer(isRound: Bool) {
self.isRound = isRound
subLayer?.removeFromSuperlayer()
var colors:[CGColor] = []
for color in completeColors {
colors.append(color.cgColor)
}
let gradientLayer = CAGradientLayer()
gradientLayer.colors = colors
gradientLayer.locations = [0.5, 0.5]
gradientLayer.startPoint = CGPoint(x: 0, y: 1)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.frame = CGRect(x: 0, y: 0, width: realWidth * CGFloat(percent), height: frame.size.height)
if isShowImage {
imageView.center = CGPoint(x: realWidth * CGFloat(percent), y: imageView.center.y)
layer.insertSublayer(gradientLayer, below: imageView.layer)
} else {
layer.addSublayer(gradientLayer)
}
subLayer = gradientLayer
if isRound {
subLayer?.cornerRadius = 8
}
}
func animation(locations:[NSNumber]) {
subLayer?.locations = locations
if isShowImage {
imageView.center = CGPoint(x: frame.size.width * percent, y: imageView.center.y)
}
}
}
|
2fced20bf152fedeabe4b7a01ebfb02c
| 30.790698 | 112 | 0.601317 | false | false | false | false |
hrunar/functional-view-controllers
|
refs/heads/master
|
FunctionalViewControllers/UIViewController+Extensions.swift
|
mit
|
1
|
//
// UIViewController+Extensions.swift
// GithubIssues
//
// Created by Chris Eidhof on 07/03/15.
// Copyright (c) 2015 Unsigned Integer. All rights reserved.
//
import UIKit
@objc class CompletionHandler: NSObject {
let handler: BarButtonContext -> ()
weak var viewController: UIViewController?
init(_ handler: BarButtonContext -> (), _ viewController: UIViewController) {
self.handler = handler
self.viewController = viewController
}
@objc func tapped(sender: UIBarButtonItem) {
let context = BarButtonContext(button: sender, viewController: viewController!)
self.handler(context)
}
}
public enum BarButtonTitle {
case Text(String)
case SystemItem(UIBarButtonSystemItem)
}
public struct BarButtonContext {
public let button: UIBarButtonItem
public let viewController: UIViewController
}
public struct BarButton {
public let title: BarButtonTitle
public let callback: BarButtonContext -> ()
public init(title: BarButtonTitle, callback: BarButtonContext -> ()) {
self.title = title
self.callback = callback
}
}
public let defaultNavigationItem = NavigationItem(title: nil, rightBarButtonItem: nil)
public struct NavigationItem {
public var title: String?
public var rightBarButtonItem: BarButton?
public var leftBarButtonItem: BarButton?
public init(title: String? = nil, rightBarButtonItem: BarButton? = nil, leftBarButtonItem: BarButton? = nil) {
self.title = title
self.rightBarButtonItem = rightBarButtonItem
self.leftBarButtonItem = leftBarButtonItem
}
}
extension BarButton {
func barButtonItem(completionHandler: CompletionHandler) -> UIBarButtonItem {
switch title {
case .Text(let title):
return UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: completionHandler, action: "tapped:")
case .SystemItem(let systemItem):
return UIBarButtonItem(barButtonSystemItem: systemItem, target: completionHandler, action: "tapped:")
}
}
}
var AssociatedRightCompletionHandle: UInt8 = 0
var AssociatedLeftCompletionHandle: UInt8 = 0
extension UIViewController {
// todo this should be on the bar button...
var rightBarButtonCompletion: CompletionHandler? {
get {
return objc_getAssociatedObject(self, &AssociatedRightCompletionHandle) as? CompletionHandler
}
set {
objc_setAssociatedObject(self, &AssociatedRightCompletionHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var leftBarButtonCompletion: CompletionHandler? {
get {
return objc_getAssociatedObject(self, &AssociatedLeftCompletionHandle) as? CompletionHandler
}
set {
objc_setAssociatedObject(self, &AssociatedLeftCompletionHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func setRightBarButton(barButton: BarButton) {
let completion = CompletionHandler(barButton.callback, self)
self.rightBarButtonCompletion = completion
self.navigationItem.rightBarButtonItem = barButton.barButtonItem(completion)
}
func setLeftBarButton(barButton: BarButton) {
let completion = CompletionHandler(barButton.callback, self)
self.leftBarButtonCompletion = completion
self.navigationItem.leftBarButtonItem = barButton.barButtonItem(completion)
}
func applyNavigationItem(navigationItem: NavigationItem) {
self.navigationItem.title = navigationItem.title
if let barButton = navigationItem.rightBarButtonItem {
setRightBarButton(barButton)
}
if let barButton = navigationItem.leftBarButtonItem {
setLeftBarButton(barButton)
}
}
}
|
1fcb485da91bb72c7f6f95dc16bbdd8a
| 31.965812 | 144 | 0.707728 | false | false | false | false |
Khrob/swiftracer
|
refs/heads/master
|
project/swiftracer/swiftracer/Tracer.swift
|
apache-2.0
|
1
|
//
// tracer.swift
// swiftracer
//
// Created by Khrob Edmonds on 6/10/2015.
// Copyright © 2015 khrob. All rights reserved.
//
import Foundation
import AppKit
import CoreGraphics
/**
Pixel buffer to CGImage routines derived from Joseph Lord's work at
http://blog.human-friendly.com/drawing-images-from-pixel-data-in-swift
**/
struct Sample
{
var r:Double = 0.0
var g:Double = 0.0
var b:Double = 0.0
var a:Double = 1.0
static func buffer (size:Int) -> [Sample]
{
return [Sample](count: size, repeatedValue: Sample())
}
}
struct Pixel
{
var a:UInt8 = 255
var r:UInt8 = 0
var g:UInt8 = 0
var b:UInt8 = 0
static func buffer (size:Int) -> [Pixel]
{
return [Pixel](count: size, repeatedValue: Pixel())
}
}
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
func imageFromARGB32Bitmap(pixels:[Pixel], width:Int, height:Int) -> NSImage?
{
assert(pixels.count == Int(width * height))
var data = pixels
let providerRef = CGDataProviderCreateWithCFData(
NSData(bytes: &data, length: data.count * sizeof(Pixel))
)
if let cgim = CGImageCreate(width, height, 8, 32, width * sizeof(Pixel), rgbColorSpace, bitmapInfo, providerRef, nil, true, .RenderingIntentDefault)
{
return NSImage(CGImage: cgim, size: CGSizeMake(CGFloat(width),CGFloat(height)))
}
return nil
}
func simpleGradient (width:Int, height:Int) -> [Pixel]
{
var buffer = Pixel.buffer(width * height)
var index = 0
repeat {
let dw = UInt8 (255 * index % width / width)
let dh = UInt8 (255 * index / width / height)
let dd = UInt8 (255 - dh)
buffer[index].r = dw
buffer[index].g = dh
buffer[index].b = dd
index++
} while index < width * height
return buffer
}
func makeRays (width:Int, height:Int, origin:Vector, distance:Double, fov:Double) -> [Ray]
{
var rays = [Ray](count:width*height, repeatedValue:Ray(origin:origin, direction:Vector(x:0, y:0, z:0)))
var index = 0
for h in 0..<height {
let dy = Double(height/2 - h)
for w in 0..<width {
let dx = Double(w - width/2)
rays[index].direction.x = dx
rays[index].direction.y = dy
rays[index].direction.z = distance
rays[index].direction = rays[index].direction.unit()
index++
}
}
return rays
}
func simpleRaycast (rays:[Ray], width:Int, height:Int) -> [Pixel]
{
var pixels = Pixel.buffer(rays.count)
let plane = Plane(ox: 0, oy: -4, oz: 0, nx: 0, ny: 1, nz: 0)
var index = 0
var max_t = 0.0
repeat
{
if let t = plane.intersection(rays[index])
{
var inter = t * 255
if inter > 255 { inter = 255 }
let gray:UInt8 = UInt8(255 - inter)
pixels[index].r = gray / 2
pixels[index].g = gray / 2
pixels[index].b = gray / 2
let p = rays[index].t(t)
let x = Int(abs(p.x))
let y = Int(abs(p.z))
if x % 2 == y % 2
{
pixels[index].r = gray / 4
pixels[index].g = gray / 4
pixels[index].b = gray / 4
}
if t > max_t { max_t = t }
}
else
{
let dw = UInt8 (255 * index % width / width)
let dh = UInt8 (255 * index / width / height)
let dd = UInt8 (255 - dh)
pixels[index].r = dw
pixels[index].g = dh
pixels[index].b = dd
}
index++
} while index < rays.count
print ("max_t: \(max_t)")
return pixels
}
func intersection (scene:[STObject], ray:Ray) -> (point:Ray, obj:STObject)?
{
var t:Double = Double.infinity
var hit:STObject?
for obj in scene
{
if let newT = obj.intersection(ray)
{
if newT < t && t > 0.00001
{
hit = obj
t = newT
}
}
}
if t == Double.infinity { return nil }
let pt = ray.t(t)
let normal = hit!.normalAtPoint(pt)
let r = Ray(origin:pt, direction:normal)
return (r, hit!)
}
func simpleScene (scene:[STObject], rays:[Ray], width:Int, height:Int) -> [Pixel]
{
var pixels = Pixel.buffer(rays.count)
var index = 0
repeat
{
let s = trace(scene, ray: rays[index], depth: 0, colour: Sample())
var r = s.r * 255
var g = s.g * 255
var b = s.b * 255
if r > 255 { r = 255 }
if g > 255 { g = 255 }
if b > 255 { b = 255 }
pixels[index] = Pixel(a: 255, r:UInt8(r), g:UInt8(g), b:UInt8(b))
// print("\(s) \(pixels[index])")
index++
} while index < rays.count
return pixels
}
let BOUNCES = 10.0
func trace (scene:[STObject], ray:Ray, depth:Int, var colour:Sample) -> Sample
{
if depth > Int(BOUNCES-1)
{
// print("depth5 \(colour) \(depth)")
return colour
}
guard let hit = intersection(scene, ray: ray) else {
// print("nohit \(colour) \(depth)")
return colour
}
colour.r += hit.obj.diffuse.x / BOUNCES
colour.g += hit.obj.diffuse.y / BOUNCES
colour.b += hit.obj.diffuse.z / BOUNCES
// print("returning \(colour) \(depth)")
return trace(scene, ray:hit.point, depth:depth+1, colour:colour)
}
|
777a2ac7170210bdbe62b85936568798
| 23.544681 | 152 | 0.524445 | false | false | false | false |
1amageek/StripeAPI
|
refs/heads/master
|
StripeAPI/Models/CORE_RESOURCES/Charge.swift
|
mit
|
1
|
//
// Charge.swift
// StripeAPI
//
// Created by 1amageek on 2017/10/01.
// Copyright © 2017年 Stamp Inc. All rights reserved.
//
import Foundation
import APIKit
public struct Charge: StripeModel, ListProtocol {
public static var path: String { return "/charges"}
private enum CodingKeys: String, CodingKey {
case id
case object
case amount
case amountRefunded = "amount_refunded"
case application
case applicationFee = "application_fee"
case balanceTransaction = "balance_transaction"
case captured
case created
case currency
case customer
case description
case destination
case dispute
case failureCode = "failure_code"
case failureMessage = "failure_message"
case fraudDetails = "fraud_details"
case invoice
case livemode
case metadata
case onBehalfOf = "on_behalf_of"
case order
case outcome
case paid
case receiptEmail = "receipt_email"
case receiptNumber = "receipt_number"
case refunded
case refunds
case review
case shipping
case source
case sourceTransfer = "source_transfer"
case statementDescriptor = "statement_descriptor"
case status
case transferGroup = "transfer_group"
}
public let id: String
public let object: String
public let amount: Double
public let amountRefunded: Double
public let application: String?
public let applicationFee: String?
public let balanceTransaction: String?
public let captured: Bool
public let created: TimeInterval
public let currency: Currency
public let customer: String
public let description: String?
public let destination: String?
public let dispute: String?
public let failureCode: String?
public let failureMessage: String?
public let fraudDetails: FraudDetails
public let invoice: String?
public let livemode: Bool
public let metadata: [String: String]?
public let onBehalfOf: String?
public let order: String?
public let outcome: Outcome
public let paid: Bool
public let receiptEmail: String?
public let receiptNumber: String?
public let refunded: Bool?
public let refunds: List<Refund>
public let review: String?
public let shipping: Shipping?
public let source: Card
public let sourceTransfer: String?
public let statementDescriptor: String?
public let status: Status
public let transferGroup: String?
public enum Status: String, Codable {
case succeeded
case pending
case failed
}
public struct FraudDetails: Codable {
private enum CodingKeys: String, CodingKey {
case userReport = "user_report"
case stripeReport = "stripe_report"
}
public let userReport: UserReport?
public let stripeReport: StripeReport?
public enum UserReport: String, Codable {
case safe
case fraudulent
}
public enum StripeReport: String, Codable {
case fraudulent
}
}
}
extension Charge {
// MARK: - Create
public struct Create: StripeParametersAPI {
public typealias Response = Charge
public var method: HTTPMethod { return .post }
public var path: String { return Charge.path }
public var _parameters: Any?
public init(amount: Double, currency: Currency, customer: String) {
self._parameters = Parameters(amount: amount, currency: currency, customer: customer)
}
public init(amount: Double, currency: Currency, source: String) {
self._parameters = Parameters(amount: amount, currency: currency, source: source)
}
public init(parameters: Parameters) {
self._parameters = parameters
}
public struct Parameters: Codable {
private enum CodingKeys: String, CodingKey {
case amount
case currency
case applicationFee = "application_fee"
case capture
case description
case destination
case transferGroup = "transfer_group"
case onBehalfOf = "on_behalf_of"
case metadata
case receiptEmail = "receipt_email"
case shipping
case customer
case source
case statementDescriptor = "statement_descriptor"
}
public let amount: Double
public let currency: Currency
public var applicationFee: String? = nil
public var capture: Bool? = nil
public var description: String? = nil
public var destination: Destination? = nil
public var transferGroup: String? = nil
public var onBehalfOf: String? = nil
public var metadata: [String: String]? = nil
public var receiptEmail: String? = nil
public var shipping: Shipping? = nil
public let customer: String?
public let source: String?
public var statementDescriptor: String? = nil
public init(amount: Double, currency: Currency, customer: String) {
self.amount = amount
self.currency = currency
self.customer = customer
self.source = nil
}
public init(amount: Double, currency: Currency, source: String) {
self.amount = amount
self.currency = currency
self.customer = nil
self.source = source
}
public struct Destination: Codable {
public let account: String
public var amount: Double? = nil
}
}
}
// MARK: - Retrieve
public struct Retrieve: StripeAPI {
public typealias Response = Charge
public var method: HTTPMethod { return .get }
public var path: String { return "\(Charge.path)/\(id)" }
public let id: String
public init(id: String) {
self.id = id
}
}
// MARK: - Update
public struct Update: StripeParametersAPI {
public typealias Response = Charge
public var method: HTTPMethod { return .post }
public var path: String { return "\(Charge.path)/\(id)" }
public let id: String
public var _parameters: Any?
public init(id: String, parameters: Parameters) {
self.id = id
self._parameters = parameters
}
public struct Parameters: Codable {
private enum CodingKeys: String, CodingKey {
case description
case fraudDetails = "fraud_details"
case metadata
case receiptEmail = "receipt_email"
case shipping
case transferGroup = "transfer_group"
}
public var description: String? = nil
public var fraudDetails: FraudDetails? = nil
public var metadata: [String: String]? = nil
public var receiptEmail: String? = nil
public var shipping: Shipping? = nil
public var transferGroup: String? = nil
}
}
// MARK: - Capture
public struct Capture: StripeParametersAPI {
public typealias Response = Charge
public var method: HTTPMethod { return .post }
public var path: String { return "\(Charge.path)/\(id)/capture" }
public let id: String
public var _parameters: Any?
public init(id: String, parameters: Parameters? = nil) {
self.id = id
self._parameters = parameters
}
public struct Parameters: Codable {
private enum CodingKeys: String, CodingKey {
case amount
case applicationFee = "application_fee"
case destination
case receiptEmail = "receipt_email"
case statementDescriptor = "statement_descriptor"
}
public var amount: Double? = nil
public var applicationFee: String? = nil
public var destination: Destination? = nil
public var receiptEmail: String? = nil
public var statementDescriptor: String? = nil
public struct Destination: Codable {
public let account: String
public var amount: Double? = nil
}
}
}
}
|
0835ba3b120c05e3977f3d0201ebb060
| 28.120401 | 97 | 0.58585 | false | false | false | false |
CodaFi/PersistentStructure.swift
|
refs/heads/master
|
Persistent/AbstractTransientSet.swift
|
mit
|
1
|
//
// AbstractTransientSet.swift
// Persistent
//
// Created by Robert Widmann on 12/22/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
public class AbstractTransientSet : ITransientSet {
var _impl: ITransientMap
init(impl: ITransientMap) {
_impl = impl
}
public var count : Int {
return _impl.count
}
public func conj(val: AnyObject) -> ITransientCollection {
let m: ITransientMap = _impl.associateKey(val, value: val)
if m !== _impl {
_impl = m
}
return self
}
public func containsObject(key: AnyObject) -> Bool {
return self !== _impl.objectForKey(key, def: self) as! AbstractTransientSet
}
public func disjoin(key: AnyObject) -> ITransientSet {
let m: ITransientMap = _impl.without(key)
if m !== _impl {
_impl = m
}
return self
}
public func objectForKey(key: AnyObject) -> AnyObject? {
return _impl.objectForKey(key)!
}
public func persistent() -> IPersistentCollection {
fatalError("\(__FUNCTION__) unimplemented")
}
}
|
719ce8e0d4c0300f796bd72b8a46c1dc
| 20.148936 | 77 | 0.677062 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
refs/heads/main
|
Swift/odd-even-linked-list.swift
|
mit
|
1
|
/**
* https://leetcode.com/problems/odd-even-linked-list/
*
*
*/
// Date: Sun May 17 14:31:14 PDT 2020
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func oddEvenList(_ head: ListNode?) -> ListNode? {
let evenHead = ListNode()
let oddHead = ListNode()
var enode = evenHead
var onode = oddHead
var node = head
var isEven = true
while node != nil {
// print("node: \(node?.val)")
if isEven {
enode.next = node
enode = node!
} else {
onode.next = node
onode = node!
}
node = node?.next
isEven = !isEven
}
enode.next = oddHead.next
onode.next = nil
return evenHead.next
}
}
/**
* https://leetcode.com/problems/odd-even-linked-list/
*
*
*/
// Date: Thu Dec 2 00:19:06 PST 2021
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func oddEvenList(_ head: ListNode?) -> ListNode? {
var oddHead: ListNode? = ListNode(0)
var evenHead: ListNode? = ListNode(0)
var oNode = oddHead
var eNode = evenHead
var cNode = head
var counter = 0
while let node = cNode {
if counter % 2 != 0 {
eNode?.next = node
eNode = eNode?.next
} else {
oNode?.next = node
oNode = oNode?.next
}
cNode = node.next
counter += 1
}
oNode?.next = evenHead?.next
eNode?.next = nil
return oddHead?.next
}
}
|
639488e263bb9c1f081798be80019ea3
| 26.780488 | 87 | 0.501976 | false | false | false | false |
arvedviehweger/swift
|
refs/heads/master
|
benchmark/single-source/SetTests.swift
|
apache-2.0
|
3
|
//===--- SetTests.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_SetIsSubsetOf(_ N: Int) {
let size = 200
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var isSubset = false
for _ in 0 ..< N * 5000 {
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset, "Incorrect results in SetIsSubsetOf")
}
@inline(never)
func sink(_ s: inout Set<Int>) {
}
@inline(never)
public func run_SetExclusiveOr(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var xor = Set<Int>()
for _ in 0 ..< N * 100 {
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var or = Set<Int>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var and = Set<Int>()
for _ in 0 ..< N * 100 {
and = set.intersection(otherSet)
}
sink(&and)
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_SetIsSubsetOf_OfObjects(_ N: Int) {
let size = 200
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var isSubset = false
for _ in 0 ..< N * 5000 {
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset, "Incorrect results in SetIsSubsetOf")
}
@inline(never)
func sink(_ s: inout Set<Box<Int>>) {
}
@inline(never)
public func run_SetExclusiveOr_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var xor = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var or = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var and = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
and = set.intersection(otherSet)
}
sink(&and)
}
|
86ee33e8d0ce7e98a8f8a35482b6e8e7
| 20.521127 | 80 | 0.622164 | false | false | false | false |
tschob/HSAudioPlayer
|
refs/heads/master
|
Example/Core/ViewController/SharedInstancePlayer/HSEPlayerViewController.swift
|
mit
|
1
|
//
// HSEPlayerViewController.swift
// Example
//
// Created by Hans Seiffert on 04.08.16.
// Copyright © 2016 Hans Seiffert. All rights reserved.
//
import UIKit
import HSAudioPlayer
import MediaPlayer
class HSEPlayerViewController: UIViewController {
@IBOutlet private weak var rewindButton : UIButton?
@IBOutlet private weak var stopButton : UIButton?
@IBOutlet private weak var playPauseButton : UIButton?
@IBOutlet private weak var forwardButton : UIButton?
@IBOutlet private weak var songLabel : UILabel?
@IBOutlet private weak var albumLabel : UILabel?
@IBOutlet private weak var artistLabel : UILabel?
@IBOutlet private weak var positionLabel : UILabel?
override func viewDidLoad() {
super.viewDidLoad()
self.updateButtonStates()
// Listen to the player state updates. This state is updated if the play, pause or queue state changed.
HSAudioPlayer.sharedInstance.addPlayStateChangeCallback(self, callback: { [weak self] (playerItem: HSAudioPlayerItem?) in
self?.updateButtonStates()
self?.updateSongInformation(playerItem)
})
// Listen to the playback time changed. This event occurs every `HSAudioPlayer.PlayingTimeRefreshRate` seconds.
HSAudioPlayer.sharedInstance.addPlaybackTimeChangeCallback(self, callback: { [weak self] (playerItem: HSAudioPlayerItem?) in
self?.updatePlaybackTime(playerItem)
})
}
deinit {
// Stop listening to the callbacks
HSAudioPlayer.sharedInstance.removePlayStateChangeCallback(self)
HSAudioPlayer.sharedInstance.removePlaybackTimeChangeCallback(self)
}
func updateButtonStates() {
self.rewindButton?.enabled = HSAudioPlayer.sharedInstance.canRewind()
let imageName = (HSAudioPlayer.sharedInstance.isPlaying() == true ? "ic_pause" : "ic_play")
self.playPauseButton?.setImage(UIImage(named: imageName), forState: .Normal)
self.playPauseButton?.enabled = HSAudioPlayer.sharedInstance.canPlay()
self.forwardButton?.enabled = HSAudioPlayer.sharedInstance.canForward()
}
func updateSongInformation(playerItem: HSAudioPlayerItem?) {
self.songLabel?.text = "\((playerItem?.nowPlayingInfo?[MPMediaItemPropertyTitle] as? String) ?? "-")"
self.albumLabel?.text = "\((playerItem?.nowPlayingInfo?[MPMediaItemPropertyAlbumTitle] as? String) ?? "-")"
self.artistLabel?.text = "\((playerItem?.nowPlayingInfo?[MPMediaItemPropertyArtist] as? String) ?? "-")"
self.updatePlaybackTime(playerItem)
}
func updatePlaybackTime(playerItem: HSAudioPlayerItem?) {
self.positionLabel?.text = "\(playerItem?.displayablePlaybackTimeString() ?? "-")/\(playerItem?.displayableDurationString() ?? "-")"
}
}
// MARK: - IBActions
extension HSEPlayerViewController {
@IBAction func didPressRewindButton(sender: AnyObject) {
HSAudioPlayer.sharedInstance.rewind()
}
@IBAction func didPressStopButton(sender: AnyObject) {
HSAudioPlayer.sharedInstance.stop()
}
@IBAction func didPressPlayPauseButton(sender: AnyObject) {
HSAudioPlayer.sharedInstance.togglePlayPause()
}
@IBAction func didPressForwardButton(sender: AnyObject) {
HSAudioPlayer.sharedInstance.forward()
}
}
|
30db4b501adf8034739190495062b2ac
| 34.825581 | 134 | 0.769555 | false | false | false | false |
juliangrosshauser/HomeControl
|
refs/heads/master
|
HomeControl/Source/StructureFileParser.swift
|
mit
|
1
|
//
// StructureFileParser.swift
// HomeControl
//
// Created by Julian Grosshauser on 30/11/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import SWXMLHash
/// Parses structure files.
class StructureFileParser {
/// Parses a structure file.
///
/// - Parameter path: Structure file path.
///
/// - Throws: `StuctureFileParserError`.
///
/// - Returns: All found rooms with their accessories.
///
func parse(path: String) throws -> [Room] {
// Read structure file content.
let structureFileContent: String
do {
structureFileContent = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
} catch {
throw StructureFileParserError.ReadError
}
// Parse structure file XML and convert it into a dictionary.
let structureFile = SWXMLHash.parse(structureFileContent)
// Get categories by parsing structure file.
let categories = parseCategories(structureFile)
// There should be at least 3 categories: lights, blinds and consumers.
guard categories.count >= 3 else {
throw StructureFileParserError.CategoryError
}
// Get accessory category.
guard let lightCategory = categories["Beleuchtung"], blindCategory = categories["Beschattung"], consumerCategory = categories["Verbraucher"] else {
throw StructureFileParserError.CategoryError
}
// Find all accessories.
let lights = parseAccessories(parseAccessoryIndices(structureFile, category: lightCategory), accessoryType: Light.self)
let blinds = parseAccessories(parseAccessoryIndices(structureFile, category: blindCategory), accessoryType: Blind.self)
let consumers = parseAccessories(parseAccessoryIndices(structureFile, category: consumerCategory), accessoryType: Consumer.self)
// Construct rooms by parsing structure file and adding accessory information.
return parseRooms(structureFile, lights: lights, blinds: blinds, consumers: consumers)
}
/// Parses a structure file for category information.
///
/// - Parameter structureFile: The structure file to parse.
///
/// - Returns: Dictionary using category names as keys and category IDs as values.
///
private func parseCategories(structureFile: XMLIndexer) -> [String: UInt] {
// Save category information in dictionary.
var categories = [String: UInt]()
for category in structureFile["LoxLIVE"]["Cats"]["Cat"] {
if let idString = category.element?.attributes["n"], id = UInt(idString), name = category.element?.attributes["name"] {
categories[name] = id
}
}
return categories
}
/// Parses a structure file for accessory XML elements.
///
/// - Parameters:
/// - structureFile: The structure file to parse.
/// - category: The accessory category.
///
/// - Returns: Array of `XMLIndixer` with specified category.
///
private func parseAccessoryIndices(structureFile: XMLIndexer, category: UInt) -> [XMLIndexer] {
// Find all accessory XML elements by checking the category attribute.
let accessoryIndices = structureFile["LoxLIVE"]["Functions"]["Function"].filter {
if let categoryString = $0.element?.attributes["cat"] {
return UInt(categoryString) == category
}
return false
}
return accessoryIndices
}
/// Parses a structure file for accessory information.
///
/// - Parameters:
/// - indices: Accessory indices to parse. These indices are found by `StructureFileParser.parseAccessoryIndices(_:category:)`.
/// - accessoryType: Type of accessory to parse.
///
/// - Returns: Dictionary using room IDs as keys and accessory arrays as values.
///
/// - SeeAlso: `StructureFileParser.parseAccessoryIndices(_:category:)`.
///
private func parseAccessories<T: Accessory>(indices: [XMLIndexer], accessoryType: T.Type) -> [UInt: [T]] {
// Create accessories with information of XML element attributes and save them in a dictionary using room IDs as keys.
var accessories = [UInt: [T]]()
for accessory in indices {
if let roomIDString = accessory.element?.attributes["room"], roomID = UInt(roomIDString), name = accessory.element?.attributes["name"], actionID = accessory.element?.attributes["UUIDaction"] {
if accessories[roomID] == nil {
accessories[roomID] = [T]()
}
accessories[roomID]?.append(T(name: name, actionID: actionID))
}
}
return accessories
}
/// Parses a structure file for room information.
///
/// - Parameters:
/// - structureFile: The structure file to parse.
/// - lights: Dictionary containing room IDs and matching light information.
/// - blinds: Dictionary containing room IDs and matching blind information.
/// - consumers: Dictionary containing room IDs and matching consumer information.
///
/// - Returns: Array containing all found rooms.
///
private func parseRooms(structureFile: XMLIndexer, lights: [UInt: [Light]], blinds: [UInt: [Blind]], consumers: [UInt: [Consumer]]) -> [Room] {
// Create rooms based on structure file information.
var rooms = [Room]()
for room in structureFile["LoxLIVE"]["Rooms"]["Room"] {
if let idString = room.element?.attributes["n"], id = UInt(idString), name = room.element?.attributes["name"] {
rooms.append(Room(id: id, name: name, lights: lights[id], blinds: blinds[id], consumers: consumers[id]))
}
}
return rooms
}
}
|
23eedbd5e43f886a2518c0f92f1191d4
| 40.316901 | 204 | 0.640361 | false | false | false | false |
quran/quran-ios
|
refs/heads/main
|
Sources/QuranAudioKit/Downloads/AyahsAudioDownloader.swift
|
apache-2.0
|
1
|
//
// AyahsAudioDownloader.swift
// Quran
//
// Created by Mohamed Afifi on 4/21/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import BatchDownloader
import Foundation
import PromiseKit
import QuranKit
public struct AyahsAudioDownloader {
let downloader: DownloadManager
let fileListFactory: ReciterAudioFileListRetrievalFactory
init(downloader: DownloadManager, fileListFactory: ReciterAudioFileListRetrievalFactory) {
self.downloader = downloader
self.fileListFactory = fileListFactory
}
public init(baseURL: URL, downloader: DownloadManager) {
self.downloader = downloader
fileListFactory = DefaultReciterAudioFileListRetrievalFactory(quran: Quran.madani, baseURL: baseURL)
}
public func download(from start: AyahNumber, to end: AyahNumber, reciter: Reciter) -> Promise<DownloadBatchResponse> {
DispatchQueue.global()
.async(.guarantee) { () -> DownloadBatchRequest in
let retriever = self.fileListFactory.fileListRetrievalForReciter(reciter)
// get downloads
let files = retriever
.get(for: reciter, from: start, to: end)
.filter { !FileManager.documentsURL.appendingPathComponent($0.local).isReachable }
.map { DownloadRequest(url: $0.remote, destinationPath: $0.local) }
return DownloadBatchRequest(requests: files)
}
.then {
// create downloads
self.downloader.download($0)
}
}
public func downloadingAudios(_ reciters: [Reciter]) -> Guarantee<[Reciter: DownloadBatchResponse]> {
downloader.getOnGoingDownloads()
.map { self.audioResponses(reciters, downloads: $0) }
}
private func audioResponses(_ reciters: [Reciter], downloads: [DownloadBatchResponse]) -> [Reciter: DownloadBatchResponse] {
var paths: [String: DownloadBatchResponse] = [:]
for batch in downloads {
if let download = batch.requests.first, batch.isAudio {
paths[download.destinationPath.stringByDeletingLastPathComponent] = batch
}
}
var responses: [Reciter: DownloadBatchResponse] = [:]
for reciter in reciters {
responses[reciter] = paths[reciter.path]
}
return responses
}
}
|
e05a99550bace89dc0bb8b2fe38e49db
| 37.842105 | 128 | 0.66565 | false | false | false | false |
zisko/swift
|
refs/heads/master
|
stdlib/public/core/Unicode.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
@_fixed_layout
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(Unicode.Scalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
@_inlineable // FIXME(sil-serialize-all)
public static func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `Unicode.Scalar` type to work with
/// decoded Unicode scalar values.
public protocol UnicodeCodec : Unicode.Encoding {
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
///
/// - Complexity: O(*n*)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
extension Unicode.UTF8 : UnicodeCodec {
/// Creates an instance of the UTF-8 codec.
@_inlineable // FIXME(sil-serialize-all)
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF8.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ ... ... ... CU0 ].
let value = buffer & 0xff
return (value, 1)
}
var p = ForwardParser()
p._buffer._storage = buffer
p._buffer._bitCount = 32
var i = EmptyCollection<UInt8>().makeIterator()
switch p.parseScalar(from: &i) {
case .valid(let s):
return (
result: UTF8.decode(s).value,
length: UInt8(truncatingIfNeeded: s.count))
case .error(let l):
return (result: nil, length: UInt8(truncatingIfNeeded: l))
case .emptyInput: Builtin.unreachable()
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._biasedBits
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codeUnit in eAcute.utf8 {
/// print(codeUnit, UTF8.isContinuation(codeUnit))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
@_inlineable // FIXME(sil-serialize-all)
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
@_inlineable // FIXME(sil-serialize-all)
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
return Int(_stdlib_strlen_unsigned(input))
}
// Support parsing C strings as-if they are UTF8 strings.
@_inlineable // FIXME(sil-serialize-all)
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CChar>
) -> Int {
return Int(_stdlib_strlen(input))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF8")
public typealias UTF8 = Unicode.UTF8
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
extension Unicode.UTF16 : UnicodeCodec {
/// Creates an instance of the UTF-16 codec.
@_inlineable // FIXME(sil-serialize-all)
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@_inlineable // FIXME(sil-serialize-all)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF16.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", into: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@_inlineable // FIXME(sil-serialize-all)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._storage
processCodeUnit(UInt16(truncatingIfNeeded: s))
s &>>= 16
if _fastPath(s == 0) { return }
processCodeUnit(UInt16(truncatingIfNeeded: s))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF16")
public typealias UTF16 = Unicode.UTF16
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
extension Unicode.UTF32 : UnicodeCodec {
/// Creates an instance of the UTF-32 codec.
@_inlineable // FIXME(sil-serialize-all)
public init() { self = ._swift3Codec }
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `Unicode.Scalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@_inlineable // FIXME(sil-serialize-all)
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
var parser = ForwardParser()
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF32.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", into: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@_inlineable // FIXME(sil-serialize-all)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
// @available(swift, obsoleted: 4.0, renamed: "Unicode.UTF32")
public typealias UTF32 = Unicode.UTF32
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, into: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func transcode<
Input : IteratorProtocol,
InputEncoding : Unicode.Encoding,
OutputEncoding : Unicode.Encoding
>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
into processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool
where InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var p = InputEncoding.ForwardParser()
var hadError = false
loop:
while true {
switch p.parseScalar(from: &input) {
case .valid(let s):
let t = OutputEncoding.transcode(s, from: inputEncoding)
guard _fastPath(t != nil), let s = t else { break }
s.forEach(processCodeUnit)
continue loop
case .emptyInput:
return hadError
case .error:
if _slowPath(stopOnError) { return true }
hadError = true
}
OutputEncoding.encodedReplacementCharacter.forEach(processCodeUnit)
}
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(truncatingIfNeeded: x)
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(truncatingIfNeeded: utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: Unicode.Scalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: Unicode.Scalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
@_inlineable // FIXME(sil-serialize-all)
public static func width(_ x: Unicode.Scalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
@_inlineable // FIXME(sil-serialize-all)
public static func leadSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xD800 + UTF16.CodeUnit(truncatingIfNeeded:
(x.value - 0x1_0000) &>> (10 as UInt32))
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specified Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: Unicode.Scalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
@_inlineable // FIXME(sil-serialize-all)
public static func trailSurrogate(_ x: Unicode.Scalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return 0xDC00 + UTF16.CodeUnit(truncatingIfNeeded:
(x.value - 0x1_0000) & (((1 as UInt32) &<< 10) - 1))
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
@_inlineable // FIXME(sil-serialize-all)
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return (x & 0xFC00) == 0xD800
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
@_inlineable // FIXME(sil-serialize-all)
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return (x & 0xFC00) == 0xDC00
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if MemoryLayout<T>.stride == MemoryLayout<U>.stride {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(MemoryLayout<U>.stride))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
@_inlineable // FIXME(sil-serialize-all)
public static func transcodedLength<
Input : IteratorProtocol,
Encoding : Unicode.Encoding
>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where Encoding.CodeUnit == Input.Element {
var utf16Count = 0
var i = input
var d = Encoding.ForwardParser()
// Fast path for ASCII in a UTF8 buffer
if sourceEncoding == Unicode.UTF8.self {
var peek: Encoding.CodeUnit = 0
while let u = i.next() {
peek = u
guard _fastPath(peek < 0x80) else { break }
utf16Count = utf16Count + 1
}
if _fastPath(peek < 0x80) { return (utf16Count, true) }
var d1 = UTF8.ForwardParser()
d1._buffer.append(numericCast(peek))
d = _identityCast(d1, to: Encoding.ForwardParser.self)
}
var utf16BitUnion: CodeUnit = 0
while true {
let s = d.parseScalar(from: &i)
if _fastPath(s._valid != nil), let scalarContent = s._valid {
let utf16 = transcode(scalarContent, from: sourceEncoding)
._unsafelyUnwrappedUnchecked
utf16Count += utf16.count
for x in utf16 { utf16BitUnion |= x }
}
else if let _ = s._error {
guard _fastPath(repairingIllFormedSequences) else { return nil }
utf16Count += 1
utf16BitUnion |= UTF16._replacementCodeUnit
}
else {
return (utf16Count, utf16BitUnion < 0x80)
}
}
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension Unicode.Scalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec {
@_inlineable // FIXME(sil-serialize-all)
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
/// A namespace for Unicode utilities.
@_fixed_layout // FIXME(sil-serialize-all)
public enum Unicode {}
|
284db95b4d840594315f86ed8a097ad9
| 37.144241 | 87 | 0.642228 | false | false | false | false |
OlegNovosad/Sample
|
refs/heads/master
|
iOS/Severenity/Services/HealthService.swift
|
apache-2.0
|
2
|
//
// HealthKitService.swift
// Severenity
//
// Created by Yuriy Yasinskyy on 02.11.16.
// Copyright © 2016 severenity. All rights reserved.
//
import UIKit
import HealthKit
class HealthService: NSObject {
static let sharedInstance = HealthService()
private var healthStore: HKHealthStore?
// MARK: Init
private override init() {
super.init()
if HKHealthStore.isHealthDataAvailable() {
healthStore = HKHealthStore()
var readTypes = Set<HKObjectType>()
readTypes.insert(HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)
readTypes.insert(HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!)
healthStore?.requestAuthorization(toShare: nil, read: readTypes) { (success, error) -> Void in
if success {
Log.info(message: "HealthKit authorized succesfully", sender: self)
} else {
Log.error(message: "HealthKit authorization failed: \(error)", sender: self)
}
}
}
else {
Log.info(message: "HealthKit is not available", sender: self)
}
Log.info(message: "HealthKitService shared instance init did complete", sender: self)
}
// MARK: Methods for getting data from HealthKit
func retrieveStepsCount(startDate: Date, endDate: Date,
completion: @escaping (_ stepsRetrieved: Double) -> Void) {
// Define the Step Quantity Type
let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
// Set the Predicates & Interval
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
var interval = DateComponents()
interval.day = 1
// Perform the Query
let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate,
options: [.cumulativeSum], anchorDate: startDate, intervalComponents: interval)
query.initialResultsHandler = { query, results, error in
if error != nil {
Log.error(message: "Cannot retrieve HealthKit steps data: \(error)", sender: self)
return
}
if let myResults = results {
var stepsCount = 0.0
myResults.enumerateStatistics(from: startDate, to: endDate) {
statistics, stop in
if let quantity = statistics.sumQuantity() {
let steps = quantity.doubleValue(for: HKUnit.count())
stepsCount += steps
}
}
completion(stepsCount)
}
}
healthStore?.execute(query)
}
func retrieveWalkRunDistance(startDate: Date, endDate: Date,
completion: @escaping (_ distanceRetrieved: Double) -> Void) {
// Define the Distance Quantity Type
let distance = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)
// Set the Predicates & Interval
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
var interval = DateComponents()
interval.day = 1
// Perform the Query
let query = HKStatisticsCollectionQuery(quantityType: distance!, quantitySamplePredicate: predicate,
options: [.cumulativeSum], anchorDate: startDate, intervalComponents: interval)
query.initialResultsHandler = { query, results, error in
if error != nil {
Log.error(message: "Cannot retrieve HealthKit distance data: \(error)", sender: self)
return
}
if let myResults = results {
var totalDistance = 0.0
myResults.enumerateStatistics(from: startDate, to: endDate) {
statistics, stop in
if let quantity = statistics.sumQuantity() {
let distance = quantity.doubleValue(for: HKUnit.mile())
totalDistance += distance
}
}
completion(totalDistance)
}
}
healthStore?.execute(query)
}
}
|
a9cf0446db725c97709662e449112341
| 40.178571 | 127 | 0.579141 | false | false | false | false |
sacrelee/iOSDev
|
refs/heads/master
|
Demos/Demo_SketchpadSwift/Demo_SketchpadSwift/FMDBManager.swift
|
apache-2.0
|
1
|
//
// FMDBManager.swift
// Demo_SketchpadSwift
//
// Created by SACRELEE on 16/2/25.
// Copyright © 2016年 SACRELEE. All rights reserved.
//
import Foundation
import FMDB
let LineModelTableName = "LinesDataTable"
class FMDBManager{
static let defaultManager = FMDBManager() // 单例
let fmdbQueue:FMDatabaseQueue?
private init(){
let dbPath = try! NSFileManager.defaultManager().URLForDirectory(.LibraryDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false).URLByAppendingPathComponent("database.sqlite")
fmdbQueue = FMDatabaseQueue(path: dbPath.path)
self.createOpenDatabase()
}
func createOpenDatabase(){
fmdbQueue?.inDatabase(){
db in
if db.open() == true {
print("create / open database success!")
}
else{
print("create / open database failed!")
}
}
}
func createTable(){
if NSUserDefaults.standardUserDefaults().boolForKey("TableCreated") == true {
print("the table is already exists!")
return
}
let SQLStr = "create table if not exists \(LineModelTableName) ( lineId integer primary key autoincrement, paintingId integer, colorIndex integer, width real, points text)"
if self.executeSQL(SQLString: SQLStr) == true {
NSUserDefaults.standardUserDefaults().setBool( true, forKey:"TableCreated")
print("create Table success!")
}
else{
print("create Table failed!!!")
}
}
func saveLineModels(lineModels lms:[LineModel]) -> Bool{
if lms.count == 0 {
return true
}
// clear old data
let clearTable = "delete from \(LineModelTableName) where paintingId = 0"
self.executeSQL(SQLString: clearTable)
var success = true
fmdbQueue?.inTransaction(){
db, rollback in
for lm in lms {
if db.executeUpdate(self.getModelInsertSQLString(lineModel: lm, paintingId: 0), withArgumentsInArray: nil) == false {
rollback.initialize(true)
success = false
break
}
}
}
return success
}
func getModelInsertSQLString(lineModel lm:LineModel, paintingId pId:NSInteger) -> String{
var pointsStr = "'["
for point in lm.points {
pointsStr += "\"\(point.x),\(point.y)\","
}
pointsStr += "]'"
return "insert into \(LineModelTableName)(paintingId, colorIndex, width, points) values(\(pId), \(lm.colorIndex), \(lm.width), \(pointsStr))"
}
func getLineModelArray() -> [LineModel]? {
let sql = "select * from \(LineModelTableName) where paintingId = 0"
var models:[LineModel] = []
// _ = ""
fmdbQueue?.inDatabase(){
db in
let resultSet = db.executeQuery( sql, withArgumentsInArray: nil)
while resultSet.next(){
// let cn = NSClassFromString(className) as! NSObject.Type
// let model = cn.init()
let lm = LineModel()
lm.width = CGFloat(resultSet.doubleForColumn("width"))
lm.colorIndex = NSInteger(resultSet.intForColumn("colorIndex"))
let points = try! NSJSONSerialization.JSONObjectWithData((resultSet.objectForColumnName("points") as! String).dataUsingEncoding(NSUTF8StringEncoding)!, options:.AllowFragments) as! [String]
var x:CGFloat = 0.0
var y:CGFloat = 0.0
for pointStr in points {
let xy = pointStr.componentsSeparatedByString(",")
x = CGFloat((xy[0] as NSString).doubleValue)
y = CGFloat((xy[1] as NSString).doubleValue)
lm.points.append(CGPointMake( x, y))
}
let count = UnsafeMutablePointer<UInt32>.alloc(1)
count.initialize(0)
let propertyList = class_copyPropertyList( lm.classForCoder, count)
for i in 0...(Int(count.memory) - 1) {
let char = property_getName(propertyList[Int(i)])
print("Property---->\(NSString.init(UTF8String: char))")
}
models.append(lm)
}
}
return models
}
func executeSQL(SQLString sql:String) -> Bool {
var result = false
fmdbQueue?.inDatabase(){
db in
result = db.executeUpdate(sql, withArgumentsInArray: nil)
}
return result
}
}
|
82345d2536188d9f047e9f652b159fb3
| 31.940789 | 205 | 0.530657 | false | false | false | false |
hironytic/FormulaCalc
|
refs/heads/master
|
FormulaCalc/View/SheetList/SheetListViewController.swift
|
mit
|
1
|
//
// SheetListViewController.swift
// FormulaCalc
//
// Copyright (c) 2016, 2017 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import RxSwift
import RxCocoa
public class SheetListElementCell: UITableViewCell {
private var _disposeBag: DisposeBag?
public var viewModel: ISheetListElementViewModel? {
didSet {
_disposeBag = nil
guard let viewModel = viewModel else { return }
let disposeBag = DisposeBag()
if let textLabel = textLabel {
viewModel.title
.bind(to: textLabel.rx.text)
.disposed(by: disposeBag)
}
_disposeBag = disposeBag
}
}
public override func prepareForReuse() {
super.prepareForReuse()
self.viewModel = nil
}
}
public class SheetListViewController: UITableViewController {
private var _disposeBag: DisposeBag?
public var viewModel: ISheetListViewModel?
@IBOutlet weak var newButton: UIBarButtonItem!
public override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
public override func viewWillAppear(_ animated: Bool) {
bindViewModel()
}
public override func viewDidDisappear(_ animated: Bool) {
_disposeBag = nil
}
private func bindViewModel() {
_disposeBag = nil
guard let viewModel = viewModel else { return }
let disposeBag = DisposeBag()
let dataSource = SheetListDataSource()
viewModel.sheetList
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
viewModel.message
.bind(to: transitioner)
.disposed(by: disposeBag)
newButton.rx.tap
.bind(to: viewModel.onNew)
.disposed(by: disposeBag)
tableView.rx.modelSelected(ISheetListElementViewModel.self)
.bind(to: viewModel.onSelect)
.disposed(by: disposeBag)
tableView.rx.modelDeleted(ISheetListElementViewModel.self)
.bind(to: viewModel.onDelete)
.disposed(by: disposeBag)
_disposeBag = disposeBag
}
}
public class SheetListDataSource: NSObject {
fileprivate var _itemModels: Element = []
}
extension SheetListDataSource: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _itemModels.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: R.Id.cell, for: indexPath) as! SheetListElementCell
let element = _itemModels[(indexPath as NSIndexPath).row]
cell.viewModel = element
return cell
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return tableView.isEditing
}
public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return false
}
}
extension SheetListDataSource: RxTableViewDataSourceType {
public typealias Element = [ISheetListElementViewModel]
public func tableView(_ tableView: UITableView, observedEvent: Event<Element>) {
UIBindingObserver(UIElement: self) { (dataSource, element) in
dataSource._itemModels = element
tableView.reloadData()
}
.on(observedEvent)
}
}
extension SheetListDataSource: SectionedViewDataSourceType {
public func model(at indexPath: IndexPath) throws -> Any {
precondition(indexPath.section == 0)
return _itemModels[indexPath.row]
}
}
|
8a2f9d229a161969ca2902697ccfc0bf
| 31.915584 | 116 | 0.661669 | false | false | false | false |
Bargetor/beak
|
refs/heads/master
|
Beak/Beak/extension/BBArrayExtension.swift
|
mit
|
1
|
//
// BBArrayExtension.swift
// Beak
//
// Created by 马进 on 2016/12/13.
// Copyright © 2016年 马进. All rights reserved.
//
import Foundation
public func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) }
if next.hashValue != i { return nil }
i += 1
return next
}
}
public func arrayEnum<T: Hashable>(_ em: T.Type) -> Array<T> {
var array: [T] = []
for e in iterateEnum(em){
array.append(e)
}
return array
}
extension Array{
public func random() -> Element?{
if self.isEmpty { return nil }
let randomIndex = Int(arc4random_uniform(UInt32(self.count)))
return self[randomIndex]
}
public func subArrayWithRange(_ location: Int, length: Int) -> Array<Element>?{
let count = self.count
if(location >= count){
return nil
}
var result = Array()
let rangeEnd = location + length
let end = rangeEnd >= count ? count : rangeEnd
for item in self[location ..< end]{
result.append(item)
}
return result
}
public func toUnsafeMutablePointer() -> UnsafeMutablePointer<Element>{
let points: UnsafeMutablePointer<Element> = UnsafeMutablePointer.allocate(capacity: self.count)
for i in 0 ..< self.count{
let item = self[i]
points[i] = item
}
return points
}
public mutating func appendAll(_ elements: [Element]?){
guard let elements = elements else{
return
}
for element in elements{
self.append(element)
}
}
public func difference <T: Equatable> (values: [T]...) -> [T] {
var result = [T]()
elements: for e in self {
if let element = e as? T {
for value in values {
// if a value is in both self and one of the values arrays
// jump to the next iteration of the outer loop
if value.contains(element) {
continue elements
}
}
// element it's only in self
result.append(element)
}
}
return result
}
}
extension Array where Element: Equatable {
/**
从array中删除一个对象
- parameter object: 要删除的对象
*/
public mutating func removeObject(_ object: Element) {
if let index = self.index(of: object) {
self.remove(at: index)
}
}
public func toUnsafeMutablePointer() -> UnsafeMutablePointer<Element>{
let pointer: UnsafeMutablePointer<Element> = UnsafeMutablePointer(mutating: self)
return pointer
}
}
|
4e16dd2ab54034f7498165964a684baa
| 24.333333 | 103 | 0.522605 | false | false | false | false |
mayongl/SpaceCannon
|
refs/heads/master
|
SpaceCannon/SpaceCannon/GameViewController.swift
|
mit
|
1
|
//
// GameViewController.swift
// SpaceCannon
//
// Created by Yonglin Ma on 2/15/17.
// Copyright © 2017 Sixlivesleft. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = false
view.showsFPS = true
view.showsNodeCount = true
//view.showsPhysics = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
|
d897b8b30d90c000b8e2c388478b34df
| 24.589286 | 77 | 0.579204 | false | false | false | false |
lorenzodonini/Motius
|
refs/heads/master
|
Motius/Motius/Classes/View/UsecaseViewController.swift
|
apache-2.0
|
1
|
//
// UsecaseViewController.swift
// Motius
//
// Created by Lorenzo Donini on 18/08/16.
// Copyright © 2016 Motius GmbH. All rights reserved.
//
import UIKit
import FontAwesome_swift
class UsecaseViewController: UIViewController {
private let apiManager = ApiManager()
private var usecases: [Usecase]?
private let defaultUsecaseIcons = [
UIImage.fontAwesomeIconWithName(.FileText, textColor: UIColor.blackColor(), size: CGSizeMake(55, 55)),
UIImage.fontAwesomeIconWithName(.Cloud, textColor: UIColor.blackColor(), size: CGSizeMake(55, 55)),
UIImage.fontAwesomeIconWithName(.Mobile, textColor: UIColor.blackColor(), size: CGSizeMake(55, 55)),
UIImage.fontAwesomeIconWithName(.PieChart, textColor: UIColor.blackColor(), size: CGSizeMake(55, 55))
]
private static let cellIdentifier = "usecaseCell"
@IBOutlet var tableView: UITableView!
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(UsecaseViewController.loadUsecases), forControlEvents: UIControlEvents.ValueChanged)
return refreshControl
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.addSubview(refreshControl)
//Load use cases through the network
loadUsecases()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc internal func loadUsecases() {
refreshControl.beginRefreshing()
//Call REST API asynchronously
apiManager.getUsecases { (usecases: [Usecase]?, error: ErrorType?) in
if let usecases = usecases {
self.usecases = usecases
} else if let error = error {
self.usecases = nil
print("Error occurred while receiving usecases: \(error)")
} else {
self.usecases = nil
print("Unknown error occurred!")
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.refreshControl.endRefreshing()
})
}
}
}
extension UsecaseViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//TODO: implement
}
}
extension UsecaseViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usecases?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(UsecaseViewController.cellIdentifier, forIndexPath: indexPath)
if let usecase = usecases?[indexPath.row],
let usecaseCell = cell as? UsecaseViewCell {
usecaseCell.titleLabel.text = usecase.title
usecaseCell.bodyLabel.text = usecase.body
usecaseCell.usecaseImageView.image = defaultUsecaseIcons[indexPath.row % defaultUsecaseIcons.count]
return usecaseCell
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 64.0
}
}
|
bfe549aeedb158bc82ac069397d53fbd
| 35.808511 | 141 | 0.661561 | false | false | false | false |
LiulietLee/BilibiliCD
|
refs/heads/master
|
Shared/CoreDataStorage.swift
|
gpl-3.0
|
1
|
//
// CoreDataStorage.swift
// TutorialAppGroup
//
// Created by Maxim on 10/18/15.
// Copyright © 2015 Maxim. All rights reserved.
//
import CoreData
import Foundation
final class CoreDataStorage {
// MARK: - Shared Instance
public static let sharedInstance = CoreDataStorage()
// MARK: - Initialization
private init() {
NotificationCenter.default.addObserver(self, selector: #selector(contextDidSavePrivateQueueContext(_:)), name: .NSManagedObjectContextDidSave, object: privateQueueContext)
NotificationCenter.default.addObserver(self, selector: #selector(contextDidSaveMainQueueContext(_:)), name: .NSManagedObjectContextDidSave, object: mainQueueContext)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Notifications
@objc func contextDidSavePrivateQueueContext(_ notification: Notification) {
synced {
self.mainQueueContext.perform {
self.mainQueueContext.mergeChanges(fromContextDidSave: notification)
}
}
}
@objc func contextDidSaveMainQueueContext(_ notification: Notification) {
synced {
self.privateQueueContext.perform {
self.privateQueueContext.mergeChanges(fromContextDidSave: notification)
}
}
}
private func synced(_ lock: AnyObject = CoreDataStorage.sharedInstance, closure: () -> Void) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
// MARK: - Core Data Saving support
public func saveContext(_ context: NSManagedObjectContext?) {
if let moc = context, moc.hasChanges {
try? moc.save()
}
}
// MARK: - Core Data stack
private lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "BCD", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
private let migrationOptions = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: urlInContainer, options: migrationOptions)
} catch {
fatalError("Unresolved error \(error), \(String(describing: error._userInfo))")
}
return coordinator
}()
// MARK: - NSManagedObject Contexts
/// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application).
public private(set) lazy var mainQueueContext: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}()
/// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application).
private lazy var privateQueueContext: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}()
}
extension CoreDataStorage {
private static let name = "BCD.sqlite"
var urlInContainer: URL {
let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.Future-Code-Institute.bili_cita_group")!
let url = directory.appendingPathComponent(CoreDataStorage.name)
return url
}
var urlInDocuments: URL {
return applicationDocumentsDirectory.appendingPathComponent(CoreDataStorage.name)
}
/// The directory the application uses to store the Core Data store file. This code uses a directory named 'Bundle identifier' in the application's documents Application Support directory.
private var applicationDocumentsDirectory: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}
}
#if canImport(MaterialKit)
import MaterialKit
func display(_ error: Error) {
var message = error.localizedDescription
if let exception = error._userInfo?["NSUnderlyingException"] as? NSException,
let reason = exception.reason {
message += "(\(reason))"
}
display(message)
}
func display(_ message: String) {
MKSnackbar(withTitle: message, withDuration: nil, withTitleColor: nil, withActionButtonTitle: nil, withActionButtonColor: nil).show()
}
extension CoreDataStorage {
func saveCoreDataModelToDocuments() {
do {
if FileManager.default.fileExists(atPath: urlInDocuments.path) {
try FileManager.default.removeItem(at: urlInDocuments)
}
let saveAsCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
try saveAsCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: urlInContainer, options: migrationOptions)
try saveAsCoordinator.migratePersistentStore(saveAsCoordinator.persistentStore(for: urlInContainer)!, to: urlInDocuments, options: nil, withType: NSSQLiteStoreType)
display("导出成功")
} catch {
display(error)
}
}
func replaceCoreDataModelWithOneInDocuments() {
if FileManager.default.fileExists(atPath: urlInDocuments.path) {
do {
try persistentStoreCoordinator.remove(persistentStoreCoordinator.persistentStore(for: urlInContainer)!)
try persistentStoreCoordinator.replacePersistentStore(at: urlInContainer, destinationOptions: nil, withPersistentStoreFrom: urlInDocuments, sourceOptions: nil, ofType: NSSQLiteStoreType)
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: urlInContainer, options: migrationOptions)
display("导入成功")
} catch {
display(error)
}
} else {
display("没有数据可以导入")
}
}
}
#endif
|
380c98a00352815b38819b4efe52abd1
| 40.875 | 290 | 0.699645 | false | false | false | false |
RxLeanCloud/rx-lean-swift
|
refs/heads/master
|
src/RxLeanCloudSwift/Internal/Encoding/AVDecoder.swift
|
mit
|
1
|
//
// AVDecoder.swift
// RxLeanCloudSwift
//
// Created by WuJun on 24/05/2017.
// Copyright © 2017 LeanCloud. All rights reserved.
//
import Foundation
public class AVDecoder: IAVDecoder {
public func decode(value: Any) -> Any {
if value is [String: Any] {
if let dataMap = value as? [String: Any] {
if dataMap["__type"] == nil {
var newMap = [String: Any]()
for (key, value) in dataMap {
newMap[key] = decode(value: value)
}
return newMap
} else {
if let typeString = dataMap["__type"] as? String {
if typeString == "Date" {
let formatter = AVCorePlugins.dateFormatter
let dateString = dataMap["iso"] as! String
return formatter.date(from: dateString) as Any
} else if typeString == "Pointer" {
let className = dataMap["className"] as! String
let objectId = dataMap["objectId"] as! String
return self.decodePotinter(className: className, objectId: objectId)
}
}
}
}
}
return value
}
public func decodePotinter(className: String, objectId: String) -> RxAVObject {
return RxAVObject.createWithoutData(classnName: className, objectId: objectId)
}
public func clone(dictionary: [String: Any]) -> [String: Any] {
var cloned = [String: Any]()
for (key, value) in dictionary {
cloned[key] = value
}
return cloned
}
}
|
7940736a4a572788d34710743ef22985
| 33.843137 | 96 | 0.487901 | false | false | false | false |
sovereignshare/fly-smuthe
|
refs/heads/master
|
Fly Smuthe/Fly Smuthe/DateUtility.swift
|
gpl-3.0
|
1
|
//
// DateUtility.swift
// Fly Smuthe
//
// Created by Adam M Rivera on 3/22/15.
// Copyright (c) 2015 Adam M Rivera. All rights reserved.
//
import Foundation
class DateUtility {
class func toUTCDate(dateString: String) -> NSDate {
let dateFormatter = NSDateFormatter();
let timeZone = NSTimeZone(name: "CDT");
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
dateFormatter.timeZone = timeZone;
let date = dateFormatter.dateFromString(dateString);
return date!;
}
class func toLocalDateString(date: NSDate!) -> String {
if(date == nil){
return "";
}
let dateFormatter = NSDateFormatter();
let timeZone = NSTimeZone.defaultTimeZone();
dateFormatter.timeZone = timeZone;
dateFormatter.dateFormat = "MMM d, h:mma";
return dateFormatter.stringFromDate(date);
}
class func toServerDateString(date: NSDate!) -> String {
if(date == nil){
return "";
}
let dateFormatter = NSDateFormatter();
let timeZone = NSTimeZone(name: "CDT");
dateFormatter.timeZone = timeZone;
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
return dateFormatter.stringFromDate(date);
}
}
extension NSDate: Comparable {
}
func + (date: NSDate, timeInterval: NSTimeInterval) -> NSDate {
return date.dateByAddingTimeInterval(timeInterval)
}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
if lhs.compare(rhs) == .OrderedSame {
return true
}
return false
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
if lhs.compare(rhs) == .OrderedAscending {
return true
}
return false
}
extension NSTimeInterval {
var withMinutes: NSTimeInterval {
let secondsInAMinute = 60 as NSTimeInterval
return self * secondsInAMinute;
}
var second: NSTimeInterval {
return self.seconds
}
var seconds: NSTimeInterval {
return self
}
var minute: NSTimeInterval {
return self.minutes
}
var minutes: NSTimeInterval {
let secondsInAMinute = 60 as NSTimeInterval
return self / secondsInAMinute
}
var hours: NSTimeInterval {
let secondsInAMinute = 60 as NSTimeInterval
let minutesInAnHour = 60 as NSTimeInterval
return self / secondsInAMinute / minutesInAnHour
}
var day: NSTimeInterval {
return self.days
}
var days: NSTimeInterval {
let secondsInADay = 86_400 as NSTimeInterval
return self / secondsInADay
}
var fromNowFriendlyString: String {
var returnStr = "";
if(self > 0){
if(self.days >= 1){
returnStr = String(Int(floor(self.days))) + " day";
} else if (self.hours >= 1){
let hours = Int(floor(self.hours));
returnStr = String(hours) + " hour" + (hours > 1 ? "s" : "");
} else if (self.minutes >= 1){
let minutes = Int(floor(self.minutes));
returnStr = String(minutes) + " minute" + (minutes > 1 ? "s" : "");
} else if (self >= 1){
let seconds = Int(self);
returnStr = String(seconds) + " second" + (seconds > 1 ? "s" : "");
}
}
return returnStr;
}
var timerString: String {
let interval = Int(self);
let seconds = interval % 60;
let minutes = (interval / 60) % 60;
return String(format: "%02d:%02d", minutes, seconds)
}
var fromNow: NSDate {
let timeInterval = self
return NSDate().dateByAddingTimeInterval(timeInterval)
}
func from(date: NSDate) -> NSDate {
let timeInterval = self
return date.dateByAddingTimeInterval(timeInterval)
}
var ago: NSDate {
let timeInterval = self
return NSDate().dateByAddingTimeInterval(-timeInterval)
}
}
|
4bf5b1e7fd199cc358ca1abb36224823
| 26.786207 | 83 | 0.578699 | false | false | false | false |
MrDeveloper4/TestProject-GitHubAPI
|
refs/heads/master
|
Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallRotateChase.swift
|
mit
|
2
|
//
// NVActivityIndicatorAnimationBallRotateChase.swift
// NVActivityIndicatorViewDemo
//
// Created by ChildhoodAndy on 15/12/7.
// Copyright © 2015年 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationBallRotateChase: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let circleSize = size.width / 5;
// Draw circles
for i in 0 ..< 5 {
let factor = Float(i) * 1.0 / 5
let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let animation = rotateAnimation(factor, x: layer.bounds.size.width / 2, y: layer.bounds.size.height / 2, size: CGSizeMake(size.width - circleSize, size.height - circleSize))
circle.frame = CGRectMake(0, 0, circleSize, circleSize)
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
func rotateAnimation(rate: Float, x: CGFloat, y: CGFloat, size: CGSize) -> CAAnimationGroup {
let duration: CFTimeInterval = 1.5
let fromScale = 1 - rate
let toScale = 0.2 + rate
let timeFunc = CAMediaTimingFunction(controlPoints: 0.5, 0.15 + rate, 0.25, 1.0)
// Scale animation
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.duration = duration
scaleAnimation.repeatCount = HUGE
scaleAnimation.fromValue = fromScale
scaleAnimation.toValue = toScale
// Position animation
let positionAnimation = CAKeyframeAnimation(keyPath: "position")
positionAnimation.duration = duration
positionAnimation.repeatCount = HUGE
positionAnimation.path = UIBezierPath(arcCenter: CGPoint(x: x, y: y), radius: size.width / 2, startAngle: 3 * CGFloat(M_PI) * 0.5, endAngle: 3 * CGFloat(M_PI) * 0.5 + 2 * CGFloat(M_PI), clockwise: true).CGPath
// Aniamtion
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, positionAnimation]
animation.timingFunction = timeFunc
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
return animation
}
}
|
f68970d5c55b83d1220577d2e708356d
| 40.413793 | 217 | 0.654455 | false | false | false | false |
Perfectorium/TaskTracker
|
refs/heads/master
|
TaskTracker/TaskTracker/Extensions/Other Extensions.swift
|
mit
|
1
|
//
// Other Extensions.swift
// eurojackpot
//
// Created by Valeriy Jefimov on 13.04.17.
// Copyright © 2017 Perfectorium. All rights reserved.
//
import UIKit
extension Int {
var asWord:String {
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
return "\(formatter.string(from: NSNumber(value:self))!)"
}
static func random(from: Int, to: Int) -> Int {
return Int(arc4random_uniform(UInt32(to))) - from
}
}
extension Data {
// func decryptWith(password:String) throws -> String {
//
// let decryptedNSData = try RNCryptor.decrypt(data: self,
// withPassword: password)
// return String(data: decryptedNSData,
// encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
// }
func toBase64() -> String {
return self.base64EncodedString()
}
}
extension Date {
func isLaterThanNow() -> Bool {
return self.compare(Date()) == .orderedDescending
}
func isLaterThanDate() -> Bool {
return self.compare(Date(timeIntervalSince1970: 1467244800)) == .orderedDescending
}
func isFriday() -> Bool {
let calendar = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar!.components([.weekday], from: self)
return components.weekday == 6
}
}
extension String {
init(unicodeScalar: UnicodeScalar) {
self.init(Character(unicodeScalar))
}
init?(unicodeCodepoint: Int) {
if let unicodeScalar = UnicodeScalar(unicodeCodepoint) {
self.init(unicodeScalar: unicodeScalar)
} else {
return nil
}
}
static func +(lhs: String, rhs: Int) -> String {
return lhs + String(unicodeCodepoint: rhs)!
}
static func +=(lhs: inout String, rhs: Int) {
lhs = lhs + rhs
}
func randomString(length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
var isValidNumber: Bool {
guard let num = Int(self)
else
{
return false
}
return num < 51 && num > 0
}
var isValidENumber: Bool {
guard let num = Int(self)
else
{
return false
}
return num < 11 && num > 0
}
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
//
//
//
// func encryptWith(password:String)-> Data? {
// let data: Data = self.data(using: String.Encoding.utf8)!
// let text = RNCryptor.encrypt(data: data as Data,
// withPassword: password)
// return text
// }
var toDate:NSDate {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy, HH:mm"
guard dateFormatter.date(from: self) != nil else
{
return NSDate.distantPast as NSDate
}
return dateFormatter.date(from: self)! as NSDate
}
var decrementNum :String {
if let myInteger = Int(self)
{
return NSNumber(value:myInteger - 1).toString
}
else
{
print("'\(self)' did not convert to an Int")
return ""
}
}
var number :Int {
if let myInteger = Int(self)
{
return myInteger
}
else
{
print("'\(self)' did not convert to an Int")
return 0
}
}
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
func localized(withComment:String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
}
var isValid: Bool {
let length = self.characters.count
return (length > 0)
}
func isValidEmail() -> Bool {
// print("validate calendar: \(testStr)")
let emailRegEx = "^\\s*[a-zA-Z0-9\\.]+@[a-zA-Z0-9]+(\\-)?[a-zA-Z0-9]+(\\.)?[a-zA-Z0-9]{2,6}?\\.[a-zA-Z]{2,6}\\s*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
func capitalizingFirstLetter() -> String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst())
return first + other
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
func isValidPassword() -> Bool {
let passwordRegEx = "^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}$"
let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegEx)
return passwordTest.evaluate(with: self)
}
}
extension UIColor {
static func randomColor(withAlpha alpha: CGFloat = 1.0) -> UIColor {
return UIColor(red: CGFloat(drand48()),
green: CGFloat(drand48()),
blue: CGFloat(drand48()),
alpha: alpha)
}
}
extension UITableView {
func setOffsetToBottom(animated: Bool) {
let point = CGPoint(x: 0, y: self.contentSize.height - self.frame.size.height)
self.setContentOffset(point, animated: true)
}
func scrollToSection(section:Int, scrollPosition: UITableViewScrollPosition,animated: Bool) {
if section > 0
{
let indexPath = NSIndexPath(item: self.numberOfRows(inSection: 0) , section: section - 1)
self.scrollToRow(at: indexPath as IndexPath, at:scrollPosition , animated: animated)
}
}
func scrollToLastRow(animated: Bool) {
self.scrollToSection(section: self.numberOfSections , scrollPosition:.bottom , animated: animated)
}
}
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
self.layer.masksToBounds = newValue > 0
}
}
func addBorderView(width:CGFloat = 0.0,
color:CGColor){
self.layer.borderColor = color
self.layer.borderWidth = width
}
func addShadowView(width:CGFloat = 0.0,
height:CGFloat = 2.0,
Opacidade:Float = 0.7,
maskToBounds:Bool = false,
radius:CGFloat = 0.5){
self.layer.shadowColor = UIColor.gray.cgColor
self.layer.shadowOffset = CGSize(width: width, height: height)
self.layer.shadowRadius = radius
self.layer.shadowOpacity = Opacidade
self.layer.masksToBounds = maskToBounds
}
func blink() {
self.blink(scale: 1.1)
}
func blink(scale:CGFloat) {
UIView.animate(withDuration: 0.1, animations: {() -> Void in
self.transform = CGAffineTransform(scaleX: scale, y: scale)
}, completion: {(_ finished: Bool) -> Void in
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: .curveEaseIn, animations: {
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
},
completion: nil)
})
}
public func blink(color:UIColor) {
let previosColor = self.backgroundColor!
self.blink(scale: 1.05)
UIView.animate(withDuration: 0.3,
delay: 0.01,
options: [.curveEaseOut],
animations: {
self.backgroundColor = color
}) { (suc:Bool) in
self.backgroundColor = previosColor
}
}
}
extension UIScrollView {
func fitView() {
var contentRect = CGRect(x: 0, y: 0, width: 0, height: 0)
for view in self.subviews {
contentRect = contentRect.union(view.frame)
}
self.contentSize = contentRect.size
}
}
extension UITextField {
var isValidENumber: Bool {
guard let num = Int(self.text!)
else
{
return false
}
return num < 11 && num > 0
}
var isValidNumber: Bool {
guard let num = Int(self.text!)
else
{
return false
}
return num < 51 && num > 0
}
@IBInspectable var borderColor: UIColor {
set {
self.layer.borderColor = newValue.cgColor
}
get {
return UIColor.init(cgColor: layer.borderColor!)
}
}
@IBInspectable var borderWidth : CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
}
extension UIButton {
@IBInspectable var borderColor: UIColor {
set {
self.layer.borderColor = newValue.cgColor
}
get {
return UIColor.init(cgColor: layer.borderColor!)
}
}
@IBInspectable var borderWidth : CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
func blinkAndRepeatStart (){
let pulseAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseAnimation.duration = 1
pulseAnimation.fromValue = 0.9
pulseAnimation.toValue = 1
pulseAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = Float.greatestFiniteMagnitude
self.layer.add(pulseAnimation, forKey: "animateOpacity")
}
func blinkAndRepeatFinish () {
UIView.animate(withDuration: 0.5) {
self.layer.removeAllAnimations()
}
}
override func blink(scale:CGFloat) {
UIView.animateKeyframes(withDuration: 0.3,
delay: 0,
options: [.allowUserInteraction],
animations: {
UIView.addKeyframe(withRelativeStartTime: 0,
relativeDuration: 0.15,
animations: {
self.transform = CGAffineTransform(scaleX: scale, y: scale )
})
UIView.addKeyframe(withRelativeStartTime: 0.15,
relativeDuration: 0.15,
animations: {
self.transform = CGAffineTransform(scaleX: 1, y: 1 )
})
}) { (suc) in
}
}
func setButtonBold() {
self.titleLabel?.font = UIFont(name: "Titillium-Bold", size: 18)
}
}
public extension UIDevice {
public func platform() -> String {
var sysinfo = utsname()
uname(&sysinfo) // ignore return value
return String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters)
}
public var hasHapticFeedback: Bool {
return ["iPhone9,1", "iPhone9,3", "iPhone9,2", "iPhone9,4"].contains(platform())
}
}
public extension Array {
func filterDuplicates( includeElement: @escaping (_ lhs:Element, _ rhs:Element) -> Bool) -> [Element]{
var results = [Element]()
forEach { (element) in
let existingElements = results.filter {
return includeElement(element, $0)
}
if existingElements.count == 0 {
results.append(element)
}
}
return results
}}
public extension DispatchQueue {
private static var _onceTracker = [String]()
public class func once(token: String, block:(Void)->Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
if _onceTracker.contains(token) {
return
}
_onceTracker.append(token)
block()
}
}
extension CALayer {
var borderUIColor: UIColor {
set {
self.borderColor = newValue.cgColor
}
get {
return UIColor(cgColor: self.borderColor!)
}
}
}
extension UITextField {
public func blinkBorder(color:UIColor) {
self.layer.masksToBounds = true;
let previosColor = self.layer.borderUIColor
let colorAnimation = CABasicAnimation(keyPath: "borderColor")
colorAnimation.fromValue = color
colorAnimation.toValue = color.cgColor
self.layer.borderColor = color.cgColor
let widthAnimation = CABasicAnimation(keyPath: "borderWidth")
widthAnimation.fromValue = 1
widthAnimation.toValue = 1
widthAnimation.duration = 4
self.layer.borderWidth = 1
let bothAnimations = CAAnimationGroup()
bothAnimations.repeatCount = 2
bothAnimations.duration = 0.3
bothAnimations.animations = [colorAnimation, widthAnimation]
bothAnimations.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.layer.add(bothAnimations, forKey: "color and width")
self.layer.borderUIColor = previosColor
}
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "",
attributes:[NSForegroundColorAttributeName: newValue!])
}
}
}
extension NSNumber{
var toString: String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.minimumFractionDigits = 0
numberFormatter.maximumFractionDigits = 0
return numberFormatter.string(from: self)!
}
}
extension UIViewController {
func showAlert(title:String,
message:String,
buttonTitle:String,
completionHandler: @escaping () -> Void) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title.localized,
message: message.localized,
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: buttonTitle.localized,
style: .destructive,
handler: { (action) in
completionHandler()
}))
self.present(alert, animated: true,
completion: nil)
}
}
func showAlert(title:String,message:String) {
let alert = UIAlertController(title: title.localized,
message: message.localized,
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Try again".localized,
style: .destructive,
handler: nil))
self.present(alert, animated: true,
completion: nil)
}
}
|
8c45d411d13cdb25e750f96f5da6d24a
| 29.078947 | 147 | 0.514961 | false | false | false | false |
Binlogo/One3-iOS-Swift
|
refs/heads/master
|
One3-iOS/Extensions/UI/UIImageViewExtensions.swift
|
mit
|
2
|
//
// UIImageViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/25/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import UIKit
// MARK: - Methods
extension UIImageView {
/// SwifterSwift: Set image from a URL.
///
/// - Parameters:
/// - url: URL of image.
/// - contentMode: imageView content mode (default is .scaleAspectFit).
/// - placeHolder: optional placeholder image
/// - completionHandler: optional completion handler to run when download finishs (default is nil).
public func download(from url: URL,
contentMode: UIViewContentMode = .scaleAspectFit,
placeholder: UIImage? = nil,
completionHandler: ((UIImage?, Error?) -> Void)? = nil) {
image = placeholder
self.contentMode = contentMode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else {
completionHandler?(nil, error)
return
}
DispatchQueue.main.async() { () -> Void in
self.image = image
completionHandler?(image, nil)
}
}.resume()
}
/// SwifterSwift: Make image view blurry
///
/// - Parameter withStyle: UIBlurEffectStyle (default is .light).
func blur(withStyle: UIBlurEffectStyle = .light) {
let blurEffect = UIBlurEffect(style: withStyle)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
self.addSubview(blurEffectView)
self.clipsToBounds = true
}
/// SwifterSwift: Blurred version of an image view
///
/// - Parameter withStyle: UIBlurEffectStyle (default is .light).
/// - Returns: blurred version of self.
func blurred(withStyle: UIBlurEffectStyle = .light) -> UIImageView {
return self.blurred(withStyle: withStyle)
}
}
|
da6d986a8c0196edfafd00d9fa356494
| 31.246154 | 103 | 0.683206 | false | false | false | false |
alexandreblin/ios-car-dashboard
|
refs/heads/master
|
CarDash/TripInfoView.swift
|
mit
|
1
|
//
// TripInfoView.swift
// CarDash
//
// Created by Alexandre Blin on 14/01/2017.
// Copyright © 2017 Alexandre Blin. All rights reserved.
//
import UIKit
/// View containing 3 icons and values to display trip computer data.
/// Two modes are available: instant view and trip view (which determines
/// which icons to display above the values)
class TripInfoView: UIView {
enum Mode {
case instant
case trip
}
@IBOutlet weak var label1: UILabel?
@IBOutlet weak var label2: UILabel?
@IBOutlet weak var label3: UILabel?
@IBOutlet private weak var titleLabel: UILabel?
@IBOutlet private weak var image1: UIImageView?
@IBOutlet private weak var image2: UIImageView?
@IBOutlet private weak var image3: UIImageView?
static func view(withTitle title: String, mode: Mode) -> TripInfoView {
guard let view = Bundle.main.loadNibNamed("TripInfoView", owner: nil, options: nil)?.first as? TripInfoView else {
fatalError("Could not load TripInfoView from nib")
}
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.titleLabel?.text = title
switch mode {
case .instant:
view.image1?.image = UIImage(named: "icon_gasstation")
view.image2?.image = UIImage(named: "icon_fuel")
view.image3?.image = UIImage(named: "icon_temperature")
case .trip:
view.image1?.image = UIImage(named: "icon_distance")
view.image2?.image = UIImage(named: "icon_fuel")
view.image3?.image = UIImage(named: "icon_speed")
}
return view
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clear
}
}
|
acd6e593b5140cb6ea0b3f27bb14d1f5
| 29.206897 | 122 | 0.645548 | false | false | false | false |
AimobierCocoaPods/OddityUI
|
refs/heads/master
|
Classes/Resources/WaitTipsView/NoInterestView.swift
|
mit
|
1
|
//
// NoInterestView.swift
// Journalism
//
// Created by Mister on 16/6/15.
// Copyright © 2016年 aimobier. All rights reserved.
//
import UIKit
import SnapKit
class NoInterestView: UIView {
static let shareNoInterest:NoInterestView = { return NoInterestView(frame: CGRect.zero)}()
lazy var label = UILabel()
lazy var imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
self.clipsToBounds = true
self.layer.cornerRadius = 8
self.backgroundColor = UIColor.black.withAlphaComponent(0.8)
self.imageView.image = UIImage.OddityImageByName("About")
self.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.centerY.equalTo(self.snp.centerY)
make.leftMargin.equalTo(20)
}
label.text = "将减少此类推荐"
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = UIColor.white
label.textAlignment = .center
self.addSubview(label)
label.snp.makeConstraints { (make) in
make.centerY.equalTo(self.snp.centerY)
make.leftMargin.equalTo(self.imageView.snp.right).offset(15)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
69a00c0596d3c688be6b9b0fd56b562f
| 26.076923 | 94 | 0.605824 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
stdlib/public/core/InputStream.swift
|
apache-2.0
|
10
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Returns `Character`s read from standard input through the end of the
/// current line or until EOF is reached, or `nil` if EOF has already been
/// reached.
///
/// If `stripNewline` is `true`, newline characters and character
/// combinations will be stripped from the result. This is the default.
///
/// Standard input is interpreted as `UTF-8`. Invalid bytes
/// will be replaced by Unicode [replacement characters](http://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character).
@warn_unused_result
public func readLine(stripNewline stripNewline: Bool = true) -> String? {
var linePtr: UnsafeMutablePointer<CChar> = nil
var readBytes = swift_stdlib_readLine_stdin(&linePtr)
if readBytes == -1 {
return nil
}
_sanityCheck(readBytes >= 0,
"unexpected return value from swift_stdlib_readLine_stdin")
if readBytes == 0 {
return ""
}
if stripNewline {
// FIXME: Unicode conformance. To fix this, we need to reimplement the
// code we call above to get a line, since it will only stop on LF.
//
// <rdar://problem/20013999> Recognize Unicode newlines in readLine()
//
// Recognize only LF and CR+LF combinations for now.
let cr = CChar(_ascii8("\r"))
let lf = CChar(_ascii8("\n"))
if readBytes == 1 && linePtr[0] == lf {
return ""
}
if readBytes >= 2 {
switch (linePtr[readBytes - 2], linePtr[readBytes - 1]) {
case (cr, lf):
readBytes -= 2
break
case (_, lf):
readBytes -= 1
break
default:
()
}
}
}
let result = String._fromCodeUnitSequenceWithRepair(UTF8.self,
input: UnsafeMutableBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(linePtr),
count: readBytes)).0
_swift_stdlib_free(linePtr)
return result
}
|
e399f0f53a5762e08ad79509b03914f3
| 33.558824 | 134 | 0.622979 | false | false | false | false |
moozzyk/SignalR-Client-Swift
|
refs/heads/master
|
Sources/SignalRClient/Logger.swift
|
mit
|
1
|
//
// Logger.swift
// SignalRClient
//
// Created by Pawel Kadluczka on 8/2/18.
// Copyright © 2018 Pawel Kadluczka. All rights reserved.
//
import Foundation
public enum LogLevel: Int {
case error = 1
case warning = 2
case info = 3
case debug = 4
}
/**
Protocol for implementing loggers.
*/
public protocol Logger {
/**
Invoked by the client to write a log entry.
- parameter logLevel: the log level of the entry to write
- parameter message: log entry
*/
func log(logLevel: LogLevel, message: @autoclosure () -> String)
}
public extension LogLevel {
func toString() -> String {
switch (self) {
case .error: return "error"
case .warning: return "warning"
case .info: return "info"
case .debug: return "debug"
}
}
}
/**
Logger that log entries with the `print()` function.
*/
public class PrintLogger: Logger {
let dateFormatter: DateFormatter
/**
Initializes a `PrintLogger`.
*/
public init() {
dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
}
/**
Writes log entries with the `print()` function.
- parameter logLevel: the log level of the entry to write
- parameter message: log entry
*/
public func log(logLevel: LogLevel, message: @autoclosure () -> String) {
print("\(dateFormatter.string(from: Date())) \(logLevel.toString()): \(message())")
}
}
/**
Logger that discards all log entries.
*/
public class NullLogger: Logger {
/**
Initializes a `NullLogger`.
*/
public init() {
}
/**
Discards all log entries.
- parameter logLevel: ignored
- parameter message: ignored
*/
public func log(logLevel: LogLevel, message: @autoclosure () -> String) {
}
}
class FilteringLogger: Logger {
private let minLogLevel: LogLevel
private let logger: Logger
init(minLogLevel: LogLevel, logger: Logger) {
self.minLogLevel = minLogLevel
self.logger = logger
}
func log(logLevel: LogLevel, message: @autoclosure () -> String) {
if (logLevel.rawValue <= minLogLevel.rawValue) {
logger.log(logLevel: logLevel, message: message())
}
}
}
|
244ff68728429b36cfb67b61d9a1b88a
| 22.836538 | 91 | 0.623235 | false | false | false | false |
xxxAIRINxxx/ViewPagerController
|
refs/heads/master
|
Sources/ViewPagerController.swift
|
mit
|
1
|
//
// ViewPagerController.swift
// ViewPagerController
//
// Created by xxxAIRINxxx on 2016/01/05.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
public enum ObservingScrollViewType {
case none
case header
case navigationBar(targetNavigationBar : UINavigationBar)
}
public final class ViewPagerController: UIViewController {
// MARK: - Public Handler Properties
public var didShowViewControllerHandler : ((UIViewController) -> Void)?
public var updateSelectedViewHandler : ((UIView) -> Void)?
public var willBeginTabMenuUserScrollingHandler : ((UIView) -> Void)?
public var didEndTabMenuUserScrollingHandler : ((UIView) -> Void)?
public var didChangeHeaderViewHeightHandler : ((CGFloat) -> Void)?
public var changeObserveScrollViewHandler : ((UIViewController) -> UIScrollView?)?
public var didScrollContentHandler : ((CGFloat) -> Void)?
// MARK: - Custom Settings Properties
public fileprivate(set) var headerViewHeight : CGFloat = 0.0
public fileprivate(set) var tabMenuViewHeight : CGFloat = 0.0
// ScrollHeaderSupport
public fileprivate(set) var scrollViewMinPositionY : CGFloat = 0.0
public fileprivate(set) var scrollViewObservingDelay : CGFloat = 0.0
public fileprivate(set) var scrollViewObservingType : ObservingScrollViewType = .none {
didSet {
switch self.scrollViewObservingType {
case .header:
self.targetNavigationBar = nil
case .navigationBar(let targetNavigationBar):
self.targetNavigationBar = targetNavigationBar
case .none:
self.targetNavigationBar = nil
self.observingScrollView = nil
}
}
}
// MARK: - Private Properties
internal var headerView : UIView = UIView(frame: CGRect.zero)
internal var tabMenuView : PagerTabMenuView = PagerTabMenuView(frame: CGRect.zero)
internal var containerView : PagerContainerView = PagerContainerView(frame: CGRect.zero)
internal var targetNavigationBar : UINavigationBar?
internal var headerViewHeightConstraint : NSLayoutConstraint!
internal var tabMenuViewHeightConstraint : NSLayoutConstraint!
internal var viewTopConstraint : NSLayoutConstraint!
internal var observingScrollView : UIScrollView? {
willSet { self.stopScrollViewContentOffsetObserving() }
didSet { self.startScrollViewContentOffsetObserving() }
}
// MARK: - Override
deinit {
self.scrollViewObservingType = .none
}
public override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.containerView)
self.view.addSubview(self.tabMenuView)
self.view.addSubview(self.headerView)
self.setupConstraint()
self.setupHandler()
self.updateAppearance(ViewPagerControllerAppearance())
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.tabMenuView.stopScrolling(self.containerView.currentIndex() ?? 0)
self.didEndTabMenuUserScrollingHandler?(self.tabMenuView.getSelectedView())
self.tabMenuView.updateSelectedViewLayout(false)
}
// MARK: - Public Functions
public func updateAppearance(_ appearance: ViewPagerControllerAppearance) {
// Header
self.headerViewHeight = appearance.headerHeight
self.headerViewHeightConstraint.constant = self.headerViewHeight
self.headerView.subviews.forEach() { $0.removeFromSuperview() }
if let _contentsView = appearance.headerContentsView {
self.headerView.addSubview(_contentsView)
self.headerView.allPin(_contentsView)
}
// Tab Menu
self.tabMenuViewHeight = appearance.tabMenuHeight
self.tabMenuViewHeightConstraint.constant = self.tabMenuViewHeight
self.tabMenuView.updateAppearance(appearance.tabMenuAppearance)
// ScrollHeaderSupport
self.scrollViewMinPositionY = appearance.scrollViewMinPositionY
self.scrollViewObservingType = appearance.scrollViewObservingType
self.scrollViewObservingDelay = appearance.scrollViewObservingDelay
self.view.layoutIfNeeded()
}
public func setParentController(_ controller: UIViewController, parentView: UIView) {
controller.automaticallyAdjustsScrollViewInsets = false
controller.addChildViewController(self)
parentView.addSubview(self.view)
self.viewTopConstraint = parentView.addPin(self.view, attribute: .top, toView: parentView, constant: 0.0)
_ = parentView.addPin(self.view, attribute: .bottom, toView: parentView, constant: 0.0)
_ = parentView.addPin(self.view, attribute: .left, toView: parentView, constant: 0.0)
_ = parentView.addPin(self.view, attribute: .right, toView: parentView, constant: 0.0)
self.didMove(toParentViewController: controller)
}
public func addContent(_ title: String, viewController: UIViewController) {
self.tabMenuView.addTitle(title)
self.addChildViewController(viewController)
self.containerView.addViewController(viewController)
}
public func removeContent(_ viewController: UIViewController) {
guard let index = self.containerView.indexFromViewController(viewController) else { return }
if self.childViewControllers.contains(viewController) {
viewController.willMove(toParentViewController: nil)
self.tabMenuView.removeContentAtIndex(index)
self.containerView.removeContent(viewController)
viewController.removeFromParentViewController()
}
}
public func currentContent() -> UIViewController? {
return self.containerView.currentContent()
}
// MARK: - Private Functions
fileprivate func setupConstraint() {
// Header
_ = self.view.addPin(self.headerView, attribute: .top, toView: self.view, constant: 0.0)
self.headerViewHeightConstraint = self.headerView.addHeightConstraint(self.headerView, constant: self.headerViewHeight)
_ = self.view.addPin(self.headerView, attribute: .left, toView: self.view, constant: 0.0)
_ = self.view.addPin(self.headerView, attribute: .right, toView: self.view, constant: 0.0)
// Tab Menu
_ = self.view.addPin(self.tabMenuView, isWithViewTop: true, toView: self.headerView, isToViewTop: false, constant: 0.0)
self.tabMenuViewHeightConstraint = self.tabMenuView.addHeightConstraint(self.tabMenuView, constant: self.tabMenuViewHeight)
_ = self.view.addPin(self.tabMenuView, attribute: .left, toView: self.view, constant: 0.0)
_ = self.view.addPin(self.tabMenuView, attribute: .right, toView: self.view, constant: 0.0)
// Container
_ = self.view.addPin(self.containerView, isWithViewTop: true, toView: self.tabMenuView, isToViewTop: false, constant: 0.0)
_ = self.view.addPin(self.containerView, attribute: .bottom, toView: self.view, constant: 0.0)
_ = self.view.addPin(self.containerView, attribute: .left, toView: self.view, constant: 0.0)
_ = self.view.addPin(self.containerView, attribute: .right, toView: self.view, constant: 0.0)
}
fileprivate func setupHandler() {
self.tabMenuView.selectedIndexHandler = { [weak self] index in
self?.containerView.scrollToCenter(index, animated: true, animation: nil, completion: nil)
}
self.tabMenuView.updateSelectedViewHandler = { [weak self] selectedView in
self?.updateSelectedViewHandler?(selectedView)
}
self.tabMenuView.willBeginScrollingHandler = { [weak self] selectedView in
self?.willBeginTabMenuUserScrollingHandler?(selectedView)
}
self.tabMenuView.didEndTabMenuScrollingHandler = { [weak self] selectedView in
self?.didEndTabMenuUserScrollingHandler?(selectedView)
}
self.containerView.startSyncHandler = { [weak self] index in
self?.tabMenuView.stopScrolling(index)
}
self.containerView.syncOffsetHandler = { [weak self] index, percentComplete, scrollingTowards in
self?.tabMenuView.syncContainerViewScrollTo(index, percentComplete: percentComplete, scrollingTowards: scrollingTowards)
self?.didScrollContentHandler?(percentComplete)
}
self.containerView.finishSyncHandler = { [weak self] index in
self?.tabMenuView.finishSyncContainerViewScroll(index)
}
self.containerView.didShowViewControllerHandler = { [weak self] controller in
self?.didShowViewControllerHandler?(controller)
let scrollView = self?.changeObserveScrollViewHandler?(controller)
self?.observingScrollView = scrollView
}
}
fileprivate func startScrollViewContentOffsetObserving() {
if let _observingScrollView = self.observingScrollView {
_observingScrollView.addObserver(self, forKeyPath: "contentOffset", options: [.old, .new], context: nil)
}
}
fileprivate func stopScrollViewContentOffsetObserving() {
if let _observingScrollView = self.observingScrollView {
_observingScrollView.removeObserver(self, forKeyPath: "contentOffset")
}
}
}
|
a45df47cf127b6b04f84df68418d3435
| 39.831933 | 132 | 0.678329 | false | false | false | false |
wenghengcong/Coderpursue
|
refs/heads/master
|
BeeFun/BeeFun/SystemManager/ProConfig/BFNotificationName.swift
|
mit
|
1
|
//
// DeviceCfg.swift
// BeeFun
//
// Created by wenghengcong on 16/1/3.
// Copyright © 2016年 JungleSong. All rights reserved.
//
extension Notification.Name {
public struct BeeFun {
public static let WillLogin = Notification.Name(rawValue: "com.luci.beefun.mac.willlogin")
public static let DidLogin = Notification.Name(rawValue: "com.luci.beefun.mac.didlogin")
/// 获取到oauth token
public static let GetOAuthToken = Notification.Name(rawValue: "com.luci.beefun.mac.gettoken")
/// 登录后,获取到用户信息
public static let GetUserInfo = Notification.Name(rawValue: "com.luci.beefun.mac.getuserinfo")
/// 用户操作改变了数据库
public static let databaseChanged = Notification.Name(rawValue: "com.luci.beefun.mac.databaseChanged")
/// 同步操作
public static let SyncStarRepoStart = Notification.Name(rawValue: "com.luci.beefun.mac.syncStarRepoStart")
public static let SyncStarRepoEnd = Notification.Name(rawValue: "com.luci.beefun.mac.syncStarRepoEnd")
public static let WillLogout = Notification.Name(rawValue: "com.luci.beefun.mac.willlogout")
public static let DidLogout = Notification.Name(rawValue: "com.luci.beefun.mac.didlogout")
public static let AddTag = Notification.Name(rawValue: "com.luci.beefun.mac.addtag")
public static let UpdateTag = Notification.Name(rawValue: "com.luci.beefun.mac.updatetag")
public static let DelTag = Notification.Name(rawValue: "com.luci.beefun.mac.deltag")
public static let RepoUpdateTag = Notification.Name(rawValue: "com.luci.beefun.mac.repoupdatetag")
/// Network reachablity
public static let NotReachable = Notification.Name(rawValue: "com.luci.beefun.mac.NotReachable")
public static let Unknown = Notification.Name(rawValue: "com.luci.beefun.mac.Unknown")
public static let ReachableAfterUnreachable = Notification.Name(rawValue: "com.luci.beefun.mac.ReachableAfterUnreachable")
public static let ReachableWiFi = Notification.Name(rawValue: "com.luci.beefun.mac.ReachableWiFi")
public static let ReachableCellular = Notification.Name(rawValue: "com.luci.beefun.mac.ReachableCellular")
public static let UnReachableAfterReachable = Notification.Name(rawValue: "com.luci.beefun.mac.UnReachableAfterReachable")
/// Star Action
public static let didStarRepo = Notification.Name(rawValue: "com.luci.beefun.mac.didStarRepo")
/// UnStar Action
public static let didUnStarRepo = Notification.Name(rawValue: "com.luci.beefun.mac.ddiUnStarRepo")
}
}
|
93a3ccb50f3497dd73fabcc7047c54eb
| 53.9375 | 130 | 0.715207 | false | false | false | false |
bitjammer/swift
|
refs/heads/master
|
test/SILGen/objc_metatypes.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
@objc class ObjCClass {}
class A {
// CHECK-LABEL: sil hidden @_T014objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F
// CHECK-LABEL: sil hidden [thunk] @_T014objc_metatypes1AC3fooAA9ObjCClassCmAFmFTo
dynamic func foo(_ m: ObjCClass.Type) -> ObjCClass.Type {
// CHECK: bb0([[M:%[0-9]+]] : $@objc_metatype ObjCClass.Type, [[SELF:%[0-9]+]] : $A):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $A
// CHECK: [[M_AS_THICK:%[0-9]+]] = objc_to_thick_metatype [[M]] : $@objc_metatype ObjCClass.Type to $@thick ObjCClass.Type
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE_FOO:%[0-9]+]] = function_ref @_T014objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F
// CHECK: [[NATIVE_RESULT:%[0-9]+]] = apply [[NATIVE_FOO]]([[M_AS_THICK]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@thick ObjCClass.Type, @guaranteed A) -> @thick ObjCClass.Type
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[OBJC_RESULT:%[0-9]+]] = thick_to_objc_metatype [[NATIVE_RESULT]] : $@thick ObjCClass.Type to $@objc_metatype ObjCClass.Type
// CHECK: return [[OBJC_RESULT]] : $@objc_metatype ObjCClass.Type
// CHECK: } // end sil function '_T014objc_metatypes1AC3fooAA9ObjCClassCmAFmFTo'
return m
}
// CHECK-LABEL: sil hidden @_T014objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ
// CHECK-LABEL: sil hidden [thunk] @_T014objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZTo
// CHECK: bb0([[SELF:%[0-9]+]] : $@objc_metatype A.Type):
// CHECK-NEXT: [[OBJC_SELF:%[0-9]+]] = objc_to_thick_metatype [[SELF]] : $@objc_metatype A.Type to $@thick A.Type
// CHECK: [[BAR:%[0-9]+]] = function_ref @_T014objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[BAR]]([[OBJC_SELF]]) : $@convention(method) (@thick A.Type) -> ()
// CHECK-NEXT: return [[RESULT]] : $()
dynamic class func bar() { }
dynamic func takeGizmo(_ g: Gizmo.Type) { }
// CHECK-LABEL: sil hidden @_T014objc_metatypes1AC7callFoo{{[_0-9a-zA-Z]*}}F
func callFoo() {
// Make sure we peephole Type/thick_to_objc_metatype.
// CHECK-NOT: thick_to_objc_metatype
// CHECK: metatype $@objc_metatype ObjCClass.Type
foo(ObjCClass.self)
// CHECK: return
}
}
|
448ecbe143e6be992b507187372cee65
| 51.145833 | 191 | 0.625649 | false | false | false | false |
johnno1962/eidolon
|
refs/heads/master
|
KioskTests/Bid Fulfillment/PlaceBidNetworkModelTests.swift
|
mit
|
1
|
import Quick
import Nimble
import RxSwift
import Moya
@testable
import Kiosk
class PlaceBidNetworkModelTests: QuickSpec {
override func spec() {
var fulfillmentController: StubFulfillmentController!
var subject: PlaceBidNetworkModel!
var disposeBag: DisposeBag!
var authorizedNetworking: AuthorizedNetworking!
beforeEach {
fulfillmentController = StubFulfillmentController()
subject = PlaceBidNetworkModel(bidDetails: fulfillmentController.bidDetails)
disposeBag = DisposeBag()
authorizedNetworking = Networking.newAuthorizedStubbingNetworking()
}
it("maps good responses to observable completions") {
var completed = false
waitUntil { done in
subject
.bid(authorizedNetworking)
.subscribeCompleted {
completed = true
done()
}
.addDisposableTo(disposeBag)
}
expect(completed).to( beTrue() )
}
it("maps good responses to bidder positions") {
var bidderPositionID: String?
waitUntil { done in
subject
.bid(authorizedNetworking)
.subscribeNext { id in
bidderPositionID = id
done()
}
.addDisposableTo(disposeBag)
}
// ID retrieved from CreateABid.json
expect(bidderPositionID) == "5437dd107261692daa170000"
}
it("maps bid details into a proper request") {
var auctionID: String?
var artworkID: String?
var bidCents: String?
let provider = OnlineProvider(endpointClosure: { target -> (Endpoint<ArtsyAuthenticatedAPI>) in
if case .PlaceABid(let receivedAuctionID, let receivedArtworkID, let receivedBidCents) = target {
auctionID = receivedAuctionID
artworkID = receivedArtworkID
bidCents = receivedBidCents
}
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, stubbedResponse("CreateABid"))}, method: target.method, parameters: target.parameters)
}, stubClosure: MoyaProvider.ImmediatelyStub, online: Observable.just(true))
waitUntil { done in
subject
.bid(AuthorizedNetworking(provider: provider))
.subscribeCompleted {
done()
}
.addDisposableTo(disposeBag)
}
expect(auctionID) == fulfillmentController.bidDetails.saleArtwork?.auctionID
expect(artworkID) == fulfillmentController.bidDetails.saleArtwork?.artwork.id
expect(Int(bidCents!)) == Int(fulfillmentController.bidDetails.bidAmountCents.value ?? 0)
}
describe("failing network responses") {
var networking: AuthorizedNetworking!
beforeEach {
let provider = OnlineProvider(endpointClosure: { target -> (Endpoint<ArtsyAuthenticatedAPI>) in
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(400, stubbedResponse("CreateABidFail"))}, method: target.method, parameters: target.parameters)
}, stubClosure: MoyaProvider.ImmediatelyStub, online: Observable.just(true))
networking = AuthorizedNetworking(provider: provider)
}
it("maps failures due to outbidding to correct error types") {
var error: NSError?
waitUntil { done in
subject
.bid(networking)
.subscribeError { receivedError in
error = receivedError as NSError
done()
}
.addDisposableTo(disposeBag)
}
expect(error?.domain) == OutbidDomain
}
it("errors on non-200 status codes"){
var errored = false
waitUntil { done in
subject
.bid(networking)
.subscribeError { _ in
errored = true
done()
}
.addDisposableTo(disposeBag)
}
expect(errored).to( beTrue() )
}
}
}
}
|
d0796dd18822b809e954c5a1d403c231
| 36.72093 | 182 | 0.538541 | false | false | false | false |
saagarjha/iina
|
refs/heads/develop
|
iina/ISO639Helper.swift
|
gpl-3.0
|
1
|
//
// ISO639_2Helper.swift
// iina
//
// Created by lhc on 14/3/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
class ISO639Helper {
struct Language {
var code: String
var name: [String]
var description: String {
return "\(name[0]) (\(code))"
}
}
static let descriptionRegex = Regex("^.+?\\(([a-z]{2,3})\\)$")
static let languages: [Language] = {
var result: [Language] = []
for (k, v) in dictionary {
let names = v.split(separator: ";").map { String($0) }
result.append(Language(code: k, name: names))
}
return result
}()
static let dictionary: [String: String] = {
let filePath = Bundle.main.path(forResource: "ISO639", ofType: "strings")!
return NSDictionary(contentsOfFile: filePath) as! [String : String]
}()
}
|
56b5566a36ceb369dc07c10b60bb1abb
| 21.27027 | 78 | 0.603155 | false | false | false | false |
kevinmbeaulieu/Signal-iOS
|
refs/heads/master
|
Signal/src/ViewControllers/SignalAttachment.swift
|
gpl-3.0
|
1
|
//
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import MobileCoreServices
enum SignalAttachmentError: Error {
case missingData
case fileSizeTooLarge
case invalidData
case couldNotParseImage
case couldNotConvertToJpeg
case invalidFileFormat
}
extension SignalAttachmentError: LocalizedError {
public var errorDescription: String {
switch self {
case .missingData:
return NSLocalizedString("ATTACHMENT_ERROR_MISSING_DATA", comment: "Attachment error message for attachments without any data")
case .fileSizeTooLarge:
return NSLocalizedString("ATTACHMENT_ERROR_FILE_SIZE_TOO_LARGE", comment: "Attachment error message for attachments whose data exceed file size limits")
case .invalidData:
return NSLocalizedString("ATTACHMENT_ERROR_INVALID_DATA", comment: "Attachment error message for attachments with invalid data")
case .couldNotParseImage:
return NSLocalizedString("ATTACHMENT_ERROR_COULD_NOT_PARSE_IMAGE", comment: "Attachment error message for image attachments which cannot be parsed")
case .couldNotConvertToJpeg:
return NSLocalizedString("ATTACHMENT_ERROR_COULD_NOT_CONVERT_TO_JPEG", comment: "Attachment error message for image attachments which could not be converted to JPEG")
case .invalidFileFormat:
return NSLocalizedString("ATTACHMENT_ERROR_INVALID_FILE_FORMAT", comment: "Attachment error message for attachments with an invalid file format")
}
}
}
enum TSImageQuality {
case uncropped
case high
case medium
case low
}
// Represents a possible attachment to upload.
// The attachment may be invalid.
//
// Signal attachments are subject to validation and
// in some cases, file format conversion.
//
// This class gathers that logic. It offers factory methods
// for attachments that do the necessary work.
//
// The return value for the factory methods will be nil if the input is nil.
//
// [SignalAttachment hasError] will be true for non-valid attachments.
//
// TODO: Perhaps do conversion off the main thread?
class SignalAttachment: NSObject {
static let TAG = "[SignalAttachment]"
// MARK: Properties
let data: Data
internal var temporaryDataUrl: URL?
// Attachment types are identified using UTIs.
//
// See: https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
let dataUTI: String
// An optional field that indicates the filename, if known, for this attachment.
let filename: String?
static let kOversizeTextAttachmentUTI = "org.whispersystems.oversize-text-attachment"
static let kUnknownTestAttachmentUTI = "org.whispersystems.unknown"
var error: SignalAttachmentError? {
didSet {
AssertIsOnMainThread()
assert(oldValue == nil)
Logger.verbose("\(SignalAttachment.TAG) Attachment has error: \(error)")
}
}
// To avoid redundant work of repeatedly compressing/uncompressing
// images, we cache the UIImage associated with this attachment if
// possible.
public var image: UIImage?
// MARK: Constants
/**
* Media Size constraints from Signal-Android
*
* https://github.com/WhisperSystems/Signal-Android/blob/master/src/org/thoughtcrime/securesms/mms/PushMediaConstraints.java
*/
static let kMaxFileSizeAnimatedImage = 25 * 1024 * 1024
static let kMaxFileSizeImage = 6 * 1024 * 1024
static let kMaxFileSizeVideo = 100 * 1024 * 1024
static let kMaxFileSizeAudio = 100 * 1024 * 1024
static let kMaxFileSizeGeneric = 100 * 1024 * 1024
// MARK: Constructor
// This method should not be called directly; use the factory
// methods instead.
internal required init(data: Data, dataUTI: String, filename: String?) {
self.data = data
self.dataUTI = dataUTI
self.filename = filename
super.init()
}
// MARK: Methods
public func getTemporaryDataUrl() -> URL? {
if temporaryDataUrl == nil {
let directory = NSTemporaryDirectory()
guard let fileExtension = self.fileExtension else {
return nil
}
let fileName = NSUUID().uuidString + "." + fileExtension
guard let fileUrl = NSURL.fileURL(withPathComponents: [directory, fileName]) else {
return nil
}
do {
try data.write(to: fileUrl)
} catch {
Logger.error("\(SignalAttachment.TAG) Could not write data to disk: \(dataUTI)")
assertionFailure()
return nil
}
temporaryDataUrl = fileUrl
}
return temporaryDataUrl
}
var hasError: Bool {
return error != nil
}
var errorName: String? {
guard let error = error else {
// This method should only be called if there is an error.
assertionFailure()
return nil
}
return "\(error)"
}
var localizedErrorDescription: String? {
guard let error = self.error else {
// This method should only be called if there is an error.
assertionFailure()
return nil
}
return "\(error.errorDescription)"
}
class var missingDataErrorMessage: String {
return SignalAttachmentError.missingData.errorDescription
}
// Returns the MIME type for this attachment or nil if no MIME type
// can be identified.
var mimeType: String? {
if dataUTI == SignalAttachment.kOversizeTextAttachmentUTI {
return OWSMimeTypeOversizeTextMessage
}
if dataUTI == SignalAttachment.kUnknownTestAttachmentUTI {
return OWSMimeTypeUnknownForTests
}
let mimeType = UTTypeCopyPreferredTagWithClass(dataUTI as CFString, kUTTagClassMIMEType)
guard mimeType != nil else {
return nil
}
return mimeType?.takeRetainedValue() as? String
}
// Returns the file extension for this attachment or nil if no file extension
// can be identified.
var fileExtension: String? {
if dataUTI == SignalAttachment.kOversizeTextAttachmentUTI ||
dataUTI == SignalAttachment.kUnknownTestAttachmentUTI {
assertionFailure()
return nil
}
guard let fileExtension = UTTypeCopyPreferredTagWithClass(dataUTI as CFString,
kUTTagClassFilenameExtension) else {
return nil
}
return fileExtension.takeRetainedValue() as String
}
// Returns the set of UTIs that correspond to valid _input_ image formats
// for Signal attachments.
//
// Image attachments may be converted to another image format before
// being uploaded.
private class var inputImageUTISet: Set<String> {
return MIMETypeUtil.supportedImageUTITypes().union(animatedImageUTISet)
}
// Returns the set of UTIs that correspond to valid _output_ image formats
// for Signal attachments.
private class var outputImageUTISet: Set<String> {
return MIMETypeUtil.supportedImageUTITypes().union(animatedImageUTISet)
}
// Returns the set of UTIs that correspond to valid animated image formats
// for Signal attachments.
private class var animatedImageUTISet: Set<String> {
return MIMETypeUtil.supportedAnimatedImageUTITypes()
}
// Returns the set of UTIs that correspond to valid video formats
// for Signal attachments.
private class var videoUTISet: Set<String> {
return MIMETypeUtil.supportedVideoUTITypes()
}
// Returns the set of UTIs that correspond to valid audio formats
// for Signal attachments.
private class var audioUTISet: Set<String> {
return MIMETypeUtil.supportedAudioUTITypes()
}
public var isImage: Bool {
return SignalAttachment.outputImageUTISet.contains(dataUTI)
}
public var isAnimatedImage: Bool {
return SignalAttachment.animatedImageUTISet.contains(dataUTI)
}
public var isVideo: Bool {
return SignalAttachment.videoUTISet.contains(dataUTI)
}
public var isAudio: Bool {
return SignalAttachment.audioUTISet.contains(dataUTI)
}
public class func pasteboardHasPossibleAttachment() -> Bool {
return UIPasteboard.general.numberOfItems > 0
}
// Returns an attachment from the pasteboard, or nil if no attachment
// can be found.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
public class func attachmentFromPasteboard() -> SignalAttachment? {
guard UIPasteboard.general.numberOfItems >= 1 else {
return nil
}
// If pasteboard contains multiple items, use only the first.
let itemSet = IndexSet(integer:0)
guard let pasteboardUTITypes = UIPasteboard.general.types(forItemSet:itemSet) else {
return nil
}
let pasteboardUTISet = Set<String>(pasteboardUTITypes[0])
for dataUTI in inputImageUTISet {
if pasteboardUTISet.contains(dataUTI) {
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
Logger.error("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
assertionFailure()
return nil
}
return imageAttachment(data : data, dataUTI : dataUTI, filename: nil)
}
}
for dataUTI in videoUTISet {
if pasteboardUTISet.contains(dataUTI) {
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
Logger.error("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
assertionFailure()
return nil
}
return videoAttachment(data : data, dataUTI : dataUTI, filename: nil)
}
}
for dataUTI in audioUTISet {
if pasteboardUTISet.contains(dataUTI) {
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
Logger.error("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
assertionFailure()
return nil
}
return audioAttachment(data : data, dataUTI : dataUTI, filename: nil)
}
}
let dataUTI = pasteboardUTISet[pasteboardUTISet.startIndex]
guard let data = dataForFirstPasteboardItem(dataUTI:dataUTI) else {
Logger.error("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
assertionFailure()
return nil
}
return genericAttachment(data : data, dataUTI : dataUTI, filename: nil)
}
// This method should only be called for dataUTIs that
// are appropriate for the first pasteboard item.
private class func dataForFirstPasteboardItem(dataUTI: String) -> Data? {
let itemSet = IndexSet(integer:0)
guard let datas = UIPasteboard.general.data(forPasteboardType:dataUTI, inItemSet:itemSet) else {
Logger.error("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
assertionFailure()
return nil
}
guard datas.count > 0 else {
Logger.error("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
assertionFailure()
return nil
}
guard let data = datas[0] as? Data else {
Logger.error("\(TAG) Missing expected pasteboard data for UTI: \(dataUTI)")
assertionFailure()
return nil
}
return data
}
// MARK: Image Attachments
// Factory method for an image attachment.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
public class func imageAttachment(data imageData: Data?, dataUTI: String, filename: String?) -> SignalAttachment {
assert(dataUTI.characters.count > 0)
assert(imageData != nil)
guard let imageData = imageData else {
let attachment = SignalAttachment(data : Data(), dataUTI: dataUTI, filename: filename)
attachment.error = .missingData
return attachment
}
let attachment = SignalAttachment(data : imageData, dataUTI: dataUTI, filename: filename)
guard inputImageUTISet.contains(dataUTI) else {
attachment.error = .invalidFileFormat
return attachment
}
guard imageData.count > 0 else {
assert(imageData.count > 0)
attachment.error = .invalidData
return attachment
}
if animatedImageUTISet.contains(dataUTI) {
guard imageData.count <= kMaxFileSizeAnimatedImage else {
attachment.error = .fileSizeTooLarge
return attachment
}
// Never re-encode animated images (i.e. GIFs) as JPEGs.
Logger.verbose("\(TAG) Sending raw \(attachment.mimeType) to retain any animation")
return attachment
} else {
guard let image = UIImage(data:imageData) else {
attachment.error = .couldNotParseImage
return attachment
}
attachment.image = image
if isInputImageValidOutputImage(image: image, imageData: imageData, dataUTI: dataUTI) {
Logger.verbose("\(TAG) Sending raw \(attachment.mimeType)")
return attachment
}
Logger.verbose("\(TAG) Compressing attachment as image/jpeg")
return compressImageAsJPEG(image : image, attachment : attachment, filename:filename)
}
}
private class func defaultImageUploadQuality() -> TSImageQuality {
// Currently default to a original image quality and size.
return .uncropped
}
// If the proposed attachment already conforms to the
// file size and content size limits, don't recompress it.
private class func isInputImageValidOutputImage(image: UIImage?, imageData: Data?, dataUTI: String) -> Bool {
guard let image = image else {
return false
}
guard let imageData = imageData else {
return false
}
guard SignalAttachment.outputImageUTISet.contains(dataUTI) else {
return false
}
let maxSize = maxSizeForImage(image: image,
imageUploadQuality:defaultImageUploadQuality())
if image.size.width <= maxSize &&
image.size.height <= maxSize &&
imageData.count <= kMaxFileSizeImage {
return true
}
return false
}
// Factory method for an image attachment.
//
// NOTE: The attachment returned by this method may nil or not be valid.
// Check the attachment's error property.
public class func imageAttachment(image: UIImage?, dataUTI: String, filename: String?) -> SignalAttachment {
assert(dataUTI.characters.count > 0)
guard let image = image else {
let attachment = SignalAttachment(data : Data(), dataUTI: dataUTI, filename: filename)
attachment.error = .missingData
return attachment
}
// Make a placeholder attachment on which to hang errors if necessary.
let attachment = SignalAttachment(data : Data(), dataUTI: dataUTI, filename: filename)
attachment.image = image
Logger.verbose("\(TAG) Writing \(attachment.mimeType) as image/jpeg")
return compressImageAsJPEG(image : image, attachment : attachment, filename:filename)
}
private class func compressImageAsJPEG(image: UIImage, attachment: SignalAttachment, filename: String?) -> SignalAttachment {
assert(attachment.error == nil)
var imageUploadQuality = defaultImageUploadQuality()
while true {
let maxSize = maxSizeForImage(image: image, imageUploadQuality:imageUploadQuality)
var dstImage: UIImage! = image
if image.size.width > maxSize ||
image.size.height > maxSize {
dstImage = imageScaled(image, toMaxSize: maxSize)
}
guard let jpgImageData = UIImageJPEGRepresentation(dstImage,
jpegCompressionQuality(imageUploadQuality:imageUploadQuality)) else {
attachment.error = .couldNotConvertToJpeg
return attachment
}
if jpgImageData.count <= kMaxFileSizeImage {
let recompressedAttachment = SignalAttachment(data : jpgImageData, dataUTI: kUTTypeJPEG as String, filename: filename)
recompressedAttachment.image = dstImage
return recompressedAttachment
}
// If the JPEG output is larger than the file size limit,
// continue to try again by progressively reducing the
// image upload quality.
switch imageUploadQuality {
case .uncropped:
imageUploadQuality = .high
case .high:
imageUploadQuality = .medium
case .medium:
imageUploadQuality = .low
case .low:
attachment.error = .fileSizeTooLarge
return attachment
}
}
}
private class func imageScaled(_ image: UIImage, toMaxSize size: CGFloat) -> UIImage {
var scaleFactor: CGFloat
let aspectRatio: CGFloat = image.size.height / image.size.width
if aspectRatio > 1 {
scaleFactor = size / image.size.width
} else {
scaleFactor = size / image.size.height
}
let newSize = CGSize(width: CGFloat(image.size.width * scaleFactor), height: CGFloat(image.size.height * scaleFactor))
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(newSize.width), height: CGFloat(newSize.height)))
let updatedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return updatedImage!
}
private class func maxSizeForImage(image: UIImage, imageUploadQuality: TSImageQuality) -> CGFloat {
switch imageUploadQuality {
case .uncropped:
return max(image.size.width, image.size.height)
case .high:
return 2048
case .medium:
return 1024
case .low:
return 512
}
}
private class func jpegCompressionQuality(imageUploadQuality: TSImageQuality) -> CGFloat {
switch imageUploadQuality {
case .uncropped:
return 1
case .high:
return 0.9
case .medium:
return 0.5
case .low:
return 0.3
}
}
// MARK: Video Attachments
// Factory method for video attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
public class func videoAttachment(data: Data?, dataUTI: String, filename: String?) -> SignalAttachment {
return newAttachment(data : data,
dataUTI : dataUTI,
validUTISet : videoUTISet,
maxFileSize : kMaxFileSizeVideo,
filename : filename)
}
// MARK: Audio Attachments
// Factory method for audio attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
public class func audioAttachment(data: Data?, dataUTI: String, filename: String?) -> SignalAttachment {
return newAttachment(data : data,
dataUTI : dataUTI,
validUTISet : audioUTISet,
maxFileSize : kMaxFileSizeAudio,
filename : filename)
}
// MARK: Oversize Text Attachments
// Factory method for oversize text attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
public class func oversizeTextAttachment(text: String?) -> SignalAttachment {
return newAttachment(data : text?.data(using: .utf8),
dataUTI : kOversizeTextAttachmentUTI,
validUTISet : nil,
maxFileSize : kMaxFileSizeGeneric,
filename : nil)
}
// MARK: Generic Attachments
// Factory method for generic attachments.
//
// NOTE: The attachment returned by this method may not be valid.
// Check the attachment's error property.
public class func genericAttachment(data: Data?, dataUTI: String, filename: String?) -> SignalAttachment {
return newAttachment(data : data,
dataUTI : dataUTI,
validUTISet : nil,
maxFileSize : kMaxFileSizeGeneric,
filename : filename)
}
// MARK: Helper Methods
private class func newAttachment(data: Data?,
dataUTI: String,
validUTISet: Set<String>?,
maxFileSize: Int,
filename: String?) -> SignalAttachment {
assert(dataUTI.characters.count > 0)
assert(data != nil)
guard let data = data else {
let attachment = SignalAttachment(data : Data(), dataUTI: dataUTI, filename: filename)
attachment.error = .missingData
return attachment
}
let attachment = SignalAttachment(data : data, dataUTI: dataUTI, filename: filename)
if let validUTISet = validUTISet {
guard validUTISet.contains(dataUTI) else {
attachment.error = .invalidFileFormat
return attachment
}
}
guard data.count > 0 else {
assert(data.count > 0)
attachment.error = .invalidData
return attachment
}
guard data.count <= maxFileSize else {
attachment.error = .fileSizeTooLarge
return attachment
}
// Attachment is valid
return attachment
}
}
|
40cec6e9781c1ba5f6e1adb0e35b73bc
| 36.607201 | 178 | 0.616111 | false | false | false | false |
spark/photon-tinker-ios
|
refs/heads/master
|
Photon-Tinker/Mesh/ControlPanel/Gen3SetupControlPanelMeshViewController.swift
|
apache-2.0
|
1
|
//
// Created by Raimundas Sakalauskas on 2019-03-15.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class Gen3SetupControlPanelMeshViewController : Gen3SetupControlPanelRootViewController {
private let refreshControl = UIRefreshControl()
override var allowBack: Bool {
get {
return true
}
set {
super.allowBack = newValue
}
}
override var customTitle: String {
return Gen3SetupStrings.ControlPanel.Mesh.Title
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.prepareContent()
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
refreshControl.tintColor = ParticleStyle.SecondaryTextColor
refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged)
}
@objc private func refreshData(_ sender: Any) {
self.fadeContent(animated: true, showSpinner: false)
self.callback(.mesh)
}
override func resume(animated: Bool) {
self.prepareContent()
super.resume(animated: animated)
self.tableView.refreshControl?.endRefreshing()
}
override func prepareContent() {
if (self.context.targetDevice.meshNetworkInfo != nil) {
cells = [[.meshInfoNetworkName, .meshInfoNetworkID, .meshInfoNetworkExtPanID, .meshInfoNetworkPanID, .meshInfoNetworkChannel, .meshInfoNetworkDeviceCount], [.meshInfoDeviceRole], [.actionLeaveMeshNetwork]]
} else {
cells = [[.meshInfoNetworkName], [.actionAddToMeshNetwork]]
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return Gen3SetupStrings.ControlPanel.Mesh.NetworkInfo
case 1:
if (self.context.targetDevice.meshNetworkInfo != nil) {
return Gen3SetupStrings.ControlPanel.Mesh.DeviceInfo
} else {
return ""
}
default:
return ""
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let command = cells[indexPath.section][indexPath.row]
if (command == .actionLeaveMeshNetwork) {
let alert = UIAlertController(title: Gen3SetupStrings.ControlPanel.Prompt.LeaveNetworkTitle, message: Gen3SetupStrings.ControlPanel.Prompt.LeaveNetworkText, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Gen3SetupStrings.ControlPanel.Action.LeaveNetwork, style: .default) { action in
super.tableView(tableView, didSelectRowAt: indexPath)
})
alert.addAction(UIAlertAction(title: Gen3SetupStrings.ControlPanel.Action.DontLeaveNetwork, style: .cancel) { action in
})
self.present(alert, animated: true)
} else {
super.tableView(tableView, didSelectRowAt: indexPath)
}
}
}
|
a8a3c2d22ec459c2a7fd0c320b88b335
| 32.27619 | 217 | 0.644533 | false | false | false | false |
swift-gtk/SwiftGTK
|
refs/heads/master
|
example/main.swift
|
gpl-2.0
|
1
|
//
// main.swift
// example
//
// Created by Artur Gurgul on 07/02/2017.
//
//
enum General:Error {
case CantStartApp
}
class FirstApplication: Application {
var buttonBox:ButtonBox!
var label: Label!
var pressMeButton: Button!
var calendarButton: Button!
var imageButton: Button!
var textView: TextView!
let socket: Socket
let inet: InetAddress
let address: SocketAddress
init() {
guard let socket = Socket(family: .ipv4, type: .stream, protocol: .tcp) else {
//throw General.CantStartApp
fatalError("Can't start the app")
}
self.socket = socket
socket.blocking = false
inet = InetAddress(string: "127.0.0.1")
address = SocketAddress(inet: inet, port: 8866)
super.init(applicationId: "simple.example")
}
func imageButtonClicked(button: Button, args: UnsafeMutableRawPointer...) {
let newWindow = Window(windowType: .topLevel)
newWindow.title = "Just a window"
newWindow.defaultSize = Size(width: 200, height: 200)
let image = Image(filename: "GTK.png")
newWindow.add(image)
newWindow.showAll()
}
func pressMeClicked(button: Button, args: UnsafeMutableRawPointer...) {
label.text = "Oh, you pressed the button."
let newWindow = Window(windowType: .topLevel)
newWindow.title = "Just a window"
newWindow.defaultSize = Size(width: 200, height: 200)
let labelPressed = Label(text: "Oh, you pressed the button.")
newWindow.add(labelPressed)
newWindow.showAll()
}
func callendarButtonClicked(button: Button, args: UnsafeMutableRawPointer...) {
let newWindow = Window(windowType: .topLevel)
newWindow.title = "Just a window"
newWindow.defaultSize = Size(width: 200, height: 200)
let calendar = Calendar()
calendar.year = 2000
calendar.showHeading = true
newWindow.add(calendar)
newWindow.showAll()
}
func startApp() {
_ = run(startApplicationWindow)
}
func startApplicationWindow(applicationWindow: ApplicationWindow) {
buttonBox = ButtonBox(orientation: .vertical)
label = Label()
label.selectable = true
buttonBox.add(label)
pressMeButton = Button(label: "Press")
pressMeButton.label = "Press Me"
pressMeButton.connect(.clicked, callback: pressMeClicked)
buttonBox.add(pressMeButton)
calendarButton = Button(label: "Calendar")
calendarButton.connect(.clicked, callback: callendarButtonClicked)
buttonBox.add(calendarButton)
imageButton = Button(label: "Image")
imageButton.connect(.clicked, callback: imageButtonClicked)
buttonBox.add(imageButton)
textView = TextView()
textView.buffer.text = "This is some text inside of a Gtk.TextView. " +
"Select text and click one of the buttons 'bold', 'italic', " +
"or 'underline' to modify the text accordingly."
buttonBox.add(textView)
applicationWindow.title = "Hello World"
applicationWindow.defaultSize = Size(width: 400, height: 400)
applicationWindow.resizable = true
applicationWindow.add(buttonBox)
}
func newConnection(socket: Socket) {
print("new connection")
}
func startServer() {
do {
try socket.bind(address: address, allowReuse: false)
try socket.listen()
socket.loop(callback: newConnection)
} catch SocketError.cantBind(let message) {
print(message)
} catch SocketError.cantListen(let message) {
print(message)
} catch {
print("unknown error")
}
}
}
_ = FirstApplication().startApp()
|
d267e70c5ec7d47c95870e5c6205b597
| 27.704225 | 86 | 0.591021 | false | false | false | false |
bradhilton/SwiftTable
|
refs/heads/master
|
SwiftTable/Table/Table/SectionTable.swift
|
mit
|
1
|
//
// SectionTable.swift
// SwiftTable
//
// Created by Bradley Hilton on 2/15/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
import OrderedObjectSet
private var sectionsKey = "sections"
public protocol SectionTable : TableSource, TableInterface {
var sections: OrderedObjectSet<SectionSource> { get set }
}
extension SectionTable {
public var sections: OrderedObjectSet<SectionSource> {
get {
guard let sections = objc_getAssociatedObject(self, §ionsKey) as? OrderedObjectSet<SectionSource> else {
return []
}
return sections
}
set {
sections.subtracting(newValue).forEach { $0.table = nil }
newValue.subtracting(sections).forEach { $0.table = self }
objc_setAssociatedObject(self, §ionsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func index(_ section: SectionSource) -> Int? {
return sections.firstIndex { $0 === section }
}
func delegate<T>(_ section: SectionSource, handler: (Int) -> T?) -> T? {
guard let index = sections.firstIndex(where: { $0 === section }) else { return nil }
return handler(index)
}
func rowForSection(_ section: SectionSource, fromIndexPath indexPath: IndexPath?) -> Int? {
guard let indexPath = indexPath, indexPath.section == index(section) else { return nil }
return indexPath.row
}
func rowsForSection(_ section: SectionSource, fromIndexPaths indexPaths: [IndexPath]?) -> [Int]? {
guard let indexPaths = indexPaths, let index = index(section) else { return nil }
let rows = indexPaths.filter { $0.section == index }.map { $0.row }
return rows.count > 0 ? rows : nil
}
func indexPathsFromSection(_ section: SectionSource, withRows rows: [Int]) -> [IndexPath] {
guard let index = index(section) else { return [] }
return rows.map { IndexPath(row: $0, section: index) }
}
func indexPathsFromRows(_ rows: [Int], inSection section: SectionSource) -> [IndexPath] {
guard let index = index(section) else { return [] }
return rows.map { IndexPath(row: $0, section: index) }
}
}
|
c4a48a1ae6e7d7ce6d2b96dfd188cb52
| 34.84127 | 120 | 0.625332 | false | false | false | false |
atrick/swift
|
refs/heads/main
|
stdlib/public/core/StringUTF16View.swift
|
apache-2.0
|
1
|
//===--- StringUTF16.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of UTF-16 code units.
///
/// You can access a string's view of UTF-16 code units by using its `utf16`
/// property. A string's UTF-16 view encodes the string's Unicode scalar
/// values as 16-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf16 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 55357
/// // 56464
///
/// Unicode scalar values that make up a string's contents can be up to 21
/// bits long. The longer scalar values may need two `UInt16` values for
/// storage. Those "pairs" of code units are called *surrogate pairs*.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf16 {
/// print(v)
/// }
/// // 55357
/// // 56464
///
/// To convert a `String.UTF16View` instance back into a string, use the
/// `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.utf16.firstIndex(where: { $0 >= 128 }) {
/// let asciiPrefix = String(favemoji.utf16[..<i])!
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
///
/// UTF16View Elements Match NSString Characters
/// ============================================
///
/// The UTF-16 code units of a string's `utf16` view match the elements
/// accessed through indexed `NSString` APIs.
///
/// print(flowers.utf16.count)
/// // Prints "10"
///
/// let nsflowers = flowers as NSString
/// print(nsflowers.length)
/// // Prints "10"
///
/// Unlike `NSString`, however, `String.UTF16View` does not use integer
/// indices. If you need to access a specific position in a UTF-16 view, use
/// Swift's index manipulation methods. The following example accesses the
/// fourth code unit in both the `flowers` and `nsflowers` strings:
///
/// print(nsflowers.character(at: 3))
/// // Prints "119"
///
/// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3)
/// print(flowers.utf16[i])
/// // Prints "119"
///
/// Although the Swift overlay updates many Objective-C methods to return
/// native Swift indices and index ranges, some still return instances of
/// `NSRange`. To convert an `NSRange` instance to a range of
/// `String.Index`, use the `Range(_:in:)` initializer, which takes an
/// `NSRange` and a string as arguments.
///
/// let snowy = "❄️ Let it snow! ☃️"
/// let nsrange = NSRange(location: 3, length: 12)
/// if let range = Range(nsrange, in: snowy) {
/// print(snowy[range])
/// }
/// // Prints "Let it snow!"
@frozen
public struct UTF16View: Sendable {
@usableFromInline
internal var _guts: _StringGuts
@inlinable
internal init(_ guts: _StringGuts) {
self._guts = guts
_invariantCheck()
}
}
}
extension String.UTF16View {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
_internalInvariant(
startIndex.transcodedOffset == 0 && endIndex.transcodedOffset == 0)
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension String.UTF16View: BidirectionalCollection {
public typealias Index = String.Index
/// The position of the first code unit if the `String` is
/// nonempty; identical to `endIndex` otherwise.
@inlinable @inline(__always)
public var startIndex: Index { return _guts.startIndex }
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty UTF-16 view, `endIndex` is equal to `startIndex`.
@inlinable @inline(__always)
public var endIndex: Index { return _guts.endIndex }
@inlinable @inline(__always)
public func index(after idx: Index) -> Index {
var idx = _guts.ensureMatchingEncoding(idx)
_precondition(idx._encodedOffset < _guts.count,
"String index is out of bounds")
if _slowPath(_guts.isForeign) { return _foreignIndex(after: idx) }
if _guts.isASCII {
return idx.nextEncoded._scalarAligned._encodingIndependent
}
// For a BMP scalar (1-3 UTF-8 code units), advance past it. For a non-BMP
// scalar, use a transcoded offset first.
// TODO: If transcoded is 1, can we just skip ahead 4?
idx = _utf16AlignNativeIndex(idx)
let len = _guts.fastUTF8ScalarLength(startingAt: idx._encodedOffset)
if len == 4 && idx.transcodedOffset == 0 {
return idx.nextTranscoded._knownUTF8
}
return idx
.strippingTranscoding
.encoded(offsetBy: len)
._scalarAligned
._knownUTF8
}
@inlinable @inline(__always)
public func index(before idx: Index) -> Index {
var idx = _guts.ensureMatchingEncoding(idx)
_precondition(!idx.isZeroPosition && idx <= endIndex,
"String index is out of bounds")
if _slowPath(_guts.isForeign) { return _foreignIndex(before: idx) }
if _guts.isASCII {
return idx.priorEncoded._scalarAligned._encodingIndependent
}
if idx.transcodedOffset != 0 {
_internalInvariant(idx.transcodedOffset == 1)
return idx.strippingTranscoding._scalarAligned._knownUTF8
}
idx = _utf16AlignNativeIndex(idx)
let len = _guts.fastUTF8ScalarLength(endingAt: idx._encodedOffset)
if len == 4 {
// 2 UTF-16 code units comprise this scalar; advance to the beginning and
// start mid-scalar transcoding
return idx.encoded(offsetBy: -len).nextTranscoded._knownUTF8
}
// Single UTF-16 code unit
_internalInvariant((1...3) ~= len)
return idx.encoded(offsetBy: -len)._scalarAligned._knownUTF8
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
let i = _guts.ensureMatchingEncoding(i)
_precondition(i <= endIndex, "String index is out of bounds")
if _slowPath(_guts.isForeign) {
return _foreignIndex(i, offsetBy: n)
}
let lowerOffset = _nativeGetOffset(for: i)
let result = _nativeGetIndex(for: lowerOffset + n)
return result
}
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
let limit = _guts.ensureMatchingEncoding(limit)
guard _fastPath(limit <= endIndex) else { return index(i, offsetBy: n) }
let i = _guts.ensureMatchingEncoding(i)
_precondition(i <= endIndex, "String index is out of bounds")
if _slowPath(_guts.isForeign) {
return _foreignIndex(i, offsetBy: n, limitedBy: limit)
}
let iOffset = _nativeGetOffset(for: i)
let limitOffset = _nativeGetOffset(for: limit)
// If distance < 0, limit has no effect if it is greater than i.
if _slowPath(n < 0 && limit <= i && limitOffset > iOffset + n) {
return nil
}
// If distance > 0, limit has no effect if it is less than i.
if _slowPath(n >= 0 && limit >= i && limitOffset < iOffset + n) {
return nil
}
let result = _nativeGetIndex(for: iOffset + n)
return result
}
public func distance(from start: Index, to end: Index) -> Int {
let start = _guts.ensureMatchingEncoding(start)
let end = _guts.ensureMatchingEncoding(end)
_precondition(start._encodedOffset <= _guts.count,
"String index is out of bounds")
_precondition(end._encodedOffset <= _guts.count,
"String index is out of bounds")
if _slowPath(_guts.isForeign) {
return _foreignDistance(from: start, to: end)
}
let lower = _nativeGetOffset(for: start)
let upper = _nativeGetOffset(for: end)
return upper &- lower
}
@inlinable
public var count: Int {
if _slowPath(_guts.isForeign) {
return _foreignCount()
}
return _nativeGetOffset(for: endIndex)
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-16 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf16.startIndex
/// print("First character's UTF-16 code unit: \(greeting.utf16[i])")
/// // Prints "First character's UTF-16 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position` must be
/// less than the view's end index.
@inlinable @inline(__always)
public subscript(idx: Index) -> UTF16.CodeUnit {
let idx = _guts.ensureMatchingEncoding(idx)
_precondition(idx._encodedOffset < _guts.count,
"String index is out of bounds")
return self[_unchecked: idx]
}
@_alwaysEmitIntoClient @inline(__always)
internal subscript(_unchecked idx: Index) -> UTF16.CodeUnit {
if _fastPath(_guts.isFastUTF8) {
let scalar = _guts.fastUTF8Scalar(
startingAt: _guts.scalarAlign(idx)._encodedOffset)
return scalar.utf16[idx.transcodedOffset]
}
return _foreignSubscript(position: idx)
}
}
extension String.UTF16View {
@frozen
public struct Iterator: IteratorProtocol, Sendable {
@usableFromInline
internal var _guts: _StringGuts
@usableFromInline
internal var _position: Int = 0
@usableFromInline
internal var _end: Int
// If non-nil, return this value for `next()` (and set it to nil).
//
// This is set when visiting a non-BMP scalar: the leading surrogate is
// returned, this field is set with the value of the trailing surrogate, and
// `_position` is advanced to the start of the next scalar.
@usableFromInline
internal var _nextIsTrailingSurrogate: UInt16? = nil
@inlinable
internal init(_ guts: _StringGuts) {
self._end = guts.count
self._guts = guts
}
@inlinable
public mutating func next() -> UInt16? {
if _slowPath(_nextIsTrailingSurrogate != nil) {
let trailing = self._nextIsTrailingSurrogate._unsafelyUnwrappedUnchecked
self._nextIsTrailingSurrogate = nil
return trailing
}
guard _fastPath(_position < _end) else { return nil }
let (scalar, len) = _guts.errorCorrectedScalar(startingAt: _position)
_position &+= len
if _slowPath(scalar.value > UInt16.max) {
self._nextIsTrailingSurrogate = scalar.utf16[1]
return scalar.utf16[0]
}
return UInt16(truncatingIfNeeded: scalar.value)
}
}
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_guts)
}
}
extension String.UTF16View: CustomStringConvertible {
@inlinable @inline(__always)
public var description: String { return String(_guts) }
}
extension String.UTF16View: CustomDebugStringConvertible {
public var debugDescription: String {
return "StringUTF16(\(self.description.debugDescription))"
}
}
extension String {
/// A UTF-16 encoding of `self`.
@inlinable
public var utf16: UTF16View {
@inline(__always) get { return UTF16View(_guts) }
@inline(__always) set { self = String(newValue._guts) }
}
/// Creates a string corresponding to the given sequence of UTF-16 code units.
@inlinable @inline(__always)
@available(swift, introduced: 4.0)
public init(_ utf16: UTF16View) {
self.init(utf16._guts)
}
}
// Index conversions
extension String.UTF16View.Index {
/// Creates an index in the given UTF-16 view that corresponds exactly to the
/// specified string position.
///
/// If the index passed as `sourcePosition` represents either the start of a
/// Unicode scalar value or the position of a UTF-16 trailing surrogate,
/// then the initializer succeeds. If `sourcePosition` does not have an
/// exact corresponding position in `target`, then the result is `nil`. For
/// example, an attempt to convert the position of a UTF-8 continuation byte
/// results in `nil`.
///
/// The following example finds the position of a space in a string and then
/// converts that position to an index in the string's `utf16` view.
///
/// let cafe = "Café 🍵"
///
/// let stringIndex = cafe.firstIndex(of: "é")!
/// let utf16Index = String.Index(stringIndex, within: cafe.utf16)!
///
/// print(String(cafe.utf16[...utf16Index])!)
/// // Prints "Café"
///
/// - Parameters:
/// - sourcePosition: A position in at least one of the views of the string
/// shared by `target`.
/// - target: The `UTF16View` in which to find the new position.
public init?(
_ idx: String.Index, within target: String.UTF16View
) {
// As a special exception, we allow `idx` to be an UTF-16 index when `self`
// is a UTF-8 string, to preserve compatibility with (broken) code that
// keeps using indices from a bridged string after converting the string to
// a native representation. Such indices are invalid, but returning nil here
// can break code that appeared to work fine for ASCII strings in Swift
// releases prior to 5.7.
guard
let idx = target._guts.ensureMatchingEncodingNoTrap(idx),
idx._encodedOffset <= target._guts.count
else { return nil }
if _slowPath(target._guts.isForeign) {
guard idx._foreignIsWithin(target) else { return nil }
} else { // fast UTF-8
guard (
// If the transcoded offset is non-zero, then `idx` addresses a trailing
// surrogate, so its encoding offset is on a scalar boundary, and it's a
// valid UTF-16 index.
idx.transcodedOffset != 0
/// Otherwise we need to reject indices that aren't scalar aligned.
|| target._guts.isOnUnicodeScalarBoundary(idx)
) else { return nil }
}
self = idx
}
/// Returns the position in the given view of Unicode scalars that
/// corresponds exactly to this index.
///
/// This index must be a valid index of `String(unicodeScalars).utf16`.
///
/// This example first finds the position of a space (UTF-16 code point `32`)
/// in a string's `utf16` view and then uses this method to find the same
/// position in the string's `unicodeScalars` view.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf16.firstIndex(of: 32)!
/// let j = i.samePosition(in: cafe.unicodeScalars)!
/// print(String(cafe.unicodeScalars[..<j]))
/// // Prints "Café"
///
/// - Parameter unicodeScalars: The view to use for the index conversion.
/// This index must be a valid index of at least one view of the string
/// shared by `unicodeScalars`.
/// - Returns: The position in `unicodeScalars` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `unicodeScalars`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-16 trailing surrogate
/// returns `nil`.
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarIndex? {
return String.UnicodeScalarIndex(self, within: unicodeScalars)
}
}
#if SWIFT_ENABLE_REFLECTION
// Reflection
extension String.UTF16View: CustomReflectable {
/// Returns a mirror that reflects the UTF-16 view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
#endif
// Slicing
extension String.UTF16View {
public typealias SubSequence = Substring.UTF16View
public subscript(r: Range<Index>) -> Substring.UTF16View {
let r = _guts.validateSubscalarRange(r)
return Substring.UTF16View(self, _bounds: r)
}
}
// Foreign string support
extension String.UTF16View {
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(after i: Index) -> Index {
_internalInvariant(_guts.isForeign)
return i.strippingTranscoding.nextEncoded._knownUTF16
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(before i: Index) -> Index {
_internalInvariant(_guts.isForeign)
return i.strippingTranscoding.priorEncoded._knownUTF16
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignSubscript(position i: Index) -> UTF16.CodeUnit {
_internalInvariant(_guts.isForeign)
return _guts.foreignErrorCorrectedUTF16CodeUnit(at: i.strippingTranscoding)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignDistance(from start: Index, to end: Index) -> Int {
_internalInvariant(_guts.isForeign)
// Ignore transcoded offsets, i.e. scalar align if-and-only-if from a
// transcoded view
return end._encodedOffset - start._encodedOffset
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_internalInvariant(_guts.isForeign)
let l = limit._encodedOffset - i._encodedOffset
if n > 0 ? l >= 0 && l < n : l <= 0 && n < l {
return nil
}
let offset = i._encodedOffset &+ n
_precondition(offset >= 0 && offset <= _guts.count,
"String index is out of bounds")
return Index(_encodedOffset: offset)._knownUTF16
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index {
_internalInvariant(_guts.isForeign)
let offset = i._encodedOffset &+ n
_precondition(offset >= 0 && offset <= _guts.count,
"String index is out of bounds")
return Index(_encodedOffset: offset)._knownUTF16
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignCount() -> Int {
_internalInvariant(_guts.isForeign)
return endIndex._encodedOffset - startIndex._encodedOffset
}
// Align a native UTF-8 index to a valid UTF-16 position. If there is a
// transcoded offset already, this is already a valid UTF-16 position
// (referring to the second surrogate) and returns `idx`. Otherwise, this will
// scalar-align the index. This is needed because we may be passed a
// non-scalar-aligned index from the UTF8View.
@_alwaysEmitIntoClient // Swift 5.1
@inline(__always)
internal func _utf16AlignNativeIndex(_ idx: String.Index) -> String.Index {
_internalInvariant(!_guts.isForeign)
guard idx.transcodedOffset == 0 else { return idx }
return _guts.scalarAlign(idx)
}
}
extension String.Index {
@usableFromInline @inline(never) // opaque slow-path
@_effects(releasenone)
internal func _foreignIsWithin(_ target: String.UTF16View) -> Bool {
_internalInvariant(target._guts.isForeign)
// If we're transcoding, we're a UTF-8 view index, not UTF-16.
return self.transcodedOffset == 0
}
}
// Breadcrumb-aware acceleration
extension _StringGuts {
@inline(__always)
fileprivate func _useBreadcrumbs(forEncodedOffset offset: Int) -> Bool {
return hasBreadcrumbs && offset >= _StringBreadcrumbs.breadcrumbStride
}
}
extension String.UTF16View {
#if SWIFT_STDLIB_ENABLE_VECTOR_TYPES
@inline(__always)
internal func _utf16Length<U: SIMD, S: SIMD>(
readPtr: inout UnsafeRawPointer,
endPtr: UnsafeRawPointer,
unsignedSIMDType: U.Type,
signedSIMDType: S.Type
) -> Int where U.Scalar == UInt8, S.Scalar == Int8 {
var utf16Count = 0
while readPtr + MemoryLayout<U>.stride < endPtr {
//Find the number of continuations (0b10xxxxxx)
let sValue = Builtin.loadRaw(readPtr._rawValue) as S
let continuations = S.zero.replacing(with: S.one, where: sValue .< -65 + 1)
//Find the number of 4 byte code points (0b11110xxx)
let uValue = Builtin.loadRaw(readPtr._rawValue) as U
let fourBytes = S.zero.replacing(
with: S.one,
where: unsafeBitCast(
uValue .>= 0b11110000,
to: SIMDMask<S.MaskStorage>.self
)
)
utf16Count &+= U.scalarCount + Int((fourBytes &- continuations).wrappedSum())
readPtr += MemoryLayout<U>.stride
}
return utf16Count
}
#endif
@inline(__always)
internal func _utf16Distance(from start: Index, to end: Index) -> Int {
_internalInvariant(end.transcodedOffset == 0 || end.transcodedOffset == 1)
return (end.transcodedOffset - start.transcodedOffset) + _guts.withFastUTF8(
range: start._encodedOffset ..< end._encodedOffset
) { utf8 in
let rawBuffer = UnsafeRawBufferPointer(utf8)
guard rawBuffer.count > 0 else { return 0 }
var utf16Count = 0
var readPtr = rawBuffer.baseAddress.unsafelyUnwrapped
let initialReadPtr = readPtr
let endPtr = readPtr + rawBuffer.count
//eat leading continuations
while readPtr < endPtr {
let byte = readPtr.load(as: UInt8.self)
if !UTF8.isContinuation(byte) {
break
}
readPtr += 1
}
#if SWIFT_STDLIB_ENABLE_VECTOR_TYPES
// TODO: Currently, using SIMD sizes above SIMD8 is slower
// Once that's fixed we should go up to SIMD64 here
utf16Count &+= _utf16Length(
readPtr: &readPtr,
endPtr: endPtr,
unsignedSIMDType: SIMD8<UInt8>.self,
signedSIMDType: SIMD8<Int8>.self
)
//TO CONSIDER: SIMD widths <8 here
//back up to the start of the current scalar if we may have a trailing
//incomplete scalar
if utf16Count > 0 && UTF8.isContinuation(readPtr.load(as: UInt8.self)) {
while readPtr > initialReadPtr && UTF8.isContinuation(readPtr.load(as: UInt8.self)) {
readPtr -= 1
}
//The trailing scalar may be incomplete, subtract it out and check below
let byte = readPtr.load(as: UInt8.self)
let len = _utf8ScalarLength(byte)
utf16Count &-= len == 4 ? 2 : 1
if readPtr == initialReadPtr {
//if we backed up all the way and didn't hit a non-continuation, then
//we don't have any complete scalars, and we should bail.
return 0
}
}
#endif
//trailing bytes
while readPtr < endPtr {
let byte = readPtr.load(as: UInt8.self)
let len = _utf8ScalarLength(byte)
// if we don't have enough bytes left, we don't have a complete scalar,
// so don't add it to the count.
if readPtr + len <= endPtr {
utf16Count &+= len == 4 ? 2 : 1
}
readPtr += len
}
return utf16Count
}
}
@usableFromInline
@_effects(releasenone)
internal func _nativeGetOffset(for idx: Index) -> Int {
_internalInvariant(idx._encodedOffset <= _guts.count)
// Trivial and common: start
if idx == startIndex { return 0 }
if _guts.isASCII {
_internalInvariant(idx.transcodedOffset == 0)
return idx._encodedOffset
}
let idx = _utf16AlignNativeIndex(idx)
guard _guts._useBreadcrumbs(forEncodedOffset: idx._encodedOffset) else {
return _utf16Distance(from: startIndex, to: idx)
}
// Simple and common: endIndex aka `length`.
let breadcrumbsPtr = _guts.getBreadcrumbsPtr()
if idx == endIndex { return breadcrumbsPtr.pointee.utf16Length }
// Otherwise, find the nearest lower-bound breadcrumb and count from there
let (crumb, crumbOffset) = breadcrumbsPtr.pointee.getBreadcrumb(
forIndex: idx)
return crumbOffset + _utf16Distance(from: crumb, to: idx)
}
@usableFromInline
@_effects(releasenone)
internal func _nativeGetIndex(for offset: Int) -> Index {
_precondition(offset >= 0, "String index is out of bounds")
// Trivial and common: start
if offset == 0 { return startIndex }
if _guts.isASCII {
return Index(
_encodedOffset: offset
)._scalarAligned._encodingIndependent
}
guard _guts._useBreadcrumbs(forEncodedOffset: offset) else {
return _index(startIndex, offsetBy: offset)._knownUTF8
}
// Simple and common: endIndex aka `length`.
let breadcrumbsPtr = _guts.getBreadcrumbsPtr()
if offset == breadcrumbsPtr.pointee.utf16Length { return endIndex }
// Otherwise, find the nearest lower-bound breadcrumb and advance that
let (crumb, remaining) = breadcrumbsPtr.pointee.getBreadcrumb(
forOffset: offset)
if remaining == 0 { return crumb }
return _guts.withFastUTF8 { utf8 in
var readIdx = crumb._encodedOffset
let readEnd = utf8.count
_internalInvariant(readIdx < readEnd)
var utf16I = 0
let utf16End: Int = remaining
// Adjust for sub-scalar initial transcoding: If we're starting the scan
// at a trailing surrogate, then we set our starting count to be -1 so as
// offset counting the leading surrogate.
if crumb.transcodedOffset != 0 {
utf16I = -1
}
while true {
_precondition(readIdx < readEnd, "String index is out of bounds")
let len = _utf8ScalarLength(utf8[_unchecked: readIdx])
let utf16Len = len == 4 ? 2 : 1
utf16I &+= utf16Len
if utf16I >= utf16End {
// Uncommon: final sub-scalar transcoded offset
if _slowPath(utf16I > utf16End) {
_internalInvariant(utf16Len == 2)
return Index(
encodedOffset: readIdx, transcodedOffset: 1
)._knownUTF8
}
return Index(
_encodedOffset: readIdx &+ len
)._scalarAligned._knownUTF8
}
readIdx &+= len
}
}
}
// Copy (i.e. transcode to UTF-16) our contents into a buffer. `alignedRange`
// means that the indices are part of the UTF16View.indices -- they are either
// scalar-aligned or transcoded (e.g. derived from the UTF-16 view). They do
// not need to go through an alignment check.
internal func _nativeCopy(
into buffer: UnsafeMutableBufferPointer<UInt16>,
alignedRange range: Range<String.Index>
) {
_internalInvariant(_guts.isFastUTF8)
_internalInvariant(
range.lowerBound == _utf16AlignNativeIndex(range.lowerBound))
_internalInvariant(
range.upperBound == _utf16AlignNativeIndex(range.upperBound))
if _slowPath(range.isEmpty) { return }
let isASCII = _guts.isASCII
return _guts.withFastUTF8 { utf8 in
var writeIdx = 0
let writeEnd = buffer.count
var readIdx = range.lowerBound._encodedOffset
let readEnd = range.upperBound._encodedOffset
if isASCII {
_internalInvariant(range.lowerBound.transcodedOffset == 0)
_internalInvariant(range.upperBound.transcodedOffset == 0)
while readIdx < readEnd {
_internalInvariant(utf8[readIdx] < 0x80)
buffer[_unchecked: writeIdx] = UInt16(
truncatingIfNeeded: utf8[_unchecked: readIdx])
readIdx &+= 1
writeIdx &+= 1
}
return
}
// Handle mid-transcoded-scalar initial index
if _slowPath(range.lowerBound.transcodedOffset != 0) {
_internalInvariant(range.lowerBound.transcodedOffset == 1)
let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx)
buffer[writeIdx] = scalar.utf16[1]
readIdx &+= len
writeIdx &+= 1
}
// Transcode middle
while readIdx < readEnd {
let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx)
buffer[writeIdx] = scalar.utf16[0]
readIdx &+= len
writeIdx &+= 1
if _slowPath(scalar.utf16.count == 2) {
buffer[writeIdx] = scalar.utf16[1]
writeIdx &+= 1
}
}
// Handle mid-transcoded-scalar final index
if _slowPath(range.upperBound.transcodedOffset == 1) {
_internalInvariant(writeIdx < writeEnd)
let (scalar, _) = _decodeScalar(utf8, startingAt: readIdx)
_internalInvariant(scalar.utf16.count == 2)
buffer[writeIdx] = scalar.utf16[0]
writeIdx &+= 1
}
_internalInvariant(writeIdx <= writeEnd)
}
}
}
|
e7ca400fcfb2011bcca452fb9ee94a0f
| 32.711268 | 93 | 0.644175 | false | false | false | false |
yaslab/ZeroFormatter.swift
|
refs/heads/master
|
Sources/ArraySerializer.swift
|
mit
|
1
|
//
// ArraySerializer.swift
// ZeroFormatter
//
// Created by Yasuhiro Hatta on 2016/12/12.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
internal enum ArraySerializer {
// MARK: - serialize
public static func serialize<T: Serializable>(_ bytes: NSMutableData, _ offset: Int, _ value: Array<T>?) -> Int {
var byteSize = 0
if let value = value {
byteSize += BinaryUtility.serialize(bytes, value.count) // length
for v in value {
byteSize += T.serialize(bytes, -1, v)
}
} else {
byteSize += BinaryUtility.serialize(bytes, -1) // length
}
return byteSize
}
public static func serialize<T: Serializable>(_ bytes: NSMutableData, _ offset: Int, _ value: Array<Array<T>>?) -> Int {
var byteSize = 0
if let value = value {
byteSize += BinaryUtility.serialize(bytes, value.count) // length
for v in value {
byteSize += serialize(bytes, -1, v)
}
} else {
byteSize += BinaryUtility.serialize(bytes, -1) // length
}
return byteSize
}
// MARK: - deserialize
public static func deserialize<T: Serializable>(_ bytes: NSData, _ offset: Int, _ byteSize: inout Int) -> Array<T>? {
let start = byteSize
let length: Int = BinaryUtility.deserialize(bytes, offset + (byteSize - start), &byteSize)
if length < 0 {
return nil
}
var array = Array<T>()
for _ in 0 ..< length {
array.append(T.deserialize(bytes, offset + (byteSize - start), &byteSize))
}
return array
}
}
|
c595b4b535d215d83859d206de06312f
| 29.732143 | 124 | 0.556653 | false | false | false | false |
ceecer1/open-muvr
|
refs/heads/master
|
ios/Lift/LiveSessionController.swift
|
apache-2.0
|
2
|
import Foundation
import UIKit
@objc
protocol MultiDeviceSessionSettable {
func multiDeviceSessionEncoding(session: MultiDeviceSession)
func mutliDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedBetween start: CFAbsoluteTime, and end: CFAbsoluteTime)
}
class LiveSessionController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, ExerciseSessionSettable,
DeviceSessionDelegate, DeviceDelegate, MultiDeviceSessionDelegate {
private var multi: MultiDeviceSession?
private var timer: NSTimer?
private var startTime: NSDate?
private var exerciseSession: ExerciseSession?
private var pageViewControllers: [UIViewController] = []
private var pageControl: UIPageControl!
@IBOutlet var stopSessionButton: UIBarButtonItem!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let ctrl = segue.destinationViewController as? SessionFeedbackController {
if let exerciseSession = sender as? ExerciseSession {
ctrl.setExerciseSession(exerciseSession)
}
}
}
// MARK: main
override func viewWillDisappear(animated: Bool) {
timer?.invalidate()
navigationItem.prompt = nil
pageControl.removeFromSuperview()
pageControl = nil
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction
func stopSession() {
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Really?".localized()
stopSessionButton.tag = 3
} else {
end()
}
}
func end() {
if let x = exerciseSession {
performSegueWithIdentifier("toSessionFeedback", sender: x)
self.exerciseSession = nil
} else {
NSLog("[WARN] LiveSessionController.end() with sessionId == nil")
}
multi?.stop()
UIApplication.sharedApplication().idleTimerDisabled = false
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let pagesStoryboard = UIStoryboard(name: "LiveSession", bundle: nil)
pageViewControllers = ["classification", "devices", "sensorDataGroup"].map { pagesStoryboard.instantiateViewControllerWithIdentifier($0) as UIViewController }
setViewControllers([pageViewControllers.first!], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
if let nc = navigationController {
let navBarSize = nc.navigationBar.bounds.size
let origin = CGPoint(x: navBarSize.width / 2, y: navBarSize.height / 2 + navBarSize.height / 4)
pageControl = UIPageControl(frame: CGRect(x: origin.x, y: origin.y, width: 0, height: 0))
pageControl.numberOfPages = 3
nc.navigationBar.addSubview(pageControl)
}
multiDeviceSessionEncoding(multi)
// propagate to children
if let session = exerciseSession {
pageViewControllers.foreach { e in
if let s = e as? ExerciseSessionSettable {
s.setExerciseSession(session)
}
}
}
startTime = NSDate()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true)
}
func tick() {
let elapsed = Int(NSDate().timeIntervalSinceDate(startTime!))
let minutes: Int = elapsed / 60
let seconds: Int = elapsed - minutes * 60
navigationItem.prompt = "LiveSessionController.elapsed".localized(minutes, seconds)
stopSessionButton.tag -= 1
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Stop".localized()
}
}
// MARK: ExerciseSessionSettable
func setExerciseSession(session: ExerciseSession) {
self.exerciseSession = session
multi = MultiDeviceSession(delegate: self, deviceDelegate: self, deviceSessionDelegate: self)
multi!.start()
UIApplication.sharedApplication().idleTimerDisabled = true
}
private func multiDeviceSessionEncoding(session: MultiDeviceSession?) {
if let x = session {
viewControllers.foreach { e in
if let s = e as? MultiDeviceSessionSettable {
s.multiDeviceSessionEncoding(x)
}
}
}
}
private func multiDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedBetween start: CFAbsoluteTime, and end: CFAbsoluteTime) {
viewControllers.foreach { e in
if let s = e as? MultiDeviceSessionSettable {
s.mutliDeviceSession(session, continuousSensorDataEncodedBetween: start, and: end)
}
}
}
// MARK: UIPageViewControllerDataSource
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
if let x = (pageViewControllers.indexOf { $0 === viewController }) {
if x < pageViewControllers.count - 1 { return pageViewControllers[x + 1] }
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
if let x = (pageViewControllers.indexOf { $0 === viewController }) {
if x > 0 { return pageViewControllers[x - 1] }
}
return nil
}
// MARK: UIPageViewControllerDelegate
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [AnyObject], transitionCompleted completed: Bool) {
if let x = (pageViewControllers.indexOf { $0 === pageViewController.viewControllers.first! }) {
pageControl.currentPage = x
}
}
// MARK: MultiDeviceSessionDelegate
func multiDeviceSession(session: MultiDeviceSession, encodingSensorDataGroup group: SensorDataGroup) {
multiDeviceSessionEncoding(multi)
}
func multiDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedRange range: TimeRange) {
multiDeviceSession(session, continuousSensorDataEncodedBetween: range.start, and: range.end)
}
// MARK: DeviceSessionDelegate
func deviceSession(session: DeviceSession, endedFrom deviceId: DeviceId) {
end()
}
func deviceSession(session: DeviceSession, sensorDataNotReceivedFrom deviceId: DeviceId) {
// ???
}
func deviceSession(session: DeviceSession, sensorDataReceivedFrom deviceId: DeviceId, atDeviceTime: CFAbsoluteTime, data: NSData) {
if let x = exerciseSession {
x.submitData(data, f: const(()))
if UIApplication.sharedApplication().applicationState != UIApplicationState.Background {
multiDeviceSessionEncoding(multi)
}
} else {
RKDropdownAlert.title("Internal inconsistency", message: "AD received, but no sessionId.", backgroundColor: UIColor.orangeColor(), textColor: UIColor.blackColor(), time: 3)
}
}
// MARK: DeviceDelegate
func deviceGotDeviceInfo(deviceId: DeviceId, deviceInfo: DeviceInfo) {
multiDeviceSessionEncoding(multi)
}
func deviceGotDeviceInfoDetail(deviceId: DeviceId, detail: DeviceInfo.Detail) {
multiDeviceSessionEncoding(multi)
}
func deviceAppLaunched(deviceId: DeviceId) {
//
}
func deviceAppLaunchFailed(deviceId: DeviceId, error: NSError) {
//
}
func deviceDidNotConnect(error: NSError) {
multiDeviceSessionEncoding(multi)
}
func deviceDisconnected(deviceId: DeviceId) {
multiDeviceSessionEncoding(multi)
}
}
|
0046cd62bdfb75ca4529194971a10c3f
| 37.208531 | 184 | 0.660506 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Networking/Pinghub.swift
|
gpl-2.0
|
2
|
import Foundation
import Starscream
// MARK: Client
/// The delegate of a PinghubClient must adopt the PinghubClientDelegate
/// protocol. The client will inform the delegate of any relevant events.
///
public protocol PinghubClientDelegate: AnyObject {
/// The client connected successfully.
///
func pingubDidConnect(_ client: PinghubClient)
/// The client disconnected. This might be intentional or due to an error.
/// The optional error argument will contain the error if there is one.
///
func pinghubDidDisconnect(_ client: PinghubClient, error: Error?)
/// The client received an action.
///
func pinghub(_ client: PinghubClient, actionReceived action: PinghubClient.Action)
/// The client received some data that it didn't look like a known action.
///
func pinghub(_ client: PinghubClient, unexpected message: PinghubClient.Unexpected)
}
/// Encapsulates a PingHub connection.
///
public class PinghubClient {
/// The client's delegate.
///
public weak var delegate: PinghubClientDelegate?
/// The web socket to use for communication with the PingHub server.
///
private let socket: Socket
/// Initializes the client with an already configured token.
///
internal init(socket: Socket) {
self.socket = socket
setupSocketCallbacks()
}
/// Initializes the client with an OAuth2 token.
///
public convenience init(token: String) {
let socket = starscreamSocket(url: PinghubClient.endpoint, token: token)
self.init(socket: socket)
}
/// Connects the client to the server.
///
public func connect() {
#if DEBUG
guard !Debug._simulateUnreachableHost else {
DispatchQueue.main.async { [weak self] in
guard let client = self else { return }
client.delegate?.pinghubDidDisconnect(client, error: Debug.unreachableHostError)
}
return
}
#endif
socket.connect()
}
/// Disconnects the client from the server.
///
public func disconnect() {
socket.disconnect()
}
private func setupSocketCallbacks() {
socket.onConnect = { [weak self] in
guard let client = self else {
return
}
client.delegate?.pingubDidConnect(client)
}
socket.onDisconnect = { [weak self] error in
guard let client = self else {
return
}
let error = error as NSError?
let filteredError: NSError? = error.flatMap({ error in
// Filter out normal disconnects that we initiated
if error.domain == WebSocket.ErrorDomain && error.code == Int(CloseCode.normal.rawValue) {
return nil
}
return error
})
client.delegate?.pinghubDidDisconnect(client, error: filteredError)
}
socket.onData = { [weak self] data in
guard let client = self else {
return
}
client.delegate?.pinghub(client, unexpected: .data(data))
}
socket.onText = { [weak self] text in
guard let client = self else {
return
}
guard let data = text.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let message = json as? [String: AnyObject],
let action = Action.from(message: message) else {
client.delegate?.pinghub(client, unexpected: .action(text))
return
}
client.delegate?.pinghub(client, actionReceived: action)
}
}
public enum Unexpected {
/// The client received some data that was not a valid message
///
case data(Data)
/// The client received a valid message that represented an unknown action
///
case action(String)
var description: String {
switch self {
case .data(let data):
return "PingHub received unexpected data: \(data)"
case .action(let text):
return "PingHub received unexpected message: \(text)"
}
}
}
internal static let endpoint = URL(string: "https://public-api.wordpress.com/pinghub/wpcom/me/newest-note-data")!
}
// MARK: - Debug
#if DEBUG
extension PinghubClient {
enum Debug {
fileprivate static var _simulateUnreachableHost = false
static func simulateUnreachableHost(_ simulate: Bool) {
_simulateUnreachableHost = simulate
}
fileprivate static let unreachableHostError = NSError(domain: kCFErrorDomainCFNetwork as String, code: Int(CFNetworkErrors.cfHostErrorUnknown.rawValue), userInfo: nil)
}
}
@objc class PinghubDebug: NSObject {
static func simulateUnreachableHost(_ simulate: Bool) {
PinghubClient.Debug._simulateUnreachableHost = simulate
}
}
#endif
// MARK: - Action
extension PinghubClient {
/// An action received through the PingHub protocol.
///
/// This enum represents all the known possible actions that we can receive
/// through a PingHub client.
///
public enum Action {
/// A note was Added or Updated
///
case push(noteID: Int, userID: Int, date: NSDate, type: String)
/// A note was Deleted
///
case delete(noteID: Int)
/// Creates an action from a received message, if it represents a known
/// action. Otherwise, it returns `nil`
///
public static func from(message: [String: AnyObject]) -> Action? {
guard let action = message["action"] as? String else {
return nil
}
switch action {
case "push":
guard let noteID = message["note_id"] as? Int,
let userID = message["user_id"] as? Int,
let timestamp = message["newest_note_time"] as? Int,
let type = message["newest_note_type"] as? String else {
return nil
}
let date = NSDate(timeIntervalSince1970: Double(timestamp))
return .push(noteID: noteID, userID: userID, date: date, type: type)
case "delete":
guard let noteID = message["note_id"] as? Int else {
return nil
}
return .delete(noteID: noteID)
default:
return nil
}
}
}
}
// MARK: - Socket
internal protocol Socket: AnyObject {
func connect()
func disconnect()
var onConnect: (() -> Void)? { get set }
var onDisconnect: ((Error?) -> Void)? { get set }
var onText: ((String) -> Void)? { get set }
var onData: ((Data) -> Void)? { get set }
}
// MARK: - Starscream
private func starscreamSocket(url: URL, token: String) -> Socket {
var request = URLRequest(url: PinghubClient.endpoint)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
return WebSocket(request: request)
}
extension WebSocket: Socket {
@objc func disconnect() {
disconnect(forceTimeout: nil)
}
}
|
7ef03a6c3169ebee862d66b2755465f5
| 28.62 | 175 | 0.582579 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
refs/heads/main
|
Swift/first-bad-version.swift
|
mit
|
2
|
/**
* https://leetcode.com/problems/first-bad-version/
*
*
*/
/**
* The knows API is defined in the parent class VersionControl.
* func isBadVersion(_ version: Int) -> Bool{}
*/
class Solution : VersionControl {
func firstBadVersion(_ n: Int) -> Int {
var left = 1
var right = n
// left will be the index of first element with satisfied requirements.
while left < right {
let mid = left + (right - left) / 2
if isBadVersion(mid) == false {
left = mid + 1
} else {
right = mid
}
}
return left
}
}
|
fbed5638f36fd0681fe3a8f91fe8b026
| 23.884615 | 79 | 0.513138 | false | false | false | false |
xxxAIRINxxx/Cmg
|
refs/heads/master
|
Sources/VectorInput.swift
|
mit
|
1
|
//
// VectorInput.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public enum VectorType {
case position(maximumSize: Vector2)
case extent(extent: Vector4)
case color
case colorOffset
case other(count: Int)
}
public final class VectorInput: FilterInputable {
public let type: VectorType
public let key: String
public fileprivate(set) var values: [CGFloat] = []
public fileprivate(set) var ranges: [Range] = []
fileprivate var initialValue: CIVector?
init(_ type: VectorType, _ filter: CIFilter, _ key: String) {
self.type = type
self.key = key
let attributes = filter.attributes[key] as? [String : AnyObject]
let vector = attributes?[kCIAttributeDefault] as? CIVector
if let _vector = vector {
self.setVector(_vector)
self.initialValue = _vector
}
}
public func setVector(_ vector: CIVector) {
self.values.removeAll()
self.ranges.removeAll()
for i in 0..<vector.count {
let v: CGFloat = vector.value(at: i)
self.values.append(v)
switch type {
case .position(let maximumSize):
switch i {
case 0: self.ranges.append(Range(0.0, Float(maximumSize.x), Float(v)))
case 1: self.ranges.append(Range(0.0, Float(maximumSize.y), Float(v)))
default: break
}
case .extent(let extent):
switch i {
case 0: self.ranges.append(Range(0.0, Float(extent.z), Float(v)))
case 1: self.ranges.append(Range(0.0, Float(extent.w), Float(v)))
case 2: self.ranges.append(Range(0.0, Float(extent.z), Float(v)))
case 3: self.ranges.append(Range(0.0, Float(extent.w), Float(v)))
default: break
}
case .color:
self.ranges.append(Range(0.0, 1.0, Float(v)))
case .colorOffset:
self.ranges.append(Range(0.0, 1.0, Float(v)))
case .other:
self.ranges.append(Range(0.0, 1.0, Float(v)))
}
}
}
internal func setValue(_ index: Int, value: CGFloat) {
self.values[index] = value
}
public func sliders() -> [Slider] {
var names: [String]
switch type {
case .position(_):
names = ["\(self.key) x", "\(self.key) y"]
case .extent(_):
names = ["\(self.key) x", "\(self.key) y", "\(self.key) z" , "\(self.key) w"]
case .color:
names = ["\(self.key) red", "\(self.key) green", "\(self.key) blue", "\(self.key) alpha"]
case .colorOffset:
names = ["\(self.key) x", "\(self.key) y"]
case .other:
names = []
self.values.enumerated().forEach() {
names.append("\(self.key) \($0.0)")
}
}
return []
// return self.values.enumerated().map { i in
// return Slider(names[i.1], self.ranges[i.0]) { [weak self] value in
// self?.setValue(i.index, value: CGFloat(value))
// }
// }
}
public func setInput(_ filter: CIFilter) {
filter.setValue(CIVector(values: self.values, count: self.values.count), forKey: self.key)
}
public func resetValue() {
guard let _initialValue = self.initialValue else { return }
self.setVector(_initialValue)
}
}
extension VectorInput {
public var vector2: Vector2 {
get { return Vector2(values: self.values) }
}
public var vector4: Vector4 {
get { return Vector4(values: self.values) }
}
public var vectorAny: VectorAny {
get { return VectorAny(count: self.values.count, values: self.values) }
}
}
extension CGSize {
public var vector2 : Vector2 {
get { return Vector2(size: self) }
}
public var vector4 : Vector4 {
get { return Vector4(x: 0, y: 0, z: self.width, w: self.height) }
}
}
extension CGRect {
public var vector2 : Vector2 {
get { return Vector2(size: self.size) }
}
public var vector4 : Vector4 {
get { return Vector4(rect: self) }
}
}
|
bd2eb588fe150547c3566a68c1ef685e
| 28.713333 | 101 | 0.536908 | false | false | false | false |
Mai-Tai-D/maitaid001
|
refs/heads/master
|
Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisGeneratorMultiplier.swift
|
apache-2.0
|
4
|
//
// ChartAxisGeneratorMultiplier.swift
// SwiftCharts
//
// Created by ischuetz on 27/06/16.
// Copyright © 2016 ivanschuetz. All rights reserved.
//
import Foundation
public enum ChartAxisGeneratorMultiplierUpdateMode {
case halve
case nice
}
public typealias ChartAxisGeneratorMultiplierUpdater = (_ axis: ChartAxis, _ generator: ChartAxisGeneratorMultiplier) -> Double
open class ChartAxisGeneratorMultiplier: ChartAxisValuesGenerator {
open var first: Double? {
return nil
}
open var last: Double? {
return nil
}
var multiplier: Double
/// After zooming in a while the multiplier may be rounded down to 0, which means the intervals are not divisible anymore. We store the last multiplier which worked and keep returning values corresponding to it until the user zooms out until a new valid multiplier.
fileprivate var lastValidMultiplier: Double?
fileprivate let multiplierUpdater: ChartAxisGeneratorMultiplierUpdater
public init(_ multiplier: Double, multiplierUpdateMode: ChartAxisGeneratorMultiplierUpdateMode = .halve) {
let multiplierUpdater: ChartAxisGeneratorMultiplierUpdater = {
switch multiplierUpdateMode {
case .halve: return MultiplierUpdaters.halve
case .nice: return MultiplierUpdaters.nice
}
}()
self.multiplier = multiplier
self.multiplierUpdater = multiplierUpdater
}
open func axisInitialized(_ axis: ChartAxis) {}
open func generate(_ axis: ChartAxis) -> [Double] {
let updatedMultiplier = multiplierUpdater(axis, self)
return generate(axis, multiplier: updatedMultiplier)
}
fileprivate func generate(_ axis: ChartAxis, multiplier: Double) -> [Double] {
let modelStart = calculateModelStart(axis, multiplier: multiplier)
var values = [Double]()
var scalar = modelStart
while scalar <= axis.lastVisible {
if ((scalar =~ axis.firstInit && axis.zoomFactor =~ 1) || scalar >= axis.firstVisible) && ((scalar =~ axis.lastInit && axis.zoomFactor =~ 1) || scalar <= axis.lastVisible) {
values.append(scalar)
}
let newScalar = incrementScalar(scalar, multiplier: multiplier)
if newScalar =~ scalar {
return lastValidMultiplier.map{lastMultiplier in
generate(axis, multiplier: lastMultiplier).filter{$0 >= axis.firstVisible && $0 <= axis.lastVisible}
} ?? []
} else {
lastValidMultiplier = multiplier
}
scalar = newScalar
}
return values
}
func calculateModelStart(_ axis: ChartAxis, multiplier: Double) -> Double {
return (floor((axis.firstVisible - axis.firstInit) / multiplier) * multiplier) + (axis.firstInit)
}
func incrementScalar(_ scalar: Double, multiplier: Double) -> Double {
return scalar + multiplier
}
}
private struct MultiplierUpdaters {
static func halve(_ axis: ChartAxis, generator: ChartAxisGeneratorMultiplier) -> Double {
// Update intervals when zooming duplicates / halves
// In order to do this, we round the zooming factor to the lowest value in 2^0, 2^1...2^n sequence (this corresponds to 1x, 2x...nx zooming) and divide the original multiplier by this
// For example, given a 2 multiplier, when zooming in, zooming factors in 2x..<4x are rounded down to 2x, and dividing our multiplier by 2x, we get a 1 multiplier, meaning during zoom 2x..<4x the values have 1 interval length. If continue zooming in, for 4x..<8x, we get a 0.5 multiplier, etc.
let roundDecimals: Double = 1000000000000
return generator.multiplier / pow(2, floor(round(log2(axis.zoomFactor) * roundDecimals) / roundDecimals))
}
static func nice(_ axis: ChartAxis, generator: ChartAxisGeneratorMultiplier) -> Double {
let origDividers = axis.length / generator.multiplier
let newDividers = floor(origDividers * axis.zoomFactor)
return ChartNiceNumberCalculator.niceNumber(axis.length / (Double(newDividers)), round: true)
}
}
|
45a03f3dc65745f25c9236172b0c7919
| 38.935185 | 302 | 0.655844 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples
|
refs/heads/main
|
MapsAndPlacesDemo/MapsAndPlacesDemo/LocationImageGenerator.swift
|
apache-2.0
|
1
|
/* Copyright (c) 2020 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.
*/
import UIKit
import GoogleMaps
import GooglePlaces
class LocationImageGenerator {
/// This should be the dimension of the image generated, regardless of the iPhone model.
private let dim: Double = 110
// MARK: Image lookup and placement methods
/// Checks to see if a location has an image and if it does, calls another method which sets the image appropriately
///
/// - Parameters:
/// - placeId: The placeId of the location we wish to find an image of.
/// - localMarker: The marker that we want to set the image on.
/// - imageView: The image view that we want to set the image on.
/// - select: Indicates if we want the image on the image view; if this is false, tapped should be true.
/// - tapped: Indicates if we want the image on the GMSMarker; if this is false, select should be true.
/// - width: The width of the image; it is set to default at 110, found via trial/error to be good for all phone sizes.
/// - height: The height of the image; it is set to default at 110, found via trial/error to be good for all phone sizes.
func viewImage(
placeId: String,
localMarker: GMSMarker,
imageView: UIImageView,
select: Bool = false,
tapped: Bool = true,
width: Int = 110,
height: Int = 110
) {
let placesClient: GMSPlacesClient = GMSPlacesClient.shared()
let fields: GMSPlaceField = .photos
placesClient.fetchPlace(fromPlaceID: placeId, placeFields: fields, sessionToken: nil,
callback: {
(place: GMSPlace?, error: Error?) in
guard error == nil else {
print("Some error occured here: \(error?.localizedDescription ?? "")")
return
}
guard place != nil else {
print("The location is nil or does not exist: \(error?.localizedDescription ?? "")")
return
}
guard let place = place else {
print("Error loading place metadata: \(error?.localizedDescription ?? "")")
return
}
guard place.photos != nil else {
if !select {
localMarker.icon = UIImage(systemName: "eye.slash.fill")
localMarker.icon?.withTintColor(.black)
} else {
imageView.image = UIImage(systemName: "eye.slash.fill")
}
return
}
guard place.photos?.count ?? 0 > 0 else {
print("There is no place photo data: \(error?.localizedDescription ?? "")")
return
}
guard let photoMetadata = place.photos?[0] else {
print("There is no photo data for location: \(error?.localizedDescription ?? "")")
return
}
self.loadImage(
photoMetadata: photoMetadata,
placesClient: placesClient,
localMarker: localMarker,
imageView: imageView,
select: select,
tapped: tapped,
width: width,
height: height
)
})
}
/// Places the found image onto the card or marker
///
/// - Parameters:
/// - placesClient: The GMSPlacesClient instance that loads the picture information.
/// - photoMetadata: The details about the photo needed.
/// - localMarker: The marker that we want to set the image on.
/// - imageView: The image view that we want to set the image on.
/// - select: Indicates if we want the image on the image view; if this is false, tapped should be true.
/// - tapped: Indicates if we want the image on the GMSMarker; if this is false, select should be true.
/// - width: The width of the image; it is set to default at 110.
/// - height: The height of the image; it is set to default at 110.
func loadImage(
photoMetadata: GMSPlacePhotoMetadata,
placesClient: GMSPlacesClient,
localMarker: GMSMarker,
imageView: UIImageView,
select: Bool = false,
tapped: Bool = true,
width: Int = 110,
height: Int = 110
) {
placesClient.loadPlacePhoto(photoMetadata, callback: { (photo, error) -> Void in
guard error == nil else {
print("Some error occured: \(error?.localizedDescription ?? "")")
return
}
let size = select ? CGSize(width: self.dim, height: self.dim) : CGSize(
width: width,
height: height
)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
photo?.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
let finalImage = select ? UIGraphicsGetImageFromCurrentImageContext()! :
newImage.opac(alpha: 0.7)
localMarker.icon = finalImage?.circleMask
imageView.image = finalImage
UIGraphicsEndImageContext()
})
}
}
|
3f1c6d6dfcb2153cf6295a94c4e09130
| 42.609023 | 127 | 0.589655 | false | false | false | false |
nikriek/gesundheit.space
|
refs/heads/master
|
NotYet/BaseOverviewViewController.swift
|
mit
|
1
|
//
// OverviewViewController.swift
// NotYet
//
// Created by Niklas Riekenbrauck on 25.11.16.
// Copyright © 2016 Niklas Riekenbrauck. All rights reserved.
//
import UIKit
import SnapKit
import RxSwift
import RxCocoa
protocol BaseOverviewViewModel {
var statusText: Variable<NSAttributedString?> { get }
var tipText: Variable<String?> { get }
var actionTapped: PublishSubject<Void> { get }
var skipTapped: PublishSubject<Void> { get }
var actionTitle: Variable<String?> { get }
var skipTitle: Variable<String?> { get }
var done: PublishSubject<Void> { get }
var infoTapped: PublishSubject<Void> { get }
}
class BaseOverviewViewController<ViewModel: BaseOverviewViewModel>: UIViewController {
weak var coordinator: Coordinator?
private lazy var statusLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 42)
label.numberOfLines = 0
let wrapperView = UIView()
self.topStackView.insertArrangedSubview(wrapperView, at: 0)
wrapperView.addSubview(label)
label.snp.makeConstraints { make in
make.leading.equalTo(wrapperView.snp.leading).offset(38)
make.trailing.equalTo(wrapperView.snp.trailing).offset(-38)
make.bottom.equalTo(wrapperView.snp.bottom)
}
return label
}()
private lazy var tipLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 30)
label.numberOfLines = 0
let wrapperView = UIView()
self.topStackView.insertArrangedSubview(wrapperView, at: 1)
wrapperView.addSubview(label)
label.snp.makeConstraints { make in
make.leading.equalTo(wrapperView.snp.leading).offset(38)
make.trailing.equalTo(wrapperView.snp.trailing).offset(-38)
make.top.equalTo(wrapperView.snp.top)
}
return label
}()
private lazy var actionButton: UIButton = {
let button = UIButton()
button.setTitleColor(UIColor.customLightGreen, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 24)
self.bottomStackView.insertArrangedSubview(button, at: 0)
button.snp.makeConstraints { make in
make.height.equalTo(48)
}
return button
}()
private lazy var skipButton: UIButton = {
let button = UIButton()
button.setTitleColor(UIColor.gray, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
self.bottomStackView.insertArrangedSubview(button, at: 1)
return button
}()
private lazy var containerStackView: UIStackView = {
let stackView = UIStackView()
self.view.addSubview(stackView)
stackView.snp.makeConstraints { make in
make.edges.equalTo(self.view.snp.edges)
}
stackView.axis = .vertical
return stackView
}()
private lazy var topStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.spacing = 38
self.containerStackView.insertArrangedSubview(stackView, at: 0)
return stackView
}()
private lazy var infoButton: UIButton = {
let button = UIButton(type: .infoLight)
let barItem = UIBarButtonItem(customView: button)
button.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = barItem
return button
}()
private lazy var bottomStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
self.containerStackView.insertArrangedSubview(stackView, at: 1)
stackView.layoutMargins = UIEdgeInsets(top: 24, left: 0, bottom: 24, right: 0)
stackView.isLayoutMarginsRelativeArrangement = true
return stackView
}()
let viewModel: ViewModel
let disposeBag = DisposeBag()
init(viewModel: ViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel.statusText.asDriver()
.drive(statusLabel.rx.attributedText)
.addDisposableTo(disposeBag)
viewModel.tipText.asDriver()
.drive(tipLabel.rx.text)
.addDisposableTo(disposeBag)
viewModel.actionTitle.asDriver()
.drive(actionButton.rx.title())
.addDisposableTo(disposeBag)
viewModel.skipTitle.asDriver()
.drive(skipButton.rx.title())
.addDisposableTo(disposeBag)
viewModel.skipTitle.asDriver()
.map { $0 == nil }
.drive(skipButton.rx.isHidden)
.addDisposableTo(disposeBag)
actionButton.rx.tap.asObservable()
.bindTo(viewModel.actionTapped)
.addDisposableTo(disposeBag)
skipButton.rx.tap.asObservable()
.bindTo(viewModel.skipTapped)
.addDisposableTo(disposeBag)
viewModel.done.asObservable()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] in
guard let `self` = self else { return }
self.coordinator?.done(with: self)
})
.addDisposableTo(disposeBag)
infoButton.rx.tap
.bindTo(viewModel.infoTapped)
.addDisposableTo(disposeBag)
if let vm = (viewModel as? OverviewViewModel) {
vm.presentInsight
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] _ in
guard let `self` = self, let recommendationId = vm.currentRecommendation.value?.id else { return }
self.coordinator?.presentInsight(on: self, recommendationId: recommendationId)
})
.addDisposableTo(disposeBag)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
topStackView.applyGradient(topRightColor: UIColor.customLightGreen, bottomLeftColor: UIColor.customGreen)
}
}
|
09d118ff9f0066bc627e98d7192c00e1
| 30.504717 | 118 | 0.606378 | false | false | false | false |
coach-plus/ios
|
refs/heads/master
|
Pods/JWTDecode/JWTDecode/JWTDecode.swift
|
mit
|
2
|
// JWTDecode.swift
//
// Copyright (c) 2015 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
Decodes a JWT token into an object that holds the decoded body (along with token header and signature parts).
If the token cannot be decoded a `NSError` will be thrown.
- parameter jwt: jwt string value to decode
- throws: an error if the JWT cannot be decoded
- returns: a decoded token as an instance of JWT
*/
public func decode(jwt: String) throws -> JWT {
return try DecodedJWT(jwt: jwt)
}
struct DecodedJWT: JWT {
let header: [String: Any]
let body: [String: Any]
let signature: String?
let string: String
init(jwt: String) throws {
let parts = jwt.components(separatedBy: ".")
guard parts.count == 3 else {
throw DecodeError.invalidPartCount(jwt, parts.count)
}
self.header = try decodeJWTPart(parts[0])
self.body = try decodeJWTPart(parts[1])
self.signature = parts[2]
self.string = jwt
}
var expiresAt: Date? { return claim(name: "exp").date }
var issuer: String? { return claim(name: "iss").string }
var subject: String? { return claim(name: "sub").string }
var audience: [String]? { return claim(name: "aud").array }
var issuedAt: Date? { return claim(name: "iat").date }
var notBefore: Date? { return claim(name: "nbf").date }
var identifier: String? { return claim(name: "jti").string }
var expired: Bool {
guard let date = self.expiresAt else {
return false
}
return date.compare(Date()) != ComparisonResult.orderedDescending
}
}
/**
* JWT Claim
*/
public struct Claim {
/// raw value of the claim
let value: Any?
/// original claim value
public var rawValue: Any? {
return self.value
}
/// value of the claim as `String`
public var string: String? {
return self.value as? String
}
/// value of the claim as `Double`
public var double: Double? {
let double: Double?
if let string = self.string {
double = Double(string)
} else {
double = self.value as? Double
}
return double
}
/// value of the claim as `Int`
public var integer: Int? {
let integer: Int?
if let string = self.string {
integer = Int(string)
} else if let double = self.value as? Double {
integer = Int(double)
} else {
integer = self.value as? Int
}
return integer
}
/// value of the claim as `NSDate`
public var date: Date? {
guard let timestamp: TimeInterval = self.double else { return nil }
return Date(timeIntervalSince1970: timestamp)
}
/// value of the claim as `[String]`
public var array: [String]? {
if let array = value as? [String] {
return array
}
if let value = self.string {
return [value]
}
return nil
}
}
private func base64UrlDecode(_ value: String) -> Data? {
var base64 = value
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8))
let requiredLength = 4 * ceil(length / 4.0)
let paddingLength = requiredLength - length
if paddingLength > 0 {
let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0)
base64 += padding
}
return Data(base64Encoded: base64, options: .ignoreUnknownCharacters)
}
private func decodeJWTPart(_ value: String) throws -> [String: Any] {
guard let bodyData = base64UrlDecode(value) else {
throw DecodeError.invalidBase64Url(value)
}
guard let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), let payload = json as? [String: Any] else {
throw DecodeError.invalidJSON(value)
}
return payload
}
|
b1ef00796171efee89f1da9e2adb9551
| 30.974684 | 128 | 0.641132 | false | false | false | false |
lucasmpaim/EasyRest
|
refs/heads/master
|
Sources/EasyRest/Classes/AuthenticableService.swift
|
mit
|
1
|
//
// AuthenticableService.swift
// Pods
//
// Created by Vithorio Polten on 3/25/16.
// Base on Tof Template
//
//
import Foundation
open class AuthenticableService<Auth: Authentication, R: Routable> : Service<R>, Authenticable {
var authenticator = Auth()
public override init() { super.init() }
open func getAuthenticator() -> Auth {
return authenticator
}
open override func builder<T : Codable>(_ routes: R, type: T.Type) throws -> APIBuilder<T> {
let builder = try super.builder(routes, type: type)
_ = builder.addInterceptor(authenticator.interceptor)
return builder
}
override open func call<E: Codable>(_ routes: R, type: E.Type, onSuccess: @escaping (Response<E>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) throws -> CancelationToken<E> {
let builder = try self.builder(routes, type: type)
if routes.rule.isAuthenticable && authenticator.getToken() == nil {
throw RestError(rawValue: RestErrorType.authenticationRequired.rawValue)
}
let token = CancelationToken<E>()
builder.cancelToken(token: token).build().execute(onSuccess, onError: onError, always: always)
return token
}
override open func upload<E: Codable>(_ routes: R, type: E.Type,
onProgress: @escaping (Float) -> Void,
onSuccess: @escaping (Response<E>?) -> Void,
onError: @escaping (RestError?) -> Void,
always: @escaping () -> Void) throws {
let builder = try self.builder(routes, type: type)
if routes.rule.isAuthenticable && authenticator.getToken() == nil {
throw RestError(rawValue: RestErrorType.authenticationRequired.rawValue)
}
builder.build().upload(
onProgress,
onSuccess: onSuccess,
onError: onError,
always: always)
}
}
|
5276b72900a1a99ba288d8e17c6d171d
| 34.694915 | 214 | 0.575973 | false | false | false | false |
goto10/Vapor-FileMaker
|
refs/heads/master
|
Tests/PerfectFileMakerTests/PerfectFileMakerTests.swift
|
apache-2.0
|
1
|
import XCTest
@testable import FileMakerConnector
let testHost = "127.0.0.1"
let testPort = 80
let testUserName = ""
let testPassword = ""
let sampleDB = "FMServer_Sample"
let sampleLayout = "Task Details"
class PerfectFileMakerTests: XCTestCase {
func getServer() -> FileMakerServer {
return FileMakerServer(host: testHost, port: testPort, userName: testUserName, password: testPassword)
}
func testDatabaseNames() {
let expect = self.expectation(description: "done")
let fms = getServer()
fms.databaseNames {
result in
defer {
expect.fulfill()
}
do {
let names = try result()
XCTAssert(names.contains(sampleDB))
} catch FMPError.serverError(let code, let msg) {
return XCTAssert(false, "\(code) \(msg)")
} catch let e {
return XCTAssert(false, "\(e)")
}
}
self.waitForExpectations(timeout: 60.0) {
_ in
}
}
func testLayoutNames() {
let expect = self.expectation(description: "done")
let fms = getServer()
fms.layoutNames(database: sampleDB) {
result in
defer {
expect.fulfill()
}
guard let names = try? result() else {
return XCTAssert(false, "\(result)")
}
XCTAssert(names.contains(sampleLayout))
}
self.waitForExpectations(timeout: 60.0) {
_ in
}
}
func testLayoutInfo() {
let expectedNames = ["Status", "Category", "Description", "Task", "Related | Sort Selection",
"Days Till Due", "Due Date", "Assignees::Name", "Assignees::Phone",
"Assignees::Email", "Attachments::Attachment | Container",
"Attachments::Comments", "Related Tasks::Task",
"Related Tasks::Due Date", "Related Tasks::Description"]
let expect = self.expectation(description: "done")
let fms = getServer()
fms.layoutInfo(database: sampleDB, layout: sampleLayout) {
result in
defer {
expect.fulfill()
}
guard let layoutInfo = try? result() else {
return XCTAssert(false, "\(result))")
}
let fieldsByName = layoutInfo.fieldsByName
for expectedField in expectedNames {
let fnd = fieldsByName[expectedField]
XCTAssert(nil != fnd)
}
}
self.waitForExpectations(timeout: 60.0) {
_ in
}
}
func testQuerySkipMax() {
let expect = self.expectation(description: "done")
let fms = getServer()
func maxZero() {
let query = FMPQuery(database: sampleDB, layout: sampleLayout, action: .findAll).maxRecords(0)
XCTAssert("-db=FMServer_Sample&-lay=Task%20Details&-skip=0&-max=0&-findall" == "\(query)")
fms.query(query) {
result in
guard let resultSet = try? result() else {
XCTAssert(false, "\(result))")
return expect.fulfill()
}
let records = resultSet.records
let recordCount = records.count
XCTAssert(recordCount == 0)
maxTwo()
}
}
func maxTwo() {
let query = FMPQuery(database: sampleDB, layout: sampleLayout, action: .findAll).skipRecords(2).maxRecords(2)
XCTAssert("-db=FMServer_Sample&-lay=Task%20Details&-skip=2&-max=2&-findall" == "\(query)")
fms.query(query) {
result in
guard let resultSet = try? result() else {
XCTAssert(false, "\(result))")
return expect.fulfill()
}
let records = resultSet.records
let recordCount = records.count
XCTAssert(recordCount == 2)
expect.fulfill()
}
}
maxZero()
self.waitForExpectations(timeout: 60.0) {
_ in
}
}
func testQueryFindAll() {
let query = FMPQuery(database: sampleDB, layout: sampleLayout, action: .findAll)
let expect = self.expectation(description: "done")
let fms = getServer()
fms.query(query) {
result in
defer {
expect.fulfill()
}
guard let resultSet = try? result() else {
return XCTAssert(false, "\(result))")
}
let fields = resultSet.layoutInfo.fields
let records = resultSet.records
let recordCount = records.count
XCTAssert(recordCount > 0)
for i in 0..<recordCount {
let rec = records[i]
for field in fields {
switch field {
case .fieldDefinition(let def):
let name = def.name
let fnd = rec.elements[name]
XCTAssert(nil != fnd, "\(name) not found in \(rec.elements)")
guard case .field(let fn, _) = fnd! else {
XCTAssert(false, "expected field \(fnd)")
continue
}
XCTAssert(fn == name)
case .relatedSetDefinition(let name, let defs):
let fnd = rec.elements[name]
XCTAssert(nil != fnd, "\(name) not found in \(rec.elements)")
guard case .relatedSet(let fn, let relatedRecs) = fnd! else {
XCTAssert(false, "expected relatedSet \(fnd)")
continue
}
XCTAssert(fn == name)
let defNames = defs.map { $0.name }
for relatedRec in relatedRecs {
for relatedRow in relatedRec.elements.values {
guard case .field(let fn, _) = relatedRow else {
XCTAssert(false)
continue
}
XCTAssert(defNames.contains(fn), "strange field name \(fn)")
}
}
}
}
}
}
self.waitForExpectations(timeout: 60.0) {
_ in
}
}
func testQueryFindInProgress() {
let qfields = [FMPQueryFieldGroup(fields: [FMPQueryField(name: "Status", value: "In Progress")])]
let query = FMPQuery(database: sampleDB, layout: sampleLayout, action: .find).queryFields(qfields)
XCTAssert("-db=FMServer_Sample&-lay=Task%20Details&-skip=0&-max=all&-query=(q1)&-q1=Status&-q1.value===In%20Progress*&-findquery" == "\(query)")
let expect = self.expectation(description: "done")
let fms = getServer()
fms.query(query) {
result in
defer {
expect.fulfill()
}
guard let resultSet = try? result() else {
return XCTAssert(false, "\(result))")
}
let fields = resultSet.layoutInfo.fields
let records = resultSet.records
let recordCount = records.count
XCTAssert(recordCount > 0)
for i in 0..<recordCount {
let rec = records[i]
for field in fields {
switch field {
case .fieldDefinition(let def):
let name = def.name
let fnd = rec.elements[name]
XCTAssert(nil != fnd, "\(name) not found in \(rec.elements)")
guard case .field(let fn, let fieldValue) = fnd! else {
XCTAssert(false, "expected field \(fnd)")
continue
}
XCTAssert(fn == name)
if name == "Status" {
guard case .text(let tstStr) = fieldValue else {
XCTAssert(false, "bad value \(fieldValue)")
continue
}
XCTAssert("In Progress" == tstStr, "\(tstStr)")
}
case .relatedSetDefinition(let name, let defs):
let fnd = rec.elements[name]
XCTAssert(nil != fnd, "\(name) not found in \(rec.elements)")
guard case .relatedSet(let fn, let relatedRecs) = fnd! else {
XCTAssert(false, "expected relatedSet \(fnd)")
continue
}
XCTAssert(fn == name)
let defNames = defs.map { $0.name }
for relatedRec in relatedRecs {
for relatedRow in relatedRec.elements.values {
guard case .field(let fn, _) = relatedRow else {
XCTAssert(false)
continue
}
XCTAssert(defNames.contains(fn), "strange field name \(fn)")
}
}
}
}
}
}
self.waitForExpectations(timeout: 60.0) {
_ in
}
}
func testNewAndDelete() {
let unique = time(nil)
let task = "Add a new record @ \(unique) ☃️"
let qfields = [FMPQueryField(name: "Task", value: task), FMPQueryField(name: "Status", value: "In Progress")]
let query = FMPQuery(database: sampleDB, layout: sampleLayout, action: .new).queryFields(qfields)
XCTAssert("-db=FMServer_Sample&-lay=Task%20Details&Task=Add%20a%20new%20record%20@%20\(unique)%20%E2%98%83%EF%B8%8F&Status=In%20Progress&-new" == "\(query)")
let expect = self.expectation(description: "done")
let fms = getServer()
fms.query(query) {
result in
guard let resultSet = try? result() else {
XCTAssert(false, "\(result))")
return expect.fulfill()
}
XCTAssert(resultSet.records.count == 0)
let findQuery = FMPQuery(database: sampleDB, layout: sampleLayout, action: .find).queryFields([FMPQueryField(name: "Task", value: task, op: .equal)])
XCTAssert("-db=FMServer_Sample&-lay=Task%20Details&-skip=0&-max=all&-query=(q1)&-q1=Task&-q1.value===Add%20a%20new%20record%20@%20\(unique)%20%E2%98%83%EF%B8%8F&-findquery" == "\(findQuery)")
fms.query(findQuery) {
result in
guard let resultSet = try? result() else {
XCTAssert(false, "\(result))")
return expect.fulfill()
}
XCTAssert(resultSet.records.count == 1)
let recId = resultSet.records.first!.recordId
XCTAssert(recId != fmpNoRecordId)
let query = FMPQuery(database: sampleDB, layout: sampleLayout, action: .find).recordId(recId)
print("\(query)")
fms.query(query) {
result in
guard let resultSet = try? result() else {
XCTAssert(false, "\(result))")
return expect.fulfill()
}
XCTAssert(resultSet.records.count == 1)
let recId = resultSet.records.first!.recordId
XCTAssert(recId != fmpNoRecordId)
let query = FMPQuery(database: sampleDB, layout: sampleLayout, action: .delete).recordId(recId)
fms.query(query) {
result in
guard let resultSet = try? result() else {
return XCTAssert(false, "\(result))")
}
XCTAssert(resultSet.records.count == 0)
fms.query(findQuery) {
result in
defer {
expect.fulfill()
}
guard let resultSet = try? result() else {
XCTAssert(false, "\(result))")
return expect.fulfill()
}
XCTAssert(resultSet.records.count == 0)
}
}
}
}
}
self.waitForExpectations(timeout: 60.0) {
_ in
}
}
static var allTests : [(String, (PerfectFileMakerTests) -> () throws -> Void)] {
return [
("testDatabaseNames", testDatabaseNames),
("testLayoutNames", testLayoutNames),
("testLayoutInfo", testLayoutInfo),
("testQuerySkipMax", testQuerySkipMax),
("testQueryFindAll", testQueryFindAll),
("testQueryFindInProgress", testQueryFindInProgress),
("testNewAndDelete", testNewAndDelete),
]
}
}
|
8445d139524cec5e91071f237dadf5a0
| 28.430636 | 194 | 0.627516 | false | true | false | false |
nodes-vapor/ironman
|
refs/heads/master
|
App/Commands/CheckListItemsSeeder.swift
|
mit
|
1
|
import Console
import MySQL
public final class CheckListItemsSeeder: Command {
public let id = "seeder:checklist"
public let help: [String] = [
"Seeds the database with checlist items"
]
public let console: ConsoleProtocol
public init(console: ConsoleProtocol) {
self.console = console
}
public func run(arguments: [String]) throws {
console.info("Started the seeder for checklists");
let mysql = try MySQL.Database(
host: "127.0.0.1",
user: "root",
password: "secret",
database: "ironman-old"
)
let result = try mysql.execute("SELECT * FROM checklist_items")
try result.forEach({
let item = $0;
let raceId = try MigrateHelper.oldRaceIdToNew(oldRaceId: item["race_id"]?.int ?? 0)
let title = item["title"]?.string ?? "";
let type = item["type"]?.string ?? "registration"
let position = item["position"]?.int ?? 0
let isActive = item["is_active"]?.bool ?? false
let updatedAt = item["modified"]?.string ?? "1970-01-01 00:00:00"
let createdAt = item["created_at"]?.string ?? "1970-01-01 00:00:00"
do {
var checkListItem: CheckListItem = try CheckListItem(node: Node([
"race_id": Node(raceId),
"title": Node(title),
"type": Node(type),
"position": Node(position),
"is_active": Node(isActive),
"updated_at": Node(updatedAt),
"created_at": Node(createdAt)
]))
try checkListItem.save()
} catch
{
drop.console.error("Could not save checklist")
}
})
console.info("Finished the seeder for checklists");
}
}
|
e031591c893b749e0a3fc904c5353b4d
| 30.825397 | 95 | 0.496758 | false | false | false | false |
FaiChou/Cassini
|
refs/heads/master
|
Cassini/Cassini/UIView+Extension.swift
|
mit
|
1
|
//
// UIView+Extension.swift
// Cassini
//
// Created by 周辉 on 2017/5/10.
// Copyright © 2017年 周辉. All rights reserved.
//
import Foundation
import UIKit
public extension UIView {
func addTopBorderWithColor(color: UIColor, width: CGFloat = 0.5) {
let view = UIView()
view.backgroundColor = color
addSubview(view)
view.snp.makeConstraints { (make) in
make.width.equalToSuperview()
make.height.equalTo(width)
make.top.equalToSuperview()
make.left.equalToSuperview()
}
}
enum BubbleDirection {
case left, right
}
func bubble(_ direction: BubbleDirection = .left) {
let iv = UIImageView()
iv.frame = CGRect(origin: .zero, size: bounds.size)
let imageDirName = direction == .left ? "bubble-left" : "bubble-right"
let capInsets = direction == .left ? UIEdgeInsetsMake(20, 20, 20, 20) : UIEdgeInsetsMake(30, 50, 30, 50)
iv.image = UIImage(named: imageDirName)?
.resizableImage(withCapInsets: capInsets,
resizingMode: .stretch)
self.layer.mask = iv.layer
}
}
extension UIView {
func contains(point: CGPoint) -> Bool {
let radius = bounds.width / 2
let dx = point.x-center.x
let dy = point.y-center.y
if (dx*dx + dy*dy) <= radius*radius {
return true
} else {
return false
}
}
}
extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 3) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(Double.pi * 2)
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
|
334fe4eeffbfd78b948decbf934ef9be
| 28.3 | 108 | 0.669511 | false | false | false | false |
creatubbles/ctb-api-swift
|
refs/heads/develop
|
CreatubblesAPIClient/Sources/Mapper/ContentEntryMapper.swift
|
mit
|
1
|
//
// ContentEntryMapper.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import ObjectMapper
class ContentEntryMapper: Mappable {
var identifier: String?
var type: String?
var userRelationship: RelationshipMapper?
var creationRelationship: RelationshipMapper?
var galleryRelationship: RelationshipMapper?
var partnerApplicationRelationship: RelationshipMapper?
required init?(map: Map) { /* Intentionally left empty */ }
func mapping(map: Map) {
identifier <- map["id"]
type <- map["attributes.type"]
userRelationship <- map["relationships.user.data"]
creationRelationship <- map["relationships.creation.data"]
galleryRelationship <- map["relationships.gallery.data"]
partnerApplicationRelationship <- map["relationships.partner_application.data"]
}
func parseCreationRelationship() -> Relationship? {
return MappingUtils.relationshipFromMapper(creationRelationship)
}
func parseGalleryRelationship() -> Relationship? {
return MappingUtils.relationshipFromMapper(galleryRelationship)
}
func parseUserRelationship() -> Relationship? {
return MappingUtils.relationshipFromMapper(userRelationship)
}
func parsePartnerApplicationRelationship() -> Relationship? {
return MappingUtils.relationshipFromMapper(partnerApplicationRelationship)
}
func parseType() -> ContentEntryType {
if type == "creation" { return .creation }
if type == "gallery" { return .gallery }
if type == "user" { return .user }
if type == "partner_application" { return .partnerApplication }
return .unknown
}
}
|
bdc4af16b66e265407e50afd192c77eb
| 39.3 | 87 | 0.721021 | false | false | false | false |
srxboys/RXSwiftExtention
|
refs/heads/master
|
Pods/SwifterSwift/Source/Extensions/DictionaryExtensions.swift
|
mit
|
1
|
//
// DictionaryExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/24/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
// MARK: - Methods
public extension Dictionary {
/// SwifterSwift: Check if key exists in dictionary.
///
/// - Parameter key: key to search for
/// - Returns: true if key exists in dictionary.
func has(key: Key) -> Bool {
return index(forKey: key) != nil
}
/// SwifterSwift: JSON Data from dictionary.
///
/// - Parameter prettify: set true to prettify data (default is false).
/// - Returns: optional JSON Data (if applicable).
public func jsonData(prettify: Bool = false) -> Data? {
guard JSONSerialization.isValidJSONObject(self) else {
return nil
}
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
return try? JSONSerialization.data(withJSONObject: self, options: options)
}
/// SwifterSwift: JSON String from dictionary.
///
/// - Parameter prettify: set true to prettify string (default is false).
/// - Returns: optional JSON String (if applicable).
public func jsonString(prettify: Bool = false) -> String? {
guard JSONSerialization.isValidJSONObject(self) else {
return nil
}
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
let jsonData = try? JSONSerialization.data(withJSONObject: self, options: options)
return jsonData?.string(encoding: .utf8)
}
}
// MARK: - Methods (ExpressibleByStringLiteral)
public extension Dictionary where Key: ExpressibleByStringLiteral {
/// SwifterSwift: Lowercase all keys in dictionary.
public mutating func lowercaseAllKeys() {
// http://stackoverflow.com/questions/33180028/extend-dictionary-where-key-is-of-type-string
for key in keys {
if let lowercaseKey = String(describing: key).lowercased() as? Key {
self[lowercaseKey] = removeValue(forKey: key)
}
}
}
}
|
5f61931637c0f747b8d381d4e343c3b3
| 30.1875 | 120 | 0.719439 | false | false | false | false |
LearningSwift2/LearningApps
|
refs/heads/master
|
SimpleTableView/SimpleTableView/MovieTableViewController.swift
|
apache-2.0
|
1
|
//
// MovieTableViewController.swift
// SimpleTableView
//
// Created by Phil Wright on 1/1/16.
// Copyright © 2016 Touchopia, LLC. All rights reserved.
//
import UIKit
class MovieTableViewController: UITableViewController {
var movies = ["Star Wars IV - A new hope", "Star Wars V - The Empire Strikes Back", "Star Wars III = Revenge of the Sith"]
override func viewDidLoad() {
super.viewDidLoad()
// Adjust for status bar
self.tableView.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.movies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell", forIndexPath: indexPath)
cell.textLabel?.text = self.movies[indexPath.row]
return cell
}
}
|
ba2b21174ebeb171b3d32fb1f2d24e09
| 26.595238 | 126 | 0.677308 | false | false | false | false |
njdehoog/Spelt
|
refs/heads/master
|
Sources/Spelt/Document.swift
|
mit
|
1
|
// Any file which contains front matter and is not a blog post is considered a document
public final class Document: FileWithMetadata {
public let path: String
public var destinationPath: String?
public var contents: String
public var metadata: Metadata
public init(path: String, contents: String = "", metadata: Metadata = .none) {
self.path = path
self.contents = contents
self.metadata = metadata
}
}
|
619b8fe08b542eaa42092d25344dc5e0
| 34.153846 | 87 | 0.682713 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.