repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cristov26/moviesApp | MoviesApp/MoviesApp/Views/MovieTabBarController.swift | 1 | 2538 | //
// MovieTabBarController.swift
// MoviesApp
//
// Created by Cristian Tovar on 11/16/17.
// Copyright © 2017 Cristian Tovar. All rights reserved.
//
import UIKit
class MovieTabBarController: UITabBarController {
override func awakeFromNib() {
super.awakeFromNib()
tabBar.barStyle = .black
tabBar.unselectedItemTintColor = .white
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let popularViewController = storyboard.instantiateViewController(withIdentifier: "navController") as! UINavigationController
let topRatedViewController = storyboard.instantiateViewController(withIdentifier: "navController") as! UINavigationController
let upcomingViewController = storyboard.instantiateViewController(withIdentifier: "navController") as! UINavigationController
let popular = "Popular"
let topRated = "Top rated"
let upcoming = "Upcoming"
let popularItem = UITabBarItem(title: popular, image: UIImage(named: "icon-Popular"), tag: 0)
let topRatedItem = UITabBarItem(title: topRated , image: UIImage(named: "icon-TopRated"), tag: 0)
let upcomingItem = UITabBarItem(title: upcoming, image: UIImage(named: "icon-Upcoming"), tag: 0)
popularViewController.tabBarItem = popularItem
popularViewController.navigationBar.topItem?.title = popular
topRatedViewController.tabBarItem = topRatedItem
topRatedViewController.navigationBar.topItem?.title = topRated
upcomingViewController.tabBarItem = upcomingItem
upcomingViewController.navigationBar.topItem?.title = upcoming
(topRatedViewController.viewControllers[0] as! MoviesViewController).presentCategory(MovieStoreCategory.TopRated)
(upcomingViewController.viewControllers[0] as! MoviesViewController).presentCategory(MovieStoreCategory.Upcoming)
viewControllers = [popularViewController, topRatedViewController, upcomingViewController]
UITabBar.appearance().shadowImage = UIImage()
UITabBar.appearance().backgroundImage = UIImage()
//Then, add the custom top line view with custom color. And set the default background color of tabbar
let lineView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0.2))
lineView.backgroundColor = UIColor(red: 128/255 , green: 127/255, blue: 137/255, alpha: 1)
tabBar.addSubview(lineView)
}
}
| mit | 2ebee5e701e6ae8c01afec863f0f6819 | 44.303571 | 133 | 0.709105 | 5.307531 | false | false | false | false |
alperdemirci/To-Do | To Do/MapViewController.swift | 1 | 5069 | //
// MapViewController.swift
// To Do
//
// Created by alper on 5/22/17.
// Copyright © 2017 alper. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
protocol ScreenshotProtocol {
func screenshotImage(image: UIImage)
}
enum mapViewMode: UInt {
case callingFromListItemViewController
case callingFromAddNewItemViewController
}
class MapViewController: UIViewController, UISearchBarDelegate, CLLocationManagerDelegate {
let database = FirebaseDataAdapter()
var delegate: ScreenshotProtocol?
var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
var locationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
@IBAction func searchPressed(_ sender: UIBarButtonItem) {
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
self.searchController.searchBar.delegate = self
present(searchController, animated: true, completion: nil)
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
self.searchController.searchBar.delegate = self
present(searchController, animated: true, completion: nil)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
searchBar.resignFirstResponder()
dismiss(animated: true, completion: nil)
if self.mapView.annotations.count != 0 {
annotation = self.mapView.annotations[0]
self.mapView.removeAnnotation(annotation)
}
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.start { (localSearchResponse, error) -> Void in
if localSearchResponse == nil{
let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
}
let location = CLLocationCoordinate2DMake(localSearchResponse!.boundingRegion.center.latitude, localSearchResponse!.boundingRegion.center.longitude) // Lattitude - Longitude
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegionMake(location, span)
self.mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = searchBar.text
// annotation.subtitle = ""
self.mapView.addAnnotation(annotation)
self.mapView.showsUserLocation = false
self.locationManager.stopUpdatingLocation()
}
}
// MARK: CLLocation delegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegionMake(myLocation, span)
self.mapView.setRegion(region, animated: true)
}
//MARK: screenshot
func screenShotMethod() {
let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.render(in: UIGraphicsGetCurrentContext()!)
guard let screenshot = UIGraphicsGetImageFromCurrentImageContext() else {
return
}
UIGraphicsEndImageContext()
//pass the image via protocol to addViewController
delegate?.screenshotImage(image: screenshot)
}
override func viewWillDisappear(_ animated: Bool) {
print("view will disappear")
self.screenShotMethod()
super.viewWillDisappear(true)
}
}
| mit | 6129021b965c49854740bf8ad53d88ab | 38.286822 | 185 | 0.695343 | 5.845444 | false | false | false | false |
Ehrippura/firefox-ios | Client/Frontend/Browser/Tab.swift | 1 | 19414 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Storage
import Shared
import SwiftyJSON
import XCGLogger
protocol TabHelper {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol TabDelegate {
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar)
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar)
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String)
@objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView)
@objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView)
}
struct TabState {
var isPrivate: Bool = false
var desktopSite: Bool = false
var isBookmarked: Bool = false
var url: URL?
var title: String?
var favicon: Favicon?
}
class Tab: NSObject {
fileprivate var _isPrivate: Bool = false
internal fileprivate(set) var isPrivate: Bool {
get {
return _isPrivate
}
set {
if _isPrivate != newValue {
_isPrivate = newValue
}
}
}
var tabState: TabState {
return TabState(isPrivate: _isPrivate, desktopSite: desktopSite, isBookmarked: isBookmarked, url: url, title: displayTitle, favicon: displayFavicon)
}
// PageMetadata is derived from the page content itself, and as such lags behind the
// rest of the tab.
var pageMetadata: PageMetadata?
var canonicalURL: URL? {
if let string = pageMetadata?.siteURL,
let siteURL = URL(string: string) {
return siteURL
}
return self.url
}
var webView: WKWebView?
var tabDelegate: TabDelegate?
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
fileprivate var lastRequest: URLRequest?
var restoring: Bool = false
var pendingScreenshot = false
var url: URL?
fileprivate var _noImageMode = false
// Use computed property so @available can be used to guard `noImageMode`.
@available(iOS 11, *)
var noImageMode: Bool {
get { return _noImageMode }
set {
if newValue == _noImageMode {
return
}
_noImageMode = newValue
let helper = (contentBlocker as? ContentBlockerHelper)
helper?.noImageMode(enabled: _noImageMode)
}
}
// There is no 'available macro' on props, we currently just need to store ownership.
var contentBlocker: AnyObject?
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
/// Whether or not the desktop site was requested with the last request, reload or navigation. Note that this property needs to
/// be managed by the web view's navigation delegate.
var desktopSite: Bool = false
var isBookmarked: Bool = false
var readerModeAvailableOrActive: Bool {
if let readerMode = self.getHelper(name: "ReaderMode") as? ReaderMode {
return readerMode.state != .unavailable
}
return false
}
fileprivate(set) var screenshot: UIImage?
var screenshotUUID: UUID?
// If this tab has been opened from another, its parent will point to the tab from which it was opened
var parent: Tab?
fileprivate var helperManager: HelperManager?
fileprivate var configuration: WKWebViewConfiguration?
/// Any time a tab tries to make requests to display a Javascript Alert and we are not the active
/// tab instance, queue it for later until we become foregrounded.
fileprivate var alertQueue = [JSAlertInfo]()
init(configuration: WKWebViewConfiguration, isPrivate: Bool = false) {
self.configuration = configuration
super.init()
self.isPrivate = isPrivate
if #available(iOS 11, *) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let profile = appDelegate.profile {
contentBlocker = ContentBlockerHelper(tab: self, profile: profile)
}
}
}
class func toTab(_ tab: Tab) -> RemoteTab? {
if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) {
let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed())
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: Date.now(),
icon: nil)
} else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty {
let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed())
if let displayURL = history.first {
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
assert(configuration != nil, "Create webview can only be called once")
configuration!.userContentController = WKUserContentController()
configuration!.preferences = WKPreferences()
configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false
configuration!.allowsInlineMediaPlayback = true
let webView = TabWebView(frame: CGRect.zero, configuration: configuration!)
webView.delegate = self
configuration = nil
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
webView.backgroundColor = UIColor.lightGray
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
helperManager = HelperManager(webView: webView)
restore(webView)
self.webView = webView
self.webView?.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
tabDelegate?.tab?(self, didCreateWebView: webView)
}
}
func restore(_ webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var urls = [String]()
for url in sessionData.urls {
urls.append(url.absoluteString)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = urls as AnyObject?
jsonDict["currentPage"] = currentPage as AnyObject?
guard let json = JSON(jsonDict).stringValue() else {
return
}
let escapedJSON = json.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let restoreURL = URL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)")
lastRequest = PrivilegedRequest(url: restoreURL!) as URLRequest
webView.load(lastRequest!)
} else if let request = lastRequest {
webView.load(request)
} else {
print("creating webview with no lastRequest and no session data: \(self.url?.description ?? "nil")")
}
}
deinit {
if let webView = webView {
tabDelegate?.tab?(self, willDeleteWebView: webView)
webView.removeObserver(self, forKeyPath: "URL")
}
}
var loading: Bool {
return webView?.isLoading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList
}
var historyList: [URL] {
func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url }
var tabs = self.backList?.map(listToUrl) ?? [URL]()
tabs.append(self.url!)
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title {
if !title.isEmpty {
return title
}
}
// When picking a display title. Tabs with sessionData are pending a restore so show their old title.
// To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle.
if let url = self.url, url.isAboutHomeURL, sessionData == nil, !restoring {
return ""
}
guard let lastTitle = lastTitle, !lastTitle.isEmpty else {
return self.url?.displayURL?.absoluteString ?? ""
}
return lastTitle
}
var currentInitialURL: URL? {
get {
let initalURL = self.webView?.backForwardList.currentItem?.initialURL
return initalURL
}
}
var displayFavicon: Favicon? {
var width = 0
var largest: Favicon?
for icon in favicons where icon.width! > width {
width = icon.width!
largest = icon
}
return largest
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
_ = webView?.goBack()
}
func goForward() {
_ = webView?.goForward()
}
func goToBackForwardListItem(_ item: WKBackForwardListItem) {
_ = webView?.go(to: item)
}
@discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? {
if let webView = webView {
lastRequest = request
return webView.load(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
let userAgent: String? = desktopSite ? UserAgent.desktopUserAgent() : nil
if (userAgent ?? "") != webView?.customUserAgent,
let currentItem = webView?.backForwardList.currentItem {
webView?.customUserAgent = userAgent
// Reload the initial URL to avoid UA specific redirection
loadRequest(PrivilegedRequest(url: currentItem.initialURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60) as URLRequest)
return
}
if let _ = webView?.reloadFromOrigin() {
print("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
print("restoring webView from scratch")
restore(webView)
}
}
func addHelper(_ helper: TabHelper, name: String) {
helperManager!.addHelper(helper, name: name)
}
func getHelper(name: String) -> TabHelper? {
return helperManager?.getHelper(name)
}
func hideContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = false
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = true
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(_ bar: SnackBar) {
bars.append(bar)
tabDelegate?.tab(self, didAddSnackbar: bar)
}
func removeSnackbar(_ bar: SnackBar) {
if let index = bars.index(of: bar) {
bars.remove(at: index)
tabDelegate?.tab(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
for i in (0..<bars.count).reversed() {
let bar = bars[i]
removeSnackbar(bar)
}
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
for i in (0..<bars.count).reversed() {
let bar = bars[i]
if !bar.shouldPersist(self) {
removeSnackbar(bar)
}
}
}
func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = UUID()
}
}
func toggleDesktopSite() {
desktopSite = !desktopSite
reload()
}
func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) {
alertQueue.append(alert)
}
func dequeueJavascriptAlertPrompt() -> JSAlertInfo? {
guard !alertQueue.isEmpty else {
return nil
}
return alertQueue.removeFirst()
}
func cancelQueuedAlerts() {
alertQueue.forEach { alert in
alert.cancel()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let webView = object as? WKWebView, webView == self.webView,
let path = keyPath, path == "URL" else {
return assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
}
func isDescendentOf(_ ancestor: Tab) -> Bool {
var tab = parent
while tab != nil {
if tab! == ancestor {
return true
}
tab = tab?.parent
}
return false
}
func setNightMode(_ enabled: Bool) {
webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(enabled))", completionHandler: nil)
}
func injectUserScriptWith(fileName: String, type: String = "js", injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, mainFrameOnly: Bool = true) {
guard let webView = self.webView else {
return
}
if let path = Bundle.main.path(forResource: fileName, ofType: type),
let source = try? String(contentsOfFile: path) {
let userScript = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly)
webView.configuration.userContentController.addUserScript(userScript)
}
}
}
extension Tab: TabWebViewDelegate {
fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) {
tabDelegate?.tab(self, didSelectFindInPageForSelection: selection)
}
}
private class HelperManager: NSObject, WKScriptMessageHandler {
fileprivate var helpers = [String: TabHelper]()
fileprivate weak var webView: WKWebView?
init(webView: WKWebView) {
self.webView = webView
}
@objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
if scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
}
func addHelper(_ helper: TabHelper, name: String) {
if let _ = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right TabHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
webView?.configuration.userContentController.add(self, name: scriptMessageHandlerName)
}
}
func getHelper(_ name: String) -> TabHelper? {
return helpers[name]
}
}
private protocol TabWebViewDelegate: class {
func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String)
}
private class TabWebView: WKWebView, MenuHelperInterface {
fileprivate weak var delegate: TabWebViewDelegate?
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return super.canPerformAction(action, withSender: sender) || action == MenuHelper.SelectorFindInPage
}
@objc func menuHelperFindInPage() {
evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection)
}
}
fileprivate override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// The find-in-page selection menu only appears if the webview is the first responder.
becomeFirstResponder()
return super.hitTest(point, with: event)
}
}
///
// Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector
//
// This class only exists to contain the swizzledMenuHelperFindInPage. This class is actually never
// instantiated. It only serves as a placeholder for the method. When the method is called, self is
// actually pointing to a WKContentView. Which is not public, but that is fine, we only need to know
// that it is a UIView subclass to access its superview.
//
class TabWebViewMenuHelper: UIView {
@objc func swizzledMenuHelperFindInPage() {
if let tabWebView = superview?.superview as? TabWebView {
tabWebView.evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
tabWebView.delegate?.tabWebView(tabWebView, didSelectFindInPageForSelection: selection)
}
}
}
}
| mpl-2.0 | e2323dc1620f4975fa461b5f44683838 | 33.421986 | 157 | 0.62527 | 5.298581 | false | false | false | false |
jakeshi01/IFlySpeechPackage | IFlyTest/IFlyTest/Audio/AudioManager.swift | 1 | 6541 | //
// AudioManager.swift
// IFlyTest
//
// Created by Jake on 2017/8/15.
// Copyright © 2017年 Jake. All rights reserved.
//
import Foundation
import AVFoundation
fileprivate struct AudioConfig {
fileprivate let recorderSetting: Dictionary = [
AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM),
AVSampleRateKey: NSNumber(value: 11025.0),
AVNumberOfChannelsKey: NSNumber(value: 2),
AVLinearPCMBitDepthKey: NSNumber(value: 16),
AVEncoderAudioQualityKey: NSNumber(value: AVAudioQuality.min.rawValue)
]
fileprivate var cacheSourceFilePath: String {
return NSTemporaryDirectory().appending("/livelesson.caf")
}
}
@objc enum AudioPlayStatus: Int {
case loading = 0
case success
case fail
}
@objc protocol AudioManagerDelegate {
@objc optional func onVolumeChanged(_ value: Double)
@objc optional func onLoading(_ success: AudioPlayStatus)
}
class AudioManager: NSObject {
var delegate: AudioManagerDelegate?
var maxRecordTime: TimeInterval = 60.0 //秒级
var isMeteringEnabled: Bool = false
fileprivate var timer: Timer?
fileprivate var isEncodingSuccess: Bool = false
fileprivate lazy var player: AVPlayer = AVPlayer()
fileprivate lazy var audioSession: AVAudioSession = AVAudioSession.sharedInstance()
fileprivate lazy var audioEncoding: AudioEncoding = AudioEncoding()
fileprivate lazy var audioConfig: AudioConfig = AudioConfig()
fileprivate lazy var fileManager: FileManager = FileManager.default
fileprivate lazy var audioRecorder: AVAudioRecorder? = { [unowned self] in
guard let cacheUrl = URL(string: self.audioConfig.cacheSourceFilePath) else {
return nil
}
let audioRecorder = try? AVAudioRecorder(url: cacheUrl, settings: self.audioConfig.recorderSetting)
guard let recorder = audioRecorder else {
return nil
}
return recorder
}()
fileprivate var isStopPlay: Bool = false {
didSet{
guard isStopPlay , oldValue != isStopPlay else {
return
}
player.currentItem?.removeObserver(self, forKeyPath: "status")
}
}
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(AudioManager.playerDidFinished), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
deinit {
timer?.invalidate()
timer = nil
NotificationCenter.default.removeObserver(self)
}
}
private extension AudioManager {
func deletSourceFile() {
guard fileManager.fileExists(atPath: audioConfig.cacheSourceFilePath) else { return }
try? fileManager.removeItem(atPath: audioConfig.cacheSourceFilePath)
}
func audioVolumeChanged() {
guard let recorder = audioRecorder else {
return
}
if recorder.currentTime > maxRecordTime {
stopRecord()
return
}
recorder.updateMeters()
let value: Double = Double(recorder.averagePower(forChannel: 0))
let volume: Double = pow(10.0, 0.05 * value)
delegate?.onVolumeChanged?(volume)
}
func addPlayerItemObserver() {
player.currentItem?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
}
}
extension AudioManager {
@discardableResult
func startRecord() -> Bool {
guard let recorder = audioRecorder else {
return false
}
if recorder.isRecording {
cancelRecord()
}
deletSourceFile()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioSession.setActive(true)
} catch {
return false
}
recorder.isMeteringEnabled = isMeteringEnabled
if isMeteringEnabled {
timer = Timer.every(0.1, target: self, { [weak self] _ in
self?.audioVolumeChanged()
})
}
isEncodingSuccess = false
return recorder.prepareToRecord() && recorder.record()
}
func stopRecord() {
guard let recorder = audioRecorder else { return }
if recorder.delegate == nil {
recorder.delegate = self
}
recorder.stop()
audioEncoding.sourceFilePath = audioConfig.cacheSourceFilePath
isEncodingSuccess = audioEncoding.encodingPCMToMP3()
}
func cancelRecord() {
timer?.invalidate()
timer = nil
audioRecorder?.delegate = nil
audioRecorder?.stop()
isEncodingSuccess = false
}
@discardableResult
func playAudio(with path: String?) -> Bool {
stopPlayAudio()
guard let playPath = path else {
return false
}
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
try audioSession.setActive(true)
} catch {
return false
}
let playUrl: URL? = playPath.hasPrefix("http") ? URL(string: playPath) : URL.init(fileURLWithPath: playPath)
guard let url = playUrl else {
return false
}
let playItem = AVPlayerItem(url: url)
player.replaceCurrentItem(with: playItem)
addPlayerItemObserver()
isStopPlay = false
player.play()
return true
}
func stopPlayAudio() {
isStopPlay = true
player.pause()
}
func getMP3FilePath() -> String? {
return isEncodingSuccess ? audioEncoding.ouputFilePath : nil
}
}
extension AudioManager: AVAudioRecorderDelegate {
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
timer?.invalidate()
timer = nil
}
}
extension AudioManager {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let path = keyPath, path == "status" else {
return
}
delegate?.onLoading?(.loading)
switch player.status {
case .unknown:
delegate?.onLoading?(.loading)
case .readyToPlay:
delegate?.onLoading?(.success)
case .failed:
delegate?.onLoading?(.fail)
}
}
@objc func playerDidFinished() {
isStopPlay = true
}
}
| mit | 04b86a63ccffe435cb9988530ae290bc | 28.565611 | 174 | 0.625191 | 5.206375 | false | false | false | false |
xwu/swift | test/IDE/newtype.swift | 1 | 12357 | // RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk-nosource) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=Newtype -skip-unavailable -access-filter-public > %t.printed.A.txt
// RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt
// RUN: %target-typecheck-verify-swift -sdk %clang-importer-sdk -I %S/Inputs/custom-modules -I %t
// REQUIRES: objc_interop
// PRINT-LABEL: struct ErrorDomain : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: extension ErrorDomain {
// PRINT-NEXT: func process()
// PRINT-NEXT: static let one: ErrorDomain
// PRINT-NEXT: static let errTwo: ErrorDomain
// PRINT-NEXT: static let three: ErrorDomain
// PRINT-NEXT: static let fourErrorDomain: ErrorDomain
// PRINT-NEXT: static let stillAMember: ErrorDomain
// PRINT-NEXT: }
// PRINT-NEXT: struct Food {
// PRINT-NEXT: init()
// PRINT-NEXT: }
// PRINT-NEXT: extension Food {
// PRINT-NEXT: static let err: ErrorDomain
// PRINT-NEXT: }
// PRINT-NEXT: struct ClosedEnum : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: extension ClosedEnum {
// PRINT-NEXT: static let firstClosedEntryEnum: ClosedEnum
// PRINT-NEXT: static let secondEntry: ClosedEnum
// PRINT-NEXT: static let thirdEntry: ClosedEnum
// PRINT-NEXT: }
// PRINT-NEXT: struct IUONewtype : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: struct MyFloat : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: Float)
// PRINT-NEXT: init(rawValue: Float)
// PRINT-NEXT: let rawValue: Float
// PRINT-NEXT: typealias RawValue = Float
// PRINT-NEXT: }
// PRINT-NEXT: extension MyFloat {
// PRINT-NEXT: static let globalFloat: MyFloat{{$}}
// PRINT-NEXT: static let PI: MyFloat{{$}}
// PRINT-NEXT: static let version: MyFloat{{$}}
// PRINT-NEXT: }
//
// PRINT-LABEL: struct MyInt : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: Int32)
// PRINT-NEXT: init(rawValue: Int32)
// PRINT-NEXT: let rawValue: Int32
// PRINT-NEXT: typealias RawValue = Int32
// PRINT-NEXT: }
// PRINT-NEXT: extension MyInt {
// PRINT-NEXT: static let zero: MyInt{{$}}
// PRINT-NEXT: static let one: MyInt{{$}}
// PRINT-NEXT: }
// PRINT-NEXT: let kRawInt: Int32
// PRINT-NEXT: func takesMyInt(_: MyInt)
//
// PRINT-LABEL: extension NSURLResourceKey {
// PRINT-NEXT: static let isRegularFileKey: NSURLResourceKey
// PRINT-NEXT: static let isDirectoryKey: NSURLResourceKey
// PRINT-NEXT: static let localizedNameKey: NSURLResourceKey
// PRINT-NEXT: }
// PRINT-NEXT: extension NSNotification.Name {
// PRINT-NEXT: static let Foo: NSNotification.Name
// PRINT-NEXT: static let bar: NSNotification.Name
// PRINT-NEXT: static let NSWibble: NSNotification.Name
// PRINT-NEXT: }
// PRINT-NEXT: let kNotification: String
// PRINT-NEXT: let Notification: String
// PRINT-NEXT: let swiftNamedNotification: String
//
// PRINT-LABEL: struct CFNewType : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: CFString)
// PRINT-NEXT: init(rawValue: CFString)
// PRINT-NEXT: let rawValue: CFString
// PRINT-NEXT: typealias RawValue = CFString
// PRINT-NEXT: }
// PRINT-NEXT: extension CFNewType {
// PRINT-NEXT: static let MyCFNewTypeValue: CFNewType
// PRINT-NEXT: static let MyCFNewTypeValueUnauditedButConst: CFNewType
// PRINT-NEXT: static var MyCFNewTypeValueUnaudited: Unmanaged<CFString>
// PRINT-NEXT: }
// PRINT-NEXT: func FooAudited() -> CFNewType
// PRINT-NEXT: func FooUnaudited() -> Unmanaged<CFString>
//
// PRINT-LABEL: struct MyABINewType : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: CFString)
// PRINT-NEXT: init(rawValue: CFString)
// PRINT-NEXT: let rawValue: CFString
// PRINT-NEXT: typealias RawValue = CFString
// PRINT-NEXT: }
// PRINT-NEXT: typealias MyABIOldType = CFString
// PRINT-NEXT: extension MyABINewType {
// PRINT-NEXT: static let global: MyABINewType!
// PRINT-NEXT: }
// PRINT-NEXT: let kMyABIOldTypeGlobal: MyABIOldType!
// PRINT-NEXT: func getMyABINewType() -> MyABINewType!
// PRINT-NEXT: func getMyABIOldType() -> MyABIOldType!
// PRINT-NEXT: func takeMyABINewType(_: MyABINewType!)
// PRINT-NEXT: func takeMyABIOldType(_: MyABIOldType!)
// PRINT-NEXT: func takeMyABINewTypeNonNull(_: MyABINewType)
// PRINT-NEXT: func takeMyABIOldTypeNonNull(_: MyABIOldType)
// PRINT-LABEL: struct MyABINewTypeNS : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: typealias MyABIOldTypeNS = NSString
// PRINT-NEXT: func getMyABINewTypeNS() -> MyABINewTypeNS!
// PRINT-NEXT: func getMyABIOldTypeNS() -> String!
// PRINT-NEXT: func takeMyABINewTypeNonNullNS(_: MyABINewTypeNS)
// PRINT-NEXT: func takeMyABIOldTypeNonNullNS(_: String)
//
// PRINT-NEXT: struct NSSomeContext {
// PRINT-NEXT: init()
// PRINT-NEXT: init(i: Int32)
// PRINT-NEXT: var i: Int32
// PRINT-NEXT: }
// PRINT-NEXT: extension NSSomeContext {
// PRINT-NEXT: struct Name : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: }
// PRINT-NEXT: extension NSSomeContext.Name {
// PRINT-NEXT: static let myContextName: NSSomeContext.Name
// PRINT-NEXT: }
//
// PRINT-NEXT: struct TRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: OpaquePointer)
// PRINT-NEXT: init(rawValue: OpaquePointer)
// PRINT-NEXT: let rawValue: OpaquePointer
// PRINT-NEXT: typealias RawValue = OpaquePointer
// PRINT-NEXT: }
// PRINT-NEXT: struct ConstTRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: OpaquePointer)
// PRINT-NEXT: init(rawValue: OpaquePointer)
// PRINT-NEXT: let rawValue: OpaquePointer
// PRINT-NEXT: typealias RawValue = OpaquePointer
// PRINT-NEXT: }
// PRINT-NEXT: func create_T() -> TRef
// PRINT-NEXT: func create_ConstT() -> ConstTRef
// PRINT-NEXT: func destroy_T(_: TRef!)
// PRINT-NEXT: func destroy_ConstT(_: ConstTRef!)
// PRINT-NEXT: extension TRef {
// PRINT-NEXT: func mutatePointee()
// PRINT-NEXT: mutating func mutate()
// PRINT-NEXT: }
// PRINT-NEXT: extension ConstTRef {
// PRINT-NEXT: func use()
// PRINT-NEXT: }
//
// PRINT-NEXT: struct TRefRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: UnsafeMutablePointer<OpaquePointer>)
// PRINT-NEXT: init(rawValue: UnsafeMutablePointer<OpaquePointer>)
// PRINT-NEXT: let rawValue: UnsafeMutablePointer<OpaquePointer>
// PRINT-NEXT: typealias RawValue = UnsafeMutablePointer<OpaquePointer>
// PRINT-NEXT: }
// PRINT-NEXT: struct ConstTRefRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable {
// PRINT-NEXT: init(_ rawValue: UnsafePointer<OpaquePointer>)
// PRINT-NEXT: init(rawValue: UnsafePointer<OpaquePointer>)
// PRINT-NEXT: let rawValue: UnsafePointer<OpaquePointer>
// PRINT-NEXT: typealias RawValue = UnsafePointer<OpaquePointer>
// PRINT-NEXT: }
// PRINT-NEXT: func create_TRef() -> TRefRef
// PRINT-NEXT: func create_ConstTRef() -> ConstTRefRef
// PRINT-NEXT: func destroy_TRef(_: TRefRef!)
// PRINT-NEXT: func destroy_ConstTRef(_: ConstTRefRef!)
// PRINT-NEXT: extension TRefRef {
// PRINT-NEXT: func mutatePointee()
// PRINT-NEXT: mutating func mutate()
// PRINT-NEXT: }
// PRINT-NEXT: extension ConstTRefRef {
// PRINT-NEXT: func use()
// PRINT-NEXT: }
import Newtype
func tests() {
let errOne = ErrorDomain.one
errOne.process()
let fooErr = Food.err
fooErr.process()
Food().process() // expected-error{{value of type 'Food' has no member 'process'}}
let thirdEnum = ClosedEnum.thirdEntry
thirdEnum.process()
// expected-error@-1{{value of type 'ClosedEnum' has no member 'process'}}
let _ = ErrorDomain(rawValue: thirdEnum.rawValue)
let _ = ClosedEnum(rawValue: errOne.rawValue)
let _ = NSNotification.Name.Foo
let _ = NSNotification.Name.bar
let _ : CFNewType = CFNewType.MyCFNewTypeValue
let _ : CFNewType = CFNewType.MyCFNewTypeValueUnauditedButConst
let _ : CFNewType = CFNewType.MyCFNewTypeValueUnaudited
// expected-error@-1{{cannot convert value of type 'Unmanaged<CFString>?' to specified type 'CFNewType'}}
}
func acceptSwiftNewtypeWrapper<T : _SwiftNewtypeWrapper>(_ t: T) { }
func acceptEquatable<T : Equatable>(_ t: T) { }
func acceptHashable<T : Hashable>(_ t: T) { }
func acceptObjectiveCBridgeable<T : _ObjectiveCBridgeable>(_ t: T) { }
func testConformances(ed: ErrorDomain) {
acceptSwiftNewtypeWrapper(ed)
acceptEquatable(ed)
acceptHashable(ed)
acceptObjectiveCBridgeable(ed)
}
func testFixit() {
let _ = NSMyContextName
// expected-error@-1{{'NSMyContextName' has been renamed to 'NSSomeContext.Name.myContextName'}} {{10-25=NSSomeContext.Name.myContextName}}
}
func testNonEphemeralInitParams(x: OpaquePointer) {
var x = x
_ = TRefRef(&x) // expected-warning {{inout expression creates a temporary pointer, but argument #1 should be a pointer that outlives the call to 'init(_:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafeMutablePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = TRefRef(rawValue: &x) // expected-warning {{inout expression creates a temporary pointer, but argument 'rawValue' should be a pointer that outlives the call to 'init(rawValue:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafeMutablePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = ConstTRefRef(&x) // expected-warning {{inout expression creates a temporary pointer, but argument #1 should be a pointer that outlives the call to 'init(_:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = ConstTRefRef(rawValue: &x) // expected-warning {{inout expression creates a temporary pointer, but argument 'rawValue' should be a pointer that outlives the call to 'init(rawValue:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
}
| apache-2.0 | 739c35ab581edd515a0b70b043386141 | 47.269531 | 222 | 0.718621 | 3.870028 | false | false | false | false |
slimane-swift/WS | Sources/Server.swift | 1 | 3799 | //
// WebSocketServer.swift
// HangerSocket
//
// Created by Yuki Takei on 5/5/16.
//
//
// Server.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 AsyncHTTPSerializer
import HTTPUpgradeAsync
public class WebSocketServer: AsyncResponder, AsyncMiddleware {
private let didConnect: @escaping (WebSocket, Request) -> Void
public init(_ didConnect: @escaping (WebSocket, Request) -> Void) {
self.didConnect = didConnect
}
public func respond(to request: Request, chainingTo chain: AsyncResponder, result: @escaping ((Void) throws -> Response) -> Void) {
guard request.isWebSocket && request.webSocketVersion == "13", let key = request.webSocketKey else {
return chain.respond(to: request, result: result)
}
WebSocket.accept(key: key) { accept in
do {
guard let accept = try accept() else {
return result {
throw S4.ServerError.internalServerError
}
}
let headers: Headers = [
"Connection": "Upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Accept": accept
]
let upgrade: (Request, AsyncStream) -> Void = { request, stream in
let socket = WebSocket(stream: stream, mode: .server)
self.didConnect(socket, request)
socket.start()
}
var response = Response(status: .switchingProtocols, headers: headers)
response.didUpgradeAsync = upgrade
result {
response
}
} catch {
result {
throw error
}
}
}
}
public func respond(to request: Request, result: @escaping ((Void) throws -> Response) -> Void) {
let badRequest = BasicAsyncResponder { _, result in
result {
throw S4.ClientError.badRequest
}
}
return respond(to: request, chainingTo: badRequest, result: result)
}
}
public extension Message {
public var webSocketVersion: String? {
return headers["Sec-Websocket-Version"]
}
public var webSocketKey: String? {
return headers["Sec-Websocket-Key"]
}
public var webSocketAccept: String? {
return headers["Sec-WebSocket-Accept"]
}
public var isWebSocket: Bool {
return connection?.lowercased() == "upgrade" && upgrade?.lowercased() == "websocket"
}
}
| mit | 892b29ccb9438b667a055908a2cd5fbd | 33.225225 | 135 | 0.598052 | 4.946615 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/BannerView/BannerView.swift | 1 | 7269 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
// ???: automaticallyAdjustsScrollViewInsets = false 在一个只有这个视图的Controller中加上这句
import UIKit
class BannerView: UIView {
var pageStepTime = 5 { /// 自动滚动时间间隔
didSet {
setTheTimer()
}
}
var isAllowLooping = true {
willSet {
if !newValue {
deinitTimer()
}
}
}
var handleBack: ((Int) -> Void)?
var showPageControl = true {
willSet {
if !newValue {
pageControl?.removeFromSuperview()
}
}
}
fileprivate let cellIdentifier = "scrollUpCell"
private var timer: DispatchSourceTimer?
fileprivate var pageControl: UIPageControl?
fileprivate var collectionView: UICollectionView?
fileprivate var urlStrs: [String] = [] {
didSet { /// 图片链接
if oldValue != urlStrs {
collectionView?.reloadData()
if isAllowLooping {
collectionView?.scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false)
}
setTheTimer()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
let layout = UICollectionViewFlowLayout()
layout.itemSize = bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
collectionView?.collectionViewLayout = layout
backgroundColor = UIColor.white
collectionView?.backgroundColor = .white
collectionView?.dataSource = self
collectionView?.delegate = self
collectionView?.register(BannerCell.self, forCellWithReuseIdentifier: cellIdentifier)
collectionView?.isPagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
addSubview(collectionView!)
pageControl = UIPageControl(frame: CGRect(x: (frame.width - 60) / 2, y: frame.height - 30, width: 60, height: 20))
pageControl?.pageIndicatorTintColor = UIColor(white: 0.7, alpha: 0.8)
addSubview(pageControl!)
}
fileprivate func setTheTimer() {
if isAllowLooping {
timer = DispatchSource.makeTimerSource(queue: .main)
timer?.schedule(deadline: .now() + .seconds(pageStepTime), repeating: .seconds(pageStepTime))
timer?.setEventHandler {
self.nextItem()
}
// 启动定时器
timer?.resume()
}
}
fileprivate func deinitTimer() {
if let time = timer {
time.cancel()
timer = nil
}
}
func nextItem() {
if let indexPath = collectionView?.indexPathsForVisibleItems.first {
if indexPath.row + 1 < urlStrs.count {
collectionView?.scrollToItem(at: IndexPath(item: indexPath.row + 1, section: 0), at: .centeredHorizontally, animated: true)
} else {
collectionView?.scrollToItem(at: IndexPath(item: indexPath.row, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
func set(content: [String]) {
if content.isEmpty { return }
isAllowLooping = content.count > 1
urlStrs = isAllowLooping ? [content[content.count - 1]] + content + [content[0]] : content
pageControl?.numberOfPages = content.count
}
deinit {
deinitTimer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension BannerView: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return urlStrs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
cell.backgroundColor = .white
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
cell.backgroundColor = UIColor(white: CGFloat(indexPath.row) / 10, alpha: 1)
let bannerCell = (cell as? BannerCell)
bannerCell?.urlStr = urlStrs[(indexPath).row]
bannerCell?.text = indexPath.row.description
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let handleBack = self.handleBack {
handleBack(max((indexPath).row - 1, 0))
}
}
// MARK: - UIScrollViewDelegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
deinitTimer()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x / scrollView.frame.width
let currentPage = {
let value = page.truncatingRemainder(dividingBy: 1) < 0.3
if value { // cell过半才改变pageControl
self.pageControl?.currentPage = Int(page) - (self.isAllowLooping ? 1 : 0)
}
}
currentPage()
guard isAllowLooping else { return }
if page <= 0.0 {
// 向右拉
collectionView?.scrollToItem(at: IndexPath(item: urlStrs.count - 2, section: 0), at: .centeredHorizontally, animated: false)
pageControl?.currentPage = urlStrs.count - 3
} else if page >= CGFloat(urlStrs.count - 1) {
// 向左
pageControl?.currentPage = 0
collectionView?.scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false)
} else {
currentPage()
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
setTheTimer()
}
}
class BannerCell: UICollectionViewCell {
private let imageView = UIImageView()
private lazy var textLabel: UILabel = {
let textLabel = UILabel(frame: self.bounds.insetBy(dx: 15, dy: 15))
textLabel.textAlignment = .center
textLabel.textColor = UIColor.white
textLabel.font = UIFont.systemFont(ofSize: 66)
return textLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
imageView.frame = bounds
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.isUserInteractionEnabled = true
contentView.addSubview(imageView)
contentView.addSubview(textLabel)
}
var text: String? {
didSet {
textLabel.text = text
}
}
var urlStr: String! {
didSet {
// if let url = URL(string: urlStr) {
// imageView.kf.setImage(with: url)
// }
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 80e5a7e2f134cbe82212a02ed7ba885b | 31.944954 | 139 | 0.614035 | 5.193059 | false | false | false | false |
kemalenver/SwiftHackerRank | Algorithms/Strings.playground/Pages/Strings - Two Strings.xcplaygroundpage/Contents.swift | 1 | 759 |
import Foundation
var inputs = ["2", "hello", "world", "hi", "world"] // YES
func readLine() -> String? {
let next = inputs.first
inputs.removeFirst()
return next
}
func checkPair(string1: String.UTF8View, string2: String.UTF8View) -> Bool {
let alphabet = "abcdefghijklmnopqrstuvwxyz".utf8
for letter in alphabet {
if (string1.contains(letter) && string2.contains(letter)) {
return true
}
}
return false
}
let numberpairs = Int(readLine()!)!
for _ in 0..<numberpairs {
let string1 = readLine()!.utf8
let string2 = readLine()!.utf8
if checkPair(string1: string1, string2: string2) {
print("YES")
} else {
print("NO")
}
}
| mit | 0385ee2ae108a3c998b033ee1356a04d | 17.975 | 76 | 0.575758 | 3.81407 | false | false | false | false |
tardate/LittleArduinoProjects | Equipment/TraceTogetherToken/TTTScan/TTTScan/TTToken.swift | 1 | 1738 | import Foundation
import CoreBluetooth
class TTToken : NSObject {
let frame: [UInt8]
init(frame: [UInt8]) {
self.frame = frame
}
func version() -> String {
return "0x" + String(frame[18], radix:16, uppercase: true)
}
func id() -> String {
return "0x" + String(frame[19], radix:16, uppercase: true)
}
func mac() -> String {
let value: [UInt8] = Array(frame[0..<6])
return "0x" + asHexString(value: value)
}
func companyEncryptedUUID() -> String {
let value: [UInt8] = Array(frame[6..<16])
return "0x" + asHexString(value: value)
}
func dumpDetails() {
print(" --> TTToken : seems like this might be one: Version = \(version()) ID = \(id())")
print(" --> TTToken : companyEncryptedUUID = \(companyEncryptedUUID())")
print(" --> TTToken : MAC = \(mac())")
}
private func asHexString(value: [UInt8]) -> String {
var retval = ""
for byte in value {
var s = String(byte, radix:16, uppercase: true)
if s.count == 1 {
s = "0" + s
}
retval += s
}
return retval
}
class func findInFrame(advertisementFrameList: [NSObject : AnyObject]) -> TTToken? {
let uuid = CBUUID(string: "FFFF")
if let frameData = advertisementFrameList[uuid] as? NSData {
let frameSize = frameData.length
if frameSize == 20 {
var frameBytes = [UInt8](repeating: 0, count: frameSize)
frameData.getBytes(&frameBytes, length: frameSize)
return TTToken(frame: frameBytes)
}
}
return nil
}
}
| mit | 70fe14f358fe42621d57e6211b97e917 | 27.966667 | 98 | 0.529919 | 4.198068 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Publish-发布/Controller/XMGPostWordViewController.swift | 1 | 4425 | //
// XMGPostWordViewController.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/3/4.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
class XMGPostWordViewController: UIViewController {
/** 文本输入控件 */
var textView:XMGPlaceholderTextView?
/** 工具条 */
var toolbar:XMGAddTagToolbar?
override func viewDidLoad() {
super.viewDidLoad()
setupNav()
setupTextView()
setupToolbar()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: 设置单行文本
func setupTextView(){
let textView:XMGPlaceholderTextView = XMGPlaceholderTextView()
textView.frame = self.view.bounds;
textView.placeholder = "把好玩的图片,好笑的段子或糗事发到这里,接受千万网友膜拜吧!发布违反国家法律内容的,我们将依法提交给有关部门处理。";
textView.delegate = self;
self.view.addSubview(textView)
self.textView = textView;
}
//MARK: 设置导航栏
func setupNav() {
self.title = "发表文字";
// 设置导航栏标题
//self.navigationItem.titleView = UIImageView(image: UIImage(named: "MainTitle"))
// 设置导航栏左的按钮
//self.navigationItem.leftBarButtonItem = UIBarButtonItem.ItemWithBarButtonItem("MainTagSubIcon", target: self, action: "tagClick")
//self.navigationItem.rightBarButtonItem = UIBarButtonItem.ItemWithBarButtonItem("MainTagSubIcon", target: self, action: "tagClick")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "cancel")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发表", style: UIBarButtonItemStyle.Done, target: self, action: "post")
// 设置背景色
self.view.backgroundColor = XMGGlobalBg;
// 默认不能点击
self.navigationItem.rightBarButtonItem!.enabled = false
// 强制刷新
self.navigationController?.navigationBar.layoutIfNeeded()
}
//MARK: 设置键盘工具条
func setupToolbar(){
let toolbar:XMGAddTagToolbar = XMGAddTagToolbar.viewFromXIB()
toolbar.width = self.view.width;
toolbar.y = self.view.height - toolbar.height;
self.view.addSubview(toolbar)
self.toolbar = toolbar;
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
func keyboardWillChangeFrame(note: NSNotification){
// 键盘显示\隐藏完毕的frame
let keyboardF:CGRect = note.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
// 动画时间
let duration:Double = note.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
// 动画 及时刷新
UIView.animateWithDuration(duration) { () -> Void in
self.toolbar!.transform = CGAffineTransformMakeTranslation(0, keyboardF.origin.y - XMGScreenH)
}
}
func cancel(){
dismissViewControllerAnimated(true, completion: nil)
}
func post(){
}
/// 点击别的地方会结束编辑
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// 主动召唤键盘
textView!.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// 主动隐藏键盘
textView!.resignFirstResponder()
}
}
extension XMGPostWordViewController:UITextViewDelegate{
// MARK: - UITextViewDelegate
func textViewDidChange(textView: UITextView) {
self.navigationItem.rightBarButtonItem!.enabled = textView.hasText()
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.view.endEditing(true)
}
}
| apache-2.0 | 7dea6e2c5f4529c2d754affbb6358dd5 | 29.251852 | 158 | 0.644711 | 4.838863 | false | false | false | false |
Dan2552/Monies | Monies/app/general/NavigationFlow.swift | 1 | 1779 | import UIKit
import Placemat
class NavigationFlow {
func presentLockscreen() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window = try! Navigation(viewController: LockViewController()).setupWindow()
}
func presentMainScreen(from current: LockViewController) {
let accounts = BankAccountIndexViewController()
accounts.title = "Overview"
let tab1 = embedInNavigationController(accounts)
tab1.tabBarItem.title = "Overview"
tab1.tabBarItem.image = UIImage(named: "money_box-50")
let banks = BankLoginIndexViewController()
banks.title = "Banks"
let tab2 = embedInNavigationController(banks)
tab2.tabBarItem.title = "Banks"
tab2.tabBarItem.image = UIImage(named: "safe-50")
let tabs = UITabBarController()
tabs.viewControllers = [tab1, tab2]
Navigation(viewController: current).show(target: tabs)
}
func presentEditBankLogin(from current: UIViewController, bankLogin: BankLogin? = nil) {
let target = BankLoginEditViewController()
target.bankLogin = bankLogin ?? target.bankLogin
Navigation(viewController: current).show(target: target, modally: true)
}
func presentBankLogin(from current: UIViewController, bankLogin: BankLogin) {
let target = BankLoginShowViewController()
target.bankLogin = bankLogin
Navigation(viewController: current).show(target: target)
}
private func embedInNavigationController(_ viewController: UIViewController) -> UIViewController {
let navigation = UINavigationController()
navigation.viewControllers = [viewController]
return navigation
}
}
| mit | 6e9235999ee7284e9e39d86a208187d9 | 37.673913 | 102 | 0.681844 | 5.082857 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/Alamofire/Tests/DownloadTests.swift | 7 | 18223 | // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
import XCTest
class DownloadInitializationTestCase: BaseTestCase {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
func testDownloadClassMethodWithMethodURLAndDestination() {
// Given
let URLString = "https://httpbin.org/"
let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
// When
let request = Alamofire.download(.GET, URLString, destination: destination)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
// Given
let URLString = "https://httpbin.org/"
let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
// When
let request = Alamofire.download(.GET, URLString, headers: ["Authorization": "123456"], destination: destination)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class DownloadResponseTestCase: BaseTestCase {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
let cachesURL: NSURL = {
let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true)
return cachesURL
}()
var randomCachesFileURL: NSURL {
return cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")
}
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "https://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(
directory: searchPathDirectory,
domain: searchPathDomain
)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
do {
let contents = try fileManager.contentsOfDirectoryAtURL(
directory,
includingPropertiesForKeys: nil,
options: .SkipsHiddenFiles
)
#if os(iOS) || os(tvOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(
file.lastPathComponent ?? "",
"\(suggestedFilename)",
"filename should be \(suggestedFilename)"
)
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
do {
try fileManager.removeItemAtURL(file)
} catch {
XCTFail("file manager should remove item at URL: \(file)")
}
} else {
XCTFail("file should not be nil")
}
} catch {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "https://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: NSData?
var responseError: ErrorType?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (
completedUnitCount: download.progress.completedUnitCount,
totalUnitCount: download.progress.totalUnitCount
)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
do {
try fileManager.removeItemAtURL(fileURL)
} catch {
XCTFail("file manager should remove item at URL: \(fileURL)")
}
}
func testDownloadRequestWithParameters() {
// Given
let fileURL = randomCachesFileURL
let URLString = "https://httpbin.org/get"
let parameters = ["foo": "bar"]
let destination: Request.DownloadFileDestination = { _, _ in fileURL }
let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, parameters: parameters, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
if let
data = NSData(contentsOfURL: fileURL),
JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
JSON = JSONObject as? [String: AnyObject],
args = JSON["args"] as? [String: String]
{
XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
} else {
XCTFail("args parameter in JSON should not be nil")
}
}
func testDownloadRequestWithHeaders() {
// Given
let fileURL = randomCachesFileURL
let URLString = "https://httpbin.org/get"
let headers = ["Authorization": "123456"]
let destination: Request.DownloadFileDestination = { _, _ in fileURL }
let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, headers: headers, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
if let
data = NSData(contentsOfURL: fileURL),
JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
JSON = JSONObject as? [String: AnyObject],
headers = JSON["headers"] as? [String: String]
{
XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456")
} else {
XCTFail("headers parameter in JSON should not be nil")
}
}
}
// MARK: -
class DownloadResumeDataTestCase: BaseTestCase {
let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
let destination: Request.DownloadFileDestination = {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
}()
func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
download.cancel()
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNil(data, "data should be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNil(download.resumeData, "resume data should be nil")
}
func testThatCancelledDownloadResponseDataMatchesResumeData() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
download.progress { _, _, _ in
download.cancel()
}
download.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNotNil(download.resumeData, "resume data should not be nil")
if let
responseData = data as? NSData,
resumeData = download.resumeData
{
XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
} else {
XCTFail("response data or resume data was unexpectedly nil")
}
}
func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var response: Response<AnyObject, NSError>?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
download.progress { _, _, _ in
download.cancel()
}
download.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isFailure, "result should be failure")
XCTAssertNotNil(response.result.error, "result error should not be nil")
} else {
XCTFail("response should not be nil")
}
XCTAssertNotNil(download.resumeData, "resume data should not be nil")
}
}
| mit | beddf77fd496f50ac2ad84e1e09301db | 38.697168 | 126 | 0.644147 | 5.902494 | false | false | false | false |
OlegKetrar/Tools | Sources/Tools/UIKit/Components/FallableContainerView.swift | 1 | 2129 | //
// FallableContainerView.swift
// ToolsUIKit
//
// Created by Oleg Ketrar on 26/02/2019.
// Copyright © 2019 Oleg Ketrar. All rights reserved.
//
import Foundation
import UIKit
// TODO: rename
// TODO: error register mechanism
public final class FallibleContainerView: UIView {
private var commonErrorView: UIView?
private var errorViews: [String : UIView] = [:]
private let errorContainer: UIView = {
let view = UIView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// MARK: - Overrides
override public init(frame: CGRect) {
super.init(frame: frame)
defaultConfiguring()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultConfiguring()
}
// MARK: - Public
public func registerError(identifier: String, toView view: UIView) {
errorViews[identifier] = view
}
public func registerCommonErrorView(_ view: UIView) {
commonErrorView = view
}
public func showError(identifier: String) {
guard let appropriateView = errorViews[identifier] ?? commonErrorView else {
fatalError("no errorView register")
}
showErrorView(appropriateView)
}
public func showCommonError() {
guard let appropriateView = commonErrorView else {
fatalError("no errorView register")
}
showErrorView(appropriateView)
}
public func showContent() {
errorContainer.isHidden = true
}
deinit {
commonErrorView?.removeFromSuperview()
errorViews.values.forEach { $0.removeFromSuperview() }
}
}
// MARK: - Private
private extension FallibleContainerView {
func showErrorView(_ errorView: UIView) {
errorContainer.subviews.forEach { $0.removeFromSuperview() }
errorContainer.addPinnedSubview(errorView)
errorContainer.isHidden = false
}
func defaultConfiguring() {
addPinnedSubview(errorContainer)
bringSubviewToFront(errorContainer)
showContent()
}
}
| mit | 4e34510e97c8cbeef2f62f180ce7819f | 22.910112 | 84 | 0.654605 | 4.891954 | false | false | false | false |
vimeo/VimeoNetworking | Tests/Shared/Core/JSONEncodingTests.swift | 1 | 2643 | //
// ParameterEncodingTests.swift
// VimeoNetworking
//
// Created by Rogerio de Paula Assis on 9/2/19.
// Copyright © 2019 Vimeo. All rights reserved.
//
import Foundation
import XCTest
@testable import VimeoNetworking
class JSONParameterEncodingTestCase: XCTestCase {
let urlRequest = URLRequest(url: URL(string: "https://example.com/")!)
let encoding = JSONEncoding.default
func testThatQueryAndBodyAreNilForNilParameters() throws {
// Given an encoding request with nil parameters, When
let URLRequest = try encoding.encode(self.urlRequest, with: nil)
// Then
XCTAssertNil(URLRequest.url?.query, "query should be nil")
XCTAssertNil(URLRequest.value(forHTTPHeaderField: "Content-Type"))
XCTAssertNil(URLRequest.httpBody, "HTTPBody should be nil")
}
func testThatNestedParametersCanBeEncoded_And_ContentTypeIsSet() throws {
// Given
let parameters: [String: Any] = [
"foo": "bar",
"baz": ["a", 1, true],
"qux": [
"a": 1,
"b": [2, 2],
"c": [3, 3, 3]
]
]
// When
let URLRequest = try encoding.encode(self.urlRequest, with: parameters)
// Then
XCTAssertNil(URLRequest.url?.query)
XCTAssertNotNil(URLRequest.value(forHTTPHeaderField: "Content-Type"))
XCTAssertEqual(URLRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
XCTAssertNotNil(URLRequest.httpBody)
if let httpBody = URLRequest.httpBody {
let json = try JSONSerialization.jsonObject(with: httpBody, options: .allowFragments)
if let json = json as? NSObject {
XCTAssertEqual(json, parameters as NSObject)
} else {
XCTFail("json should be an NSObject")
}
} else {
XCTFail("json should not be nil")
}
}
func testThatEncodingDoesntOverrideCustomContentType() throws {
// Given
var mutableURLRequest = URLRequest(url: URL(string: "https://example.com/")!)
mutableURLRequest.setValue("application/custom-json-type+json", forHTTPHeaderField: "Content-Type")
let parameters = ["foo": "bar"]
// When
let urlRequest = try encoding.encode(mutableURLRequest, with: parameters)
// Then
XCTAssertNil(urlRequest.url?.query)
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/custom-json-type+json")
}
}
| mit | 425be1c08981d605b641640f20e6c7a7 | 33.763158 | 113 | 0.607116 | 4.910781 | false | true | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Platform/BRAnalyticsEvent.swift | 1 | 1301 | //
// BRAnalyticsEvent.swift
// breadwallet
//
// Created by Ray Vander Veen on 2018-12-12.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
import Foundation
typealias Attributes = [String: String]
enum BRAnalyticsEventName: String {
case sessionId = "sessionId"
case time = "time"
case eventName = "eventName"
case metaData = "metadata"
}
struct BRAnalyticsEvent {
let sessionId: String
let time: TimeInterval
let eventName: String
let attributes: Attributes
var dictionary: [String: Any] {
var result: [String: Any] = [String: Any]()
result[BRAnalyticsEventName.sessionId.rawValue] = sessionId
result[BRAnalyticsEventName.time.rawValue] = Int(time)
result[BRAnalyticsEventName.eventName.rawValue] = eventName
if !attributes.keys.isEmpty {
var metaData: [[String: String]] = [[String: String]]()
for key in attributes.keys {
if let value = attributes[key] {
metaData.append(["key": key, "value": value])
}
}
result[BRAnalyticsEventName.metaData.rawValue] = metaData
}
return result
}
}
| mit | 0db6e0dc18444253a66f8fb330e08757 | 26.659574 | 89 | 0.582308 | 4.710145 | false | false | false | false |
brentdax/swift | test/SILGen/toplevel.swift | 1 | 3856 | // RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -enable-sil-ownership %s | %FileCheck %s
func markUsed<T>(_ t: T) {}
func trap() -> Never {
fatalError()
}
// CHECK-LABEL: sil @main
// CHECK: bb0({{%.*}} : @trivial $Int32, {{%.*}} : @trivial $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>):
// -- initialize x
// CHECK: alloc_global @$s8toplevel1xSiv
// CHECK: [[X:%[0-9]+]] = global_addr @$s8toplevel1xSivp : $*Int
// CHECK: integer_literal $Builtin.Int2048, 999
// CHECK: store {{.*}} to [trivial] [[X]]
var x = 999
func print_x() {
markUsed(x)
}
// -- assign x
// CHECK: integer_literal $Builtin.Int2048, 0
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X]] : $*Int
// CHECK: assign {{.*}} to [[WRITE]]
// CHECK: [[PRINT_X:%[0-9]+]] = function_ref @$s8toplevel7print_xyyF :
// CHECK: apply [[PRINT_X]]
x = 0
print_x()
// <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground
// CHECK: alloc_global @$s8toplevel5countSiv
// CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @$s8toplevel5countSivp : $*Int
// CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int
let count: Int
// CHECK: cond_br
if x == 5 {
count = 0
// CHECK: assign {{.*}} to [[COUNTMUI]]
// CHECK: br [[MERGE:bb[0-9]+]]
} else {
count = 10
// CHECK: assign {{.*}} to [[COUNTMUI]]
// CHECK: br [[MERGE]]
}
// CHECK: [[MERGE]]:
// CHECK: load [trivial] [[COUNTMUI]]
markUsed(count)
var y : Int
func print_y() {
markUsed(y)
}
// -- assign y
// CHECK: alloc_global @$s8toplevel1ySiv
// CHECK: [[Y1:%[0-9]+]] = global_addr @$s8toplevel1ySivp : $*Int
// CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[Y]]
// CHECK: assign {{.*}} to [[WRITE]]
// CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @$s8toplevel7print_yyyF
y = 1
print_y()
// -- treat 'guard' vars as locals
// CHECK-LABEL: function_ref toplevel.A.__allocating_init
// CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt.1: [[SOME_CASE:.+]], case #Optional.none!
// CHECK: [[SOME_CASE]]([[VALUE:%.+]] : @owned $A):
// CHECK: store [[VALUE]] to [init] [[BOX:%.+]] : $*A
// CHECK-NOT: destroy_value
// CHECK: [[SINK:%.+]] = function_ref @$s8toplevel8markUsedyyxlF
// CHECK-NOT: destroy_value
// CHECK: apply [[SINK]]<A>({{%.+}})
class A {}
guard var a = Optional(A()) else { trap() }
markUsed(a)
// CHECK: alloc_global @$s8toplevel21NotInitializedIntegerSiv
// CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @$s8toplevel21NotInitializedIntegerSiv
// CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int
// CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int
// <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables
let NotInitializedInteger : Int
func fooUsesUninitializedValue() {
_ = NotInitializedInteger
}
fooUsesUninitializedValue()
NotInitializedInteger = 10
fooUsesUninitializedValue()
// Test initialization of variables captured by top-level defer.
// CHECK: alloc_global @$s8toplevel9uninitVarSiv
// CHECK-NEXT: [[UNINIADDR:%[0-9]+]] = global_addr @$s8toplevel9uninitVarSiv
// CHECK-NEXT: [[UNINIMUI:%[0-9]+]] = mark_uninitialized [var] [[UNINIADDR]] : $*Int
// CHECK-NEXT: mark_function_escape [[UNINIMUI]] : $*Int
var uninitVar: Int
defer {
print(uninitVar)
}
// CHECK: [[RET:%[0-9]+]] = struct $Int32
// CHECK: return [[RET]]
// CHECK-LABEL: sil hidden @$s8toplevel7print_xyyF
// CHECK-LABEL: sil hidden @$s8toplevel7print_yyyF
// CHECK: sil hidden @$s8toplevel13testGlobalCSESiyF
// CHECK-NOT: global_addr
// CHECK: %0 = global_addr @$s8toplevel1xSivp : $*Int
// CHECK-NOT: global_addr
// CHECK: return
func testGlobalCSE() -> Int {
// We should only emit one global_addr in this function.
return x + x
}
| apache-2.0 | 4dd00d23cfcad93a6b8f257052601b46 | 27.145985 | 121 | 0.641598 | 3.127332 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/User/RealmHair.swift | 1 | 864 | //
// RealmHair.swift
// Habitica Database
//
// Created by Phillip Thelen on 20.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmHair: Object, HairProtocol {
var color: String?
var bangs: Int = 0
var base: Int = 0
var beard: Int = 0
var mustache: Int = 0
var flower: Int = 0
@objc dynamic var id: String?
override static func primaryKey() -> String {
return "id"
}
convenience init(userID: String?, protocolObject: HairProtocol) {
self.init()
self.id = userID
color = protocolObject.color
bangs = protocolObject.bangs
base = protocolObject.base
beard = protocolObject.beard
mustache = protocolObject.mustache
flower = protocolObject.flower
}
}
| gpl-3.0 | 211757a53f5ae4b361ec3d96cad18079 | 22.972222 | 69 | 0.636153 | 4.209756 | false | false | false | false |
younatics/MediaBrowser | MediaBrowser/MediaZoomingScrollView.swift | 1 | 17028 | //
// MediaZoomingScrollView.swift
// MediaBrowser
//
// Created by Seungyoun Yi on 2017. 9. 6..
// Copyright © 2017년 Seungyoun Yi. All rights reserved.
//
import UIKit
import UICircularProgressRing
class MediaZoomingScrollView: UIScrollView, UIScrollViewDelegate, TapDetectingImageViewDelegate, TapDetectingViewDelegate {
var index = 0
var media: Media?
weak var captionView: MediaCaptionView?
weak var selectedButton: UIButton?
weak var playButton: UIButton?
var loadingIndicator = UICircularProgressRing(frame: CGRect(x: 140, y: 30, width: 40, height: 40))
weak var mediaBrowser: MediaBrowser!
var tapView = MediaTapDetectingView(frame: .zero) // for background taps
var photoImageView = MediaTapDetectingImageView(frame: .zero)
var loadingError: UIImageView?
init(mediaBrowser: MediaBrowser) {
super.init(frame: .zero)
// Setup
index = Int.max
self.mediaBrowser = mediaBrowser
// Tap view for background
tapView = MediaTapDetectingView(frame: bounds)
tapView.tapDelegate = self
tapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tapView.backgroundColor = .clear
addSubview(tapView)
// Image view
photoImageView.tapDelegate = self
photoImageView.contentMode = .center
photoImageView.backgroundColor = .clear
addSubview(photoImageView)
// Loading indicator
loadingIndicator.isUserInteractionEnabled = false
loadingIndicator.autoresizingMask =
[.flexibleLeftMargin, .flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin]
loadingIndicator.style = .ontop
loadingIndicator.innerRingColor = UIColor.white
loadingIndicator.outerRingColor = UIColor.gray
loadingIndicator.innerRingWidth = 1
loadingIndicator.outerRingWidth = 1
addSubview(loadingIndicator)
// Listen progress notifications
NotificationCenter.default.addObserver(
self,
selector: #selector(setProgressFromNotification),
name: NSNotification.Name(rawValue: MEDIA_PROGRESS_NOTIFICATION),
object: nil)
// Setup
delegate = self
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
decelerationRate = UIScrollView.DecelerationRate.fast
autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
media?.cancelAnyLoading()
NotificationCenter.default.removeObserver(self)
}
func prepareForReuse() {
hideImageFailure()
// photo = nil
captionView = nil
selectedButton = nil
playButton = nil
photoImageView.isHidden = false
if let placeholder = self.mediaBrowser.placeholderImage, placeholder.isAppliedForAll || (!placeholder.isAppliedForAll && self.index == self.mediaBrowser.currentIndex) {
photoImageView.image = self.mediaBrowser.placeholderImage?.image
} else {
photoImageView.image = nil
}
photoImageView.alpha = 0.8
index = Int.max
}
func displayingVideo() -> Bool {
return photo?.isVideo ?? false
}
public override var backgroundColor: UIColor? {
set(color) {
tapView.backgroundColor = color
super.backgroundColor = color
}
get {
return super.backgroundColor
}
}
var imageHidden: Bool {
set(hidden) {
photoImageView.isHidden = hidden
}
get {
return photoImageView.isHidden
}
}
//MARK: - Image
var photo: Media? {
set(p) {
// Cancel any loading on old photo
if media != nil && p == nil {
media!.cancelAnyLoading()
}
media = p
if let image = mediaBrowser.image(for: media), image !== mediaBrowser.placeholderImage?.image {
self.displayImage()
} else {
// Will be loading so show loading
self.showLoadingIndicator()
}
}
get {
return media
}
}
// Get and display image
func displayImage() {
if media != nil && (photoImageView.image == nil || photoImageView.image === self.mediaBrowser.placeholderImage?.image) {
// Reset
maximumZoomScale = 1.0
minimumZoomScale = 1.0
zoomScale = 1.0
contentSize = CGSize.zero
// Get image from browser as it handles ordering of fetching
if let img = mediaBrowser.image(for: photo), img !== mediaBrowser.placeholderImage?.image {
// Hide indicator
hideLoadingIndicator()
// Set image
photoImageView.alpha = 1.0
photoImageView.image = img
photoImageView.isHidden = false
// Setup photo frame
let photoImageViewFrame = CGRect(origin: CGPoint.zero, size: img.size)
photoImageView.frame = photoImageViewFrame
contentSize = photoImageViewFrame.size
// Set zoom to minimum zoom
setMaxMinZoomScalesForCurrentBounds()
} else {
// Show image failure
displayImageFailure()
}
setNeedsLayout()
}
}
// Image failed so just show grey!
func displayImageFailure() {
hideLoadingIndicator()
if let placeholder = self.mediaBrowser.placeholderImage, placeholder.isAppliedForAll || (!placeholder.isAppliedForAll && self.index == self.mediaBrowser.currentIndex) {
photoImageView.image = self.mediaBrowser.placeholderImage?.image
} else {
photoImageView.image = nil
}
photoImageView.alpha = 0.8
// Show if image is not empty
if let p = photo {
if p.emptyImage {
if nil == loadingError {
loadingError = UIImageView()
loadingError!.image = UIImage.imageForResourcePath(
name: "ImageError",
inBundle: Bundle(for: MediaZoomingScrollView.self))
loadingError!.isUserInteractionEnabled = false
loadingError!.autoresizingMask =
[.flexibleLeftMargin, .flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin]
loadingError!.sizeToFit()
addSubview(loadingError!)
}
loadingError!.frame = CGRect(
x: floorcgf(x: (bounds.size.width - loadingError!.frame.size.width) / 2.0),
y: floorcgf(x: (bounds.size.height - loadingError!.frame.size.height) / 2.0),
width: loadingError!.frame.size.width,
height: loadingError!.frame.size.height)
}
}
}
private func hideImageFailure() {
if let e = loadingError {
e.removeFromSuperview()
loadingError = nil
}
}
//MARK: - Loading Progress
@objc public func setProgressFromNotification(notification: NSNotification) {
DispatchQueue.main.async() {
let dict = notification.object as! [String : AnyObject]
if let photoWithProgress = dict["photo"] as? Media, let progress = dict["progress"] as? CGFloat, let p = self.photo, photoWithProgress.equals(photo: p) {
self.loadingIndicator.startProgress(to: progress * 100, duration: 0.1)
}
}
}
private func hideLoadingIndicator() {
loadingIndicator.isHidden = true
}
private func showLoadingIndicator() {
zoomScale = 0.0
minimumZoomScale = 0.0
maximumZoomScale = 0.0
loadingIndicator.startProgress(to: 0.0, duration: 0)
loadingIndicator.isHidden = false
hideImageFailure()
}
//MARK: - Setup
private func initialZoomScaleWithMinScale() -> CGFloat {
var zoomScale = minimumZoomScale
if let pb = mediaBrowser,let image = photoImageView.image, pb.zoomPhotosToFill {
// Zoom image to fill if the aspect ratios are fairly similar
let boundsSize = self.bounds.size
let imageSize = image.size
let boundsAR = boundsSize.width / boundsSize.height
let imageAR = imageSize.width / imageSize.height
let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise
let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise
// Zooms standard portrait images on a 3.5in screen but not on a 4in screen.
if (abs(boundsAR - imageAR) < 0.17) {
zoomScale = max(xScale, yScale)
// Ensure we don't zoom in or out too far, just in case
zoomScale = min(max(minimumZoomScale, zoomScale), maximumZoomScale)
}
}
return zoomScale
}
func setMaxMinZoomScalesForCurrentBounds() {
// Reset
maximumZoomScale = 1.0
minimumZoomScale = 1.0
zoomScale = 1.0
guard let image = photoImageView.image else { return }
// Reset position
photoImageView.frame = CGRect(x: 0, y: 0, width: photoImageView.frame.size.width, height: photoImageView.frame.size.height)
// Sizes
let boundsSize = self.bounds.size
let imageSize = image.size
// Calculate Min
let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise
let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise
var minScale:CGFloat = min(xScale, yScale) // use minimum of these to allow the image to become fully visible
// Calculate Max
var maxScale: CGFloat = 3.0
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
// Let them go a bit bigger on a bigger screen!
maxScale = 4.0
}
// Image is smaller than screen so no zooming!
if xScale >= 1.0 && yScale >= 1.0 {
minScale = 1.0
}
// Set min/max zoom
maximumZoomScale = maxScale
minimumZoomScale = minScale
// Initial zoom
zoomScale = initialZoomScaleWithMinScale()
// If we're zooming to fill then centralise
if zoomScale != minScale {
// Centralise
contentOffset = CGPoint(x: (imageSize.width * zoomScale - boundsSize.width) / 2.0, y: (imageSize.height * zoomScale - boundsSize.height) / 2.0)
}
// Disable scrolling initially until the first pinch to fix issues with swiping on an initally zoomed in photo
isScrollEnabled = false
// If it's a video then disable zooming
if displayingVideo() {
maximumZoomScale = zoomScale
minimumZoomScale = zoomScale
}
// Layout
setNeedsLayout()
}
//MARK: - Layout
override func layoutSubviews() {
// Update tap view frame
tapView.frame = bounds
// Position indicators (centre does not seem to work!)
if !loadingIndicator.isHidden {
loadingIndicator.frame = CGRect(
x: floorcgf(x: (bounds.size.width - loadingIndicator.frame.size.width) / 2.0),
y: floorcgf(x: (bounds.size.height - loadingIndicator.frame.size.height) / 2.0),
width: loadingIndicator.frame.size.width,
height: loadingIndicator.frame.size.height)
}
if let le = loadingError {
le.frame = CGRect(
x: floorcgf(x: (bounds.size.width - le.frame.size.width) / 2.0),
y: floorcgf(x: (bounds.size.height - le.frame.size.height) / 2.0),
width: le.frame.size.width,
height: le.frame.size.height)
}
// Super
super.layoutSubviews()
self.alignCenterMedia()
}
func alignCenterMedia() {
// Center the image as it becomes smaller than the size of the screen
let boundsSize = bounds.size
var frameToCenter = photoImageView.frame
// Horizontally
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = floorcgf(x: (boundsSize.width - frameToCenter.size.width) / 2.0)
} else {
frameToCenter.origin.x = 0.0
}
// Vertically
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = floorcgf(x: (boundsSize.height - frameToCenter.size.height) / 2.0)
} else {
frameToCenter.origin.y = 0.0
}
// Center
if !photoImageView.frame.equalTo(frameToCenter) {
photoImageView.frame = frameToCenter
}
}
//MARK: - UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return photoImageView
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
mediaBrowser.cancelControlHiding()
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
isScrollEnabled = true // reset
mediaBrowser.cancelControlHiding()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
mediaBrowser.hideControlsAfterDelay()
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
setNeedsLayout()
layoutIfNeeded()
}
//MARK: - Tap Detection
func handleSingleTap(touchPoint: CGPoint) {
mediaBrowser.perform(#selector(MediaBrowser.toggleControls), with: nil, afterDelay: 0.2)
}
func handleDoubleTap(touchPoint: CGPoint) {
// Dont double tap to zoom if showing a video
if displayingVideo() {
return
}
// Cancel any single tap handling
NSObject.cancelPreviousPerformRequests(withTarget: mediaBrowser as Any)
// Zoom
if zoomScale != minimumZoomScale && zoomScale != initialZoomScaleWithMinScale() {
// Zoom out
setZoomScale(minimumZoomScale, animated: true)
} else {
// Zoom in to twice the size
let newZoomScale = ((maximumZoomScale + minimumZoomScale) / 2.0)
let xsize = bounds.size.width / newZoomScale
let ysize = bounds.size.height / newZoomScale
zoom(to: CGRect(x: touchPoint.x - xsize / 2.0, y: touchPoint.y - ysize / 2.0, width: xsize, height: ysize), animated: true)
}
// Delay controls
mediaBrowser.hideControlsAfterDelay()
}
// Image View
func singleTapDetectedInImageView(view: UIImageView, touch: UITouch) {
handleSingleTap(touchPoint: touch.location(in: view))
}
func doubleTapDetectedInImageView(view: UIImageView, touch: UITouch) {
handleDoubleTap(touchPoint: touch.location(in: view))
}
func tripleTapDetectedInImageView(view: UIImageView, touch: UITouch) {
}
// Background View
func singleTapDetectedInView(view: UIView, touch: UITouch) {
// Translate touch location to image view location
var touchX = touch.location(in: view).x
var touchY = touch.location(in: view).y
touchX *= 1.0 / self.zoomScale
touchY *= 1.0 / self.zoomScale
touchX += self.contentOffset.x
touchY += self.contentOffset.y
handleSingleTap(touchPoint: CGPoint(x: touchX, y: touchY))
}
func doubleTapDetectedInView(view: UIView, touch: UITouch) {
// Translate touch location to image view location
var touchX = touch.location(in: view).x
var touchY = touch.location(in: view).y
touchX *= 1.0 / self.zoomScale
touchY *= 1.0 / self.zoomScale
touchX += self.contentOffset.x
touchY += self.contentOffset.y
handleDoubleTap(touchPoint: CGPoint(x: touchX, y: touchY))
}
func tripleTapDetectedInView(view: UIView, touch: UITouch) {
}
}
| mit | 60eb5fe0985e55881f3c5002acbd6cbd | 34.46875 | 176 | 0.586608 | 5.449744 | false | false | false | false |
triestpa/BlueSky | BlueSky/AppDelegate.swift | 1 | 3348 | //
// AppDelegate.swift
// BlueSky
//
// Created by Patrick on 11/18/14.
// Copyright (c) 2014 Patrick Triest. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? WeatherViewController {
if topAsDetailController.weatherLocation == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
| gpl-2.0 | 08e359f8c89f7b2bbaf3ca1d2db6dfb2 | 52.142857 | 285 | 0.751493 | 6.257944 | false | false | false | false |
matsuda/MuddlerKit | MuddlerKit/UIViewExtensiont.swift | 1 | 1028 | //
// UIViewExtensiont.swift
// MuddlerKit
//
// Created by Kosuke Matsuda on 2016/12/29.
// Copyright © 2016年 Kosuke Matsuda. All rights reserved.
//
import UIKit
extension Extension where Base: UIView {
// http://stackoverflow.com/a/36406508/226791
public var firstResponder: UIResponder? {
if base.isFirstResponder { return base }
for subview in base.subviews {
if let responder = subview.mk.firstResponder {
return responder
}
}
return nil
}
}
extension Extension where Base: UIView {
public func detectView<T: UIView>(_ type: T.Type) -> T? {
var target: T?
var view: UIView? = base
while let parent = view?.superview {
if let c = parent as? T {
target = c
break
}
view = parent
}
return target
}
public func detectTableViewCell() -> UITableViewCell? {
return detectView(UITableViewCell.self)
}
}
| mit | 893f454bd787dd88e3413d21c89daefb | 24 | 61 | 0.574634 | 4.380342 | false | false | false | false |
adamnemecek/AudioKit | Sources/AudioKit/Audio Files/AVAudioPCMBuffer+Utilities.swift | 1 | 7885 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CryptoKit
extension AVAudioPCMBuffer {
/// Hash useful for testing
public var md5: String {
var sampleData = Data()
if let floatChannelData = self.floatChannelData {
for frame in 0 ..< self.frameCapacity {
for channel in 0 ..< self.format.channelCount {
let sample = floatChannelData[Int(channel)][Int(frame)]
withUnsafePointer(to: sample) { ptr in
sampleData.append(UnsafeBufferPointer(start: ptr, count: 1))
}
}
}
}
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
let digest = Insecure.MD5.hash(data: sampleData)
return digest.map { String(format: "%02hhx", $0) }.joined()
} else {
// Fallback on earlier versions
return "Oh well, old version"
}
}
public var isSilent: Bool {
if let floatChannelData = self.floatChannelData {
for channel in 0 ..< self.format.channelCount {
for frame in 0 ..< self.frameLength {
if floatChannelData[Int(channel)][Int(frame)] != 0.0 {
return false
}
}
}
}
return true
}
/// Add to an existing buffer
///
/// - Parameter buffer: Buffer to append
public func append(_ buffer: AVAudioPCMBuffer) {
self.append(buffer, startingFrame: 0, frameCount: buffer.frameLength)
}
/// Add to an existing buffer with specific starting frame and size
/// - Parameters:
/// - buffer: Buffer to append
/// - startingFrame: Starting frame location
/// - frameCount: Number of frames to append
public func append(_ buffer: AVAudioPCMBuffer,
startingFrame: AVAudioFramePosition,
frameCount: AVAudioFrameCount) {
precondition(format == buffer.format,
"Format mismatch")
precondition(startingFrame + AVAudioFramePosition(frameCount) <= AVAudioFramePosition(buffer.frameLength),
"Insufficient audio in buffer")
precondition(frameLength + frameCount <= frameCapacity,
"Insufficient space in buffer")
let dst1 = floatChannelData![0]
let src1 = buffer.floatChannelData![0]
memcpy(dst1.advanced(by: stride * Int(frameLength)),
src1.advanced(by: stride * Int(startingFrame)),
Int(frameCount) * stride * MemoryLayout<Float>.size)
let dst2 = floatChannelData![1]
let src2 = buffer.floatChannelData![1]
memcpy(dst2.advanced(by: stride * Int(frameLength)),
src2.advanced(by: stride * Int(startingFrame)),
Int(frameCount) * stride * MemoryLayout<Float>.size)
frameLength += frameCount
}
/// Copies data from another PCM buffer. Will copy to the end of the buffer (frameLength), and
/// increment frameLength. Will not exceed frameCapacity.
///
/// - Parameter buffer: The source buffer that data will be copied from.
/// - Parameter readOffset: The offset into the source buffer to read from.
/// - Parameter frames: The number of frames to copy from the source buffer.
/// - Returns: The number of frames copied.
@discardableResult public func copy(from buffer: AVAudioPCMBuffer,
readOffset: AVAudioFrameCount = 0,
frames: AVAudioFrameCount = 0) -> AVAudioFrameCount {
let remainingCapacity = frameCapacity - frameLength
if remainingCapacity == 0 {
Log("AVAudioBuffer copy(from) - no capacity!")
return 0
}
if format != buffer.format {
Log("AVAudioBuffer copy(from) - formats must match!")
return 0
}
let totalFrames = Int(min(min(frames == 0 ? buffer.frameLength : frames, remainingCapacity),
buffer.frameLength - readOffset))
if totalFrames <= 0 {
Log("AVAudioBuffer copy(from) - No frames to copy!")
return 0
}
let frameSize = Int(format.streamDescription.pointee.mBytesPerFrame)
if let src = buffer.floatChannelData,
let dst = floatChannelData {
for channel in 0 ..< Int(format.channelCount) {
memcpy(dst[channel] + Int(frameLength), src[channel] + Int(readOffset), totalFrames * frameSize)
}
} else if let src = buffer.int16ChannelData,
let dst = int16ChannelData {
for channel in 0 ..< Int(format.channelCount) {
memcpy(dst[channel] + Int(frameLength), src[channel] + Int(readOffset), totalFrames * frameSize)
}
} else if let src = buffer.int32ChannelData,
let dst = int32ChannelData {
for channel in 0 ..< Int(format.channelCount) {
memcpy(dst[channel] + Int(frameLength), src[channel] + Int(readOffset), totalFrames * frameSize)
}
} else {
return 0
}
frameLength += AVAudioFrameCount(totalFrames)
return AVAudioFrameCount(totalFrames)
}
/// Copy from a certain point tp the end of the buffer
/// - Parameter startSample: Point to start copy from
/// - Returns: an AVAudioPCMBuffer copied from a sample offset to the end of the buffer.
public func copyFrom(startSample: AVAudioFrameCount) -> AVAudioPCMBuffer? {
guard startSample < frameLength,
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameLength - startSample) else {
return nil
}
let framesCopied = buffer.copy(from: self, readOffset: startSample)
return framesCopied > 0 ? buffer : nil
}
/// Copy from the beginner of a buffer to a certain number of frames
/// - Parameter count: Length of frames to copy
/// - Returns: an AVAudioPCMBuffer copied from the start of the buffer to the specified endSample.
public func copyTo(count: AVAudioFrameCount) -> AVAudioPCMBuffer? {
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: count) else {
return nil
}
let framesCopied = buffer.copy(from: self, readOffset: 0, frames: min(count, frameLength))
return framesCopied > 0 ? buffer : nil
}
/// Extract a portion of the buffer
///
/// - Parameter startTime: The time of the in point of the extraction
/// - Parameter endTime: The time of the out point
/// - Returns: A new edited AVAudioPCMBuffer
public func extract(from startTime: TimeInterval,
to endTime: TimeInterval) -> AVAudioPCMBuffer? {
let sampleRate = format.sampleRate
let startSample = AVAudioFrameCount(startTime * sampleRate)
var endSample = AVAudioFrameCount(endTime * sampleRate)
if endSample == 0 {
endSample = frameLength
}
let frameCapacity = endSample - startSample
guard frameCapacity > 0 else {
Log("startSample must be before endSample", type: .error)
return nil
}
guard let editedBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else {
Log("Failed to create edited buffer", type: .error)
return nil
}
guard editedBuffer.copy(from: self, readOffset: startSample, frames: frameCapacity) > 0 else {
Log("Failed to write to edited buffer", type: .error)
return nil
}
return editedBuffer
}
}
| mit | af2064ed561c621c97ad3796a2bc56f9 | 39.229592 | 114 | 0.596449 | 5.235724 | false | false | false | false |
modocache/swift | test/IRGen/objc_class_export.swift | 3 | 5632 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// CHECK: %swift.refcounted = type
// CHECK: [[HOOZIT:%C17objc_class_export6Hoozit]] = type <{ [[REF:%swift.refcounted]] }>
// CHECK: [[FOO:%C17objc_class_export3Foo]] = type <{ [[REF]], %Si }>
// CHECK: [[INT:%Si]] = type <{ i64 }>
// CHECK: [[NSRECT:%VSC6NSRect]] = type <{ %VSC7NSPoint, %VSC6NSSize }>
// CHECK: [[NSPOINT:%VSC7NSPoint]] = type <{ %Sd, %Sd }>
// CHECK: [[DOUBLE:%Sd]] = type <{ double }>
// CHECK: [[NSSIZE:%VSC6NSSize]] = type <{ %Sd, %Sd }>
// CHECK: [[OBJC:%objc_object]] = type opaque
// CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class {
// CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject",
// CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject",
// CHECK: %swift.opaque* @_objc_empty_cache,
// CHECK: %swift.opaque* null,
// CHECK: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64)
// CHECK: }
// CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00"
// CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK: i32 129,
// CHECK: i32 40,
// CHECK: i32 40,
// CHECK: i32 0,
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK: @_CLASS_METHODS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: i8* null,
// CHECK: i8* null,
// CHECK: i8* null
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK: i32 128,
// CHECK: i32 16,
// CHECK: i32 24,
// CHECK: i32 0,
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: @_IVARS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: _PROPERTIES__TtC17objc_class_export3Foo
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_TMfC17objc_class_export3Foo = internal global <{{.*i64}} }> <{
// CHECK: void ([[FOO]]*)* @_TFC17objc_class_export3FooD,
// CHECK: i8** @_TWVBO,
// CHECK: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64),
// CHECK: %objc_class* @"OBJC_CLASS_$_SwiftObject",
// CHECK: %swift.opaque* @_objc_empty_cache,
// CHECK: %swift.opaque* null,
// CHECK: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1),
// CHECK: [[FOO]]* (%swift.type*)* @_TZFC17objc_class_export3Foo6createfT_S0_,
// CHECK: void (%VSC6NSRect*, [[FOO]]*)* @_TFC17objc_class_export3Foo10drawInRectfT5dirtyVSC6NSRect_T_
// CHECK: }>, section "__DATA,__objc_data, regular"
// -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of
// Foo.
// CHECK: @_TMC17objc_class_export3Foo = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @_TMfC17objc_class_export3Foo, i32 0, i32 2) to %swift.type*)
// CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = alias %swift.type, %swift.type* @_TMC17objc_class_export3Foo
import gizmo
class Hoozit {}
struct BigStructWithNativeObjects {
var x, y, w : Double
var h : Hoozit
}
@objc class Foo {
var x = 0
class func create() -> Foo {
return Foo()
}
func drawInRect(dirty dirty: NSRect) {
}
// CHECK: define internal void @_TToFC17objc_class_export3Foo10drawInRectfT5dirtyVSC6NSRect_T_([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]*
// CHECK: call void @_TFC17objc_class_export3Foo10drawInRectfT5dirtyVSC6NSRect_T_(%VSC6NSRect* {{.*}}, [[FOO]]* [[CAST]])
// CHECK: }
func bounds() -> NSRect {
return NSRect(origin: NSPoint(x: 0, y: 0),
size: NSSize(width: 0, height: 0))
}
// CHECK: define internal void @_TToFC17objc_class_export3Foo6boundsfT_VSC6NSRect([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]*
// CHECK: call void @_TFC17objc_class_export3Foo6boundsfT_VSC6NSRect([[NSRECT]]* noalias nocapture sret {{.*}}, [[FOO]]* [[CAST]])
func convertRectToBacking(r r: NSRect) -> NSRect {
return r
}
// CHECK: define internal void @_TToFC17objc_class_export3Foo20convertRectToBackingfT1rVSC6NSRect_S1_([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]*
// CHECK: call void @_TFC17objc_class_export3Foo20convertRectToBackingfT1rVSC6NSRect_S1_([[NSRECT]]* noalias nocapture sret {{.*}}, %VSC6NSRect* {{.*}}, [[FOO]]* [[CAST]])
func doStuffToSwiftSlice(f f: [Int]) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @_TToFC17objc_class_export3Foo19doStuffToSwiftSlicefS_FT1fGSaSi__T_
func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStructfS_FT1fV17objc_class_export27BigStructWithNativeObjects_T_
init() { }
}
| apache-2.0 | 57cc39bfa7ac9cd953603501ec7df163 | 47.136752 | 211 | 0.638139 | 3.065868 | false | false | false | false |
zehrer/SOGraphDB | Sources/SOGraphDB_old/Stores_OLD/ObjectDataStore.swift | 1 | 3746 | //
// ObjectDataStore.swift
// SOGraphDB
//
// Created by Stephan Zehrer on 17.06.14.
// Copyright (c) 2014 Stephan Zehrer. All rights reserved.
//
import Foundation
struct ObjectStoreHeader : DataStoreHeader {
var used: Bool = true;
}
public class ObjectDataStore<O: Coding> : DataStore<ObjectStoreHeader,O.DataType> {
let cache = NSCache() //SOTypedCache<O>()
//---------------------------------------------------------------------------------------------------------
//MARK: DataStore
//---------------------------------------------------------------------------------------------------------
public override init(url: NSURL) {
super.init(url: url)
}
// subclasses should overide this method
// Create a block with the ID:0
// ID 0 is not allowd to use in the store because
override func initStore() {
registerBlock()
// store SampleData as ID:0 in the file
// ID:0 is a reserved ID and should not be availabled for public access
var header = ObjectStoreHeader(used: false)
self.writeHeader(header)
var sampleData = O()
sampleData.uid = 0
self.writeData(sampleData.data)
}
//---------------------------------------------------------------------------------------------------------
//MARK: ObjectDataStore
//---------------------------------------------------------------------------------------------------------
public func registerObject(aObj: O) -> UID? {
var result: UID? = nil
if aObj.uid == nil {
// only NEW object have a nil uid
var pos = self.registerBlock()
result = self.calculateID(pos)
aObj.uid = result
self.cache.setObject(aObj, forKey: result!)
}
return result;
}
public func createObject() -> O {
var result = O()
self.addObject(result)
return result
}
public func addObject(aObj: O) -> UID {
var pos = registerBlock()
var uid = calculateID(pos)
self.writeBlock(aObj.data, atPos: pos)
aObj.uid = uid
aObj.dirty = false
cache.setObject(aObj, forKey: uid)
return uid
}
public func readObject(aID: UID) -> O! {
var result :O! = cache.objectForKey(aID) as! O!
if result == nil {
// not in cache
var data = self[aID] // read data
if (data != nil) {
result = O(data: data)
result.uid = aID
//var key = NSNumber(long: uid)
self.cache.setObject(result, forKey: aID)
}
}
return result
}
public func updateObject(aObj: O) {
if aObj.dirty && aObj.uid != nil {
self[aObj.uid!] = aObj.data
aObj.dirty = false
}
}
public func deleteObject(aObj: O) {
if aObj.uid != nil {
cache.removeObjectForKey(aObj.uid!)
self.deleteBlock(aObj.uid!)
aObj.uid = nil;
}
}
//---------------------------------------------------------------------------------------------------------
//MARK: Cache Controll
//---------------------------------------------------------------------------------------------------------
public func removeAllObjectsForCache() {
cache.removeAllObjects()
}
} | mit | 2ad29ea571e9797e1a1a78757ce21969 | 25.202797 | 111 | 0.408169 | 5.599402 | false | false | false | false |
jmp9c/number-chords | Nashville Chords/Nashville Chords/Transposer.swift | 1 | 1024 | //
// Transposer.swift
// Nashville Chords
//
// Created by John Peden on 9/20/17.
// Copyright © 2017 John Peden. All rights reserved.
//
import UIKit
// All keys
enum Key {
case aflat, anat, asharp
case bflat, bnat
case cnat, csharp
case dflat, dnat, dsharp
case eflat, enat
case fnat, fsharp
case gflat, gnat, gsharp
}
class Transposer: NSObject {
var key: Key
var chordBook: [Key: [String: String]] = [
.cnat: ["C": "1",
"D": "2",
"E": "3",
"F": "4",
"G": "5",
"A": "6",
"B": "7"]
]
init(key: Key) {
self.key = key
}
}
// MARK: - Methods
extension Transposer {
func parse(chords: String) -> [String] {
var result: [String] = []
// empty string provided
if chords == "" {
return []
}
result = chords.characters.split(separator: " ").map(String.init)
return result
}
}
| mit | b06ae384c1eef189e92bb51160a01afa | 16.947368 | 73 | 0.481916 | 3.398671 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/Models/List.swift | 1 | 3501 | import Foundation
import CoreData
import PersistedPropertyWrapper
@objc(List)
class List: NSManagedObject {
@NSManaged var name: String
@NSManaged var order: BookSort
@NSManaged var sort: Int32
@NSManaged private(set) var custom: Bool
/** The item which hold a book-index pair for each book in this list */
@NSManaged private(set) var items: Set<ListItem>
/** The ordered array of books within this list. If just a count is required, use items.count instead. */
var books: [Book] {
items.sorted(byAscending: \.sort).map(\.book)
}
convenience init(context: NSManagedObjectContext, name: String) {
self.init(context: context)
self.name = name
if let maxSort = List.maxSort(fromContext: context) {
self.sort = maxSort + 1
}
}
func removeBook(_ book: Book) {
for item in items where item.book == book {
item.delete()
}
}
func removeBooks(_ books: Set<Book>) {
for item in items where books.contains(item.book) {
item.delete()
}
}
func addBooks(_ books: [Book]) {
guard let context = managedObjectContext else {
preconditionFailure("Attempted to add books to a List which was not in a context")
}
// Grab the largest current sort value (if we have any books) to use in our next ListItem sort index
var index: Int32
if !items.isEmpty, let maxSort = context.getMaximum(sortValueKeyPath: \ListItem.sort) {
index = maxSort + 1
} else {
index = 0
}
// Create some ordered ListItems mapping to the provided books. Create a set of all the existing books so we can
// efficiently check whether any of the books are already in this list, and skip them if so.
let existingBooks = Set(self.books)
for book in books {
guard !existingBooks.contains(book) else { continue }
_ = ListItem(context: context, book: book, list: self, sort: index)
index += 1
}
}
class func names(fromContext context: NSManagedObjectContext) -> [String] {
let fetchRequest = NSManagedObject.fetchRequest(List.self)
fetchRequest.sortDescriptors = [NSSortDescriptor(\List.sort), NSSortDescriptor(\List.name)]
fetchRequest.returnsObjectsAsFaults = false
return (try! context.fetch(fetchRequest)).map { $0.name }
}
class func maxSort(fromContext context: NSManagedObjectContext) -> Int32? {
return context.getMaximum(sortValueKeyPath: \List.sort)
}
class func getOrCreate(inContext context: NSManagedObjectContext, withName name: String) -> List {
let listFetchRequest = NSManagedObject.fetchRequest(List.self, limit: 1)
listFetchRequest.predicate = NSPredicate(format: "%K == %@", #keyPath(Subject.name), name)
listFetchRequest.returnsObjectsAsFaults = false
if let existingList = (try! context.fetch(listFetchRequest)).first {
return existingList
}
return List(context: context, name: name)
}
}
enum ListSortOrder: Int, CustomStringConvertible, CaseIterable {
case custom = 0
case alphabetical = 1
@Persisted("listSortOrder", defaultValue: .custom)
static var selectedSort: ListSortOrder
var description: String {
switch self {
case .custom: return "Custom"
case .alphabetical: return "Alphabetical"
}
}
}
| gpl-3.0 | 8935e09c3fed66ad8b7e687f5a903aa3 | 34.72449 | 120 | 0.645815 | 4.618734 | false | false | false | false |
kalvish21/AndroidMessenger | AndroidMessengerMacDesktopClient/Pods/Swifter/Sources/Scopes.swift | 1 | 31932 | //
// HttpHandlers+Scopes.swift
// Swifter
//
// Copyright © 2014-2016 Damian Kołakowski. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Foundation
#endif
public func scopes(scope: Closure) -> ((HttpRequest) -> HttpResponse) {
return { r in
ScopesBuffer[Process.TID] = ""
scope()
return .RAW(200, "OK", ["Content-Type": "text/html"],
{ $0.write([UInt8](("<!DOCTYPE html>" + (ScopesBuffer[Process.TID] ?? "")).utf8)) })
}
}
public typealias Closure = (Void) -> Void
public var idd: String? = nil
public var dir: String? = nil
public var rel: String? = nil
public var rev: String? = nil
public var alt: String? = nil
public var forr: String? = nil
public var src: String? = nil
public var type: String? = nil
public var href: String? = nil
public var text: String? = nil
public var abbr: String? = nil
public var size: String? = nil
public var face: String? = nil
public var char: String? = nil
public var cite: String? = nil
public var span: String? = nil
public var data: String? = nil
public var axis: String? = nil
public var Name: String? = nil
public var name: String? = nil
public var code: String? = nil
public var link: String? = nil
public var lang: String? = nil
public var cols: String? = nil
public var rows: String? = nil
public var ismap: String? = nil
public var shape: String? = nil
public var style: String? = nil
public var alink: String? = nil
public var width: String? = nil
public var rules: String? = nil
public var align: String? = nil
public var frame: String? = nil
public var vlink: String? = nil
public var deferr: String? = nil
public var color: String? = nil
public var media: String? = nil
public var title: String? = nil
public var scope: String? = nil
public var classs: String? = nil
public var value: String? = nil
public var clear: String? = nil
public var start: String? = nil
public var label: String? = nil
public var action: String? = nil
public var height: String? = nil
public var method: String? = nil
public var acceptt: String? = nil
public var object: String? = nil
public var scheme: String? = nil
public var coords: String? = nil
public var usemap: String? = nil
public var onblur: String? = nil
public var nohref: String? = nil
public var nowrap: String? = nil
public var hspace: String? = nil
public var border: String? = nil
public var valign: String? = nil
public var vspace: String? = nil
public var onload: String? = nil
public var target: String? = nil
public var prompt: String? = nil
public var onfocus: String? = nil
public var enctype: String? = nil
public var onclick: String? = nil
public var onkeyup: String? = nil
public var profile: String? = nil
public var version: String? = nil
public var onreset: String? = nil
public var charset: String? = nil
public var standby: String? = nil
public var colspan: String? = nil
public var charoff: String? = nil
public var classid: String? = nil
public var compact: String? = nil
public var declare: String? = nil
public var rowspan: String? = nil
public var checked: String? = nil
public var archive: String? = nil
public var bgcolor: String? = nil
public var content: String? = nil
public var noshade: String? = nil
public var summary: String? = nil
public var headers: String? = nil
public var onselect: String? = nil
public var readonly: String? = nil
public var tabindex: String? = nil
public var onchange: String? = nil
public var noresize: String? = nil
public var disabled: String? = nil
public var longdesc: String? = nil
public var codebase: String? = nil
public var language: String? = nil
public var datetime: String? = nil
public var selected: String? = nil
public var hreflang: String? = nil
public var onsubmit: String? = nil
public var multiple: String? = nil
public var onunload: String? = nil
public var codetype: String? = nil
public var scrolling: String? = nil
public var onkeydown: String? = nil
public var maxlength: String? = nil
public var valuetype: String? = nil
public var accesskey: String? = nil
public var onmouseup: String? = nil
public var autofocus: String? = nil
public var onkeypress: String? = nil
public var ondblclick: String? = nil
public var onmouseout: String? = nil
public var httpEquiv: String? = nil
public var background: String? = nil
public var onmousemove: String? = nil
public var onmouseover: String? = nil
public var cellpadding: String? = nil
public var onmousedown: String? = nil
public var frameborder: String? = nil
public var marginwidth: String? = nil
public var cellspacing: String? = nil
public var placeholder: String? = nil
public var marginheight: String? = nil
public var acceptCharset: String? = nil
public var inner: String? = nil
public func a(c: Closure) { element("a", c) }
public func b(c: Closure) { element("b", c) }
public func i(c: Closure) { element("i", c) }
public func p(c: Closure) { element("p", c) }
public func q(c: Closure) { element("q", c) }
public func s(c: Closure) { element("s", c) }
public func u(c: Closure) { element("u", c) }
public func br(c: Closure) { element("br", c) }
public func dd(c: Closure) { element("dd", c) }
public func dl(c: Closure) { element("dl", c) }
public func dt(c: Closure) { element("dt", c) }
public func em(c: Closure) { element("em", c) }
public func hr(c: Closure) { element("hr", c) }
public func li(c: Closure) { element("li", c) }
public func ol(c: Closure) { element("ol", c) }
public func rp(c: Closure) { element("rp", c) }
public func rt(c: Closure) { element("rt", c) }
public func td(c: Closure) { element("td", c) }
public func th(c: Closure) { element("th", c) }
public func tr(c: Closure) { element("tr", c) }
public func tt(c: Closure) { element("tt", c) }
public func ul(c: Closure) { element("ul", c) }
public func ul<T: SequenceType>(collection: T, _ c: (T.Generator.Element) -> Void) {
element("ul", {
for item in collection {
c(item)
}
})
}
public func h1(c: Closure) { element("h1", c) }
public func h2(c: Closure) { element("h2", c) }
public func h3(c: Closure) { element("h3", c) }
public func h4(c: Closure) { element("h4", c) }
public func h5(c: Closure) { element("h5", c) }
public func h6(c: Closure) { element("h6", c) }
public func bdi(c: Closure) { element("bdi", c) }
public func bdo(c: Closure) { element("bdo", c) }
public func big(c: Closure) { element("big", c) }
public func col(c: Closure) { element("col", c) }
public func del(c: Closure) { element("del", c) }
public func dfn(c: Closure) { element("dfn", c) }
public func dir(c: Closure) { element("dir", c) }
public func div(c: Closure) { element("div", c) }
public func img(c: Closure) { element("img", c) }
public func ins(c: Closure) { element("ins", c) }
public func kbd(c: Closure) { element("kbd", c) }
public func map(c: Closure) { element("map", c) }
public func nav(c: Closure) { element("nav", c) }
public func pre(c: Closure) { element("pre", c) }
public func rtc(c: Closure) { element("rtc", c) }
public func sub(c: Closure) { element("sub", c) }
public func sup(c: Closure) { element("sup", c) }
public func varr(c: Closure) { element("var", c) }
public func wbr(c: Closure) { element("wbr", c) }
public func xmp(c: Closure) { element("xmp", c) }
public func abbr(c: Closure) { element("abbr", c) }
public func area(c: Closure) { element("area", c) }
public func base(c: Closure) { element("base", c) }
public func body(c: Closure) { element("body", c) }
public func cite(c: Closure) { element("cite", c) }
public func code(c: Closure) { element("code", c) }
public func data(c: Closure) { element("data", c) }
public func font(c: Closure) { element("font", c) }
public func form(c: Closure) { element("form", c) }
public func head(c: Closure) { element("head", c) }
public func html(c: Closure) { element("html", c) }
public func link(c: Closure) { element("link", c) }
public func main(c: Closure) { element("main", c) }
public func mark(c: Closure) { element("mark", c) }
public func menu(c: Closure) { element("menu", c) }
public func meta(c: Closure) { element("meta", c) }
public func nobr(c: Closure) { element("nobr", c) }
public func ruby(c: Closure) { element("ruby", c) }
public func samp(c: Closure) { element("samp", c) }
public func span(c: Closure) { element("span", c) }
public func time(c: Closure) { element("time", c) }
public func aside(c: Closure) { element("aside", c) }
public func audio(c: Closure) { element("audio", c) }
public func blink(c: Closure) { element("blink", c) }
public func embed(c: Closure) { element("embed", c) }
public func frame(c: Closure) { element("frame", c) }
public func image(c: Closure) { element("image", c) }
public func input(c: Closure) { element("input", c) }
public func label(c: Closure) { element("label", c) }
public func meter(c: Closure) { element("meter", c) }
public func param(c: Closure) { element("param", c) }
public func small(c: Closure) { element("small", c) }
public func style(c: Closure) { element("style", c) }
public func table(c: Closure) { element("table", c) }
public func table<T: SequenceType>(collection: T, c: (T.Generator.Element) -> Void) {
element("table", {
for item in collection {
c(item)
}
})
}
public func tbody(c: Closure) { element("tbody", c) }
public func tbody<T: SequenceType>(collection: T, c: (T.Generator.Element) -> Void) {
element("tbody", {
for item in collection {
c(item)
}
})
}
public func tfoot(c: Closure) { element("tfoot", c) }
public func thead(c: Closure) { element("thead", c) }
public func title(c: Closure) { element("title", c) }
public func track(c: Closure) { element("track", c) }
public func video(c: Closure) { element("video", c) }
public func applet(c: Closure) { element("applet", c) }
public func button(c: Closure) { element("button", c) }
public func canvas(c: Closure) { element("canvas", c) }
public func center(c: Closure) { element("center", c) }
public func dialog(c: Closure) { element("dialog", c) }
public func figure(c: Closure) { element("figure", c) }
public func footer(c: Closure) { element("footer", c) }
public func header(c: Closure) { element("header", c) }
public func hgroup(c: Closure) { element("hgroup", c) }
public func iframe(c: Closure) { element("iframe", c) }
public func keygen(c: Closure) { element("keygen", c) }
public func legend(c: Closure) { element("legend", c) }
public func object(c: Closure) { element("object", c) }
public func option(c: Closure) { element("option", c) }
public func output(c: Closure) { element("output", c) }
public func script(c: Closure) { element("script", c) }
public func select(c: Closure) { element("select", c) }
public func shadow(c: Closure) { element("shadow", c) }
public func source(c: Closure) { element("source", c) }
public func spacer(c: Closure) { element("spacer", c) }
public func strike(c: Closure) { element("strike", c) }
public func strong(c: Closure) { element("strong", c) }
public func acronym(c: Closure) { element("acronym", c) }
public func address(c: Closure) { element("address", c) }
public func article(c: Closure) { element("article", c) }
public func bgsound(c: Closure) { element("bgsound", c) }
public func caption(c: Closure) { element("caption", c) }
public func command(c: Closure) { element("command", c) }
public func content(c: Closure) { element("content", c) }
public func details(c: Closure) { element("details", c) }
public func elementt(c: Closure) { element("element", c) }
public func isindex(c: Closure) { element("isindex", c) }
public func listing(c: Closure) { element("listing", c) }
public func marquee(c: Closure) { element("marquee", c) }
public func noembed(c: Closure) { element("noembed", c) }
public func picture(c: Closure) { element("picture", c) }
public func section(c: Closure) { element("section", c) }
public func summary(c: Closure) { element("summary", c) }
public func basefont(c: Closure) { element("basefont", c) }
public func colgroup(c: Closure) { element("colgroup", c) }
public func datalist(c: Closure) { element("datalist", c) }
public func fieldset(c: Closure) { element("fieldset", c) }
public func frameset(c: Closure) { element("frameset", c) }
public func menuitem(c: Closure) { element("menuitem", c) }
public func multicol(c: Closure) { element("multicol", c) }
public func noframes(c: Closure) { element("noframes", c) }
public func noscript(c: Closure) { element("noscript", c) }
public func optgroup(c: Closure) { element("optgroup", c) }
public func progress(c: Closure) { element("progress", c) }
public func template(c: Closure) { element("template", c) }
public func textarea(c: Closure) { element("textarea", c) }
public func plaintext(c: Closure) { element("plaintext", c) }
public func javascript(c: Closure) { element("script", ["type": "text/javascript"], c) }
public func blockquote(c: Closure) { element("blockquote", c) }
public func figcaption(c: Closure) { element("figcaption", c) }
public func stylesheet(c: Closure) { element("link", ["rel": "stylesheet", "type": "text/css"], c) }
public func element(node: String, _ c: Closure) { evaluate(node, [:], c) }
public func element(node: String, _ attrs: [String: String?] = [:], _ c: Closure) { evaluate(node, attrs, c) }
var ScopesBuffer = [UInt64: String]()
private func evaluate(node: String, _ attrs: [String: String?] = [:], _ c: Closure) {
// Push the attributes.
let stackid = idd
let stackdir = dir
let stackrel = rel
let stackrev = rev
let stackalt = alt
let stackfor = forr
let stacksrc = src
let stacktype = type
let stackhref = href
let stacktext = text
let stackabbr = abbr
let stacksize = size
let stackface = face
let stackchar = char
let stackcite = cite
let stackspan = span
let stackdata = data
let stackaxis = axis
let stackName = Name
let stackname = name
let stackcode = code
let stacklink = link
let stacklang = lang
let stackcols = cols
let stackrows = rows
let stackismap = ismap
let stackshape = shape
let stackstyle = style
let stackalink = alink
let stackwidth = width
let stackrules = rules
let stackalign = align
let stackframe = frame
let stackvlink = vlink
let stackdefer = deferr
let stackcolor = color
let stackmedia = media
let stacktitle = title
let stackscope = scope
let stackclass = classs
let stackvalue = value
let stackclear = clear
let stackstart = start
let stacklabel = label
let stackaction = action
let stackheight = height
let stackmethod = method
let stackaccept = acceptt
let stackobject = object
let stackscheme = scheme
let stackcoords = coords
let stackusemap = usemap
let stackonblur = onblur
let stacknohref = nohref
let stacknowrap = nowrap
let stackhspace = hspace
let stackborder = border
let stackvalign = valign
let stackvspace = vspace
let stackonload = onload
let stacktarget = target
let stackprompt = prompt
let stackonfocus = onfocus
let stackenctype = enctype
let stackonclick = onclick
let stackonkeyup = onkeyup
let stackprofile = profile
let stackversion = version
let stackonreset = onreset
let stackcharset = charset
let stackstandby = standby
let stackcolspan = colspan
let stackcharoff = charoff
let stackclassid = classid
let stackcompact = compact
let stackdeclare = declare
let stackrowspan = rowspan
let stackchecked = checked
let stackarchive = archive
let stackbgcolor = bgcolor
let stackcontent = content
let stacknoshade = noshade
let stacksummary = summary
let stackheaders = headers
let stackonselect = onselect
let stackreadonly = readonly
let stacktabindex = tabindex
let stackonchange = onchange
let stacknoresize = noresize
let stackdisabled = disabled
let stacklongdesc = longdesc
let stackcodebase = codebase
let stacklanguage = language
let stackdatetime = datetime
let stackselected = selected
let stackhreflang = hreflang
let stackonsubmit = onsubmit
let stackmultiple = multiple
let stackonunload = onunload
let stackcodetype = codetype
let stackscrolling = scrolling
let stackonkeydown = onkeydown
let stackmaxlength = maxlength
let stackvaluetype = valuetype
let stackaccesskey = accesskey
let stackonmouseup = onmouseup
let stackonkeypress = onkeypress
let stackondblclick = ondblclick
let stackonmouseout = onmouseout
let stackhttpEquiv = httpEquiv
let stackbackground = background
let stackonmousemove = onmousemove
let stackonmouseover = onmouseover
let stackcellpadding = cellpadding
let stackonmousedown = onmousedown
let stackframeborder = frameborder
let stackmarginwidth = marginwidth
let stackcellspacing = cellspacing
let stackplaceholder = placeholder
let stackmarginheight = marginheight
let stackacceptCharset = acceptCharset
let stackinner = inner
// Reset the values before a nested scope evalutation.
idd = nil
dir = nil
rel = nil
rev = nil
alt = nil
forr = nil
src = nil
type = nil
href = nil
text = nil
abbr = nil
size = nil
face = nil
char = nil
cite = nil
span = nil
data = nil
axis = nil
Name = nil
name = nil
code = nil
link = nil
lang = nil
cols = nil
rows = nil
ismap = nil
shape = nil
style = nil
alink = nil
width = nil
rules = nil
align = nil
frame = nil
vlink = nil
deferr = nil
color = nil
media = nil
title = nil
scope = nil
classs = nil
value = nil
clear = nil
start = nil
label = nil
action = nil
height = nil
method = nil
acceptt = nil
object = nil
scheme = nil
coords = nil
usemap = nil
onblur = nil
nohref = nil
nowrap = nil
hspace = nil
border = nil
valign = nil
vspace = nil
onload = nil
target = nil
prompt = nil
onfocus = nil
enctype = nil
onclick = nil
onkeyup = nil
profile = nil
version = nil
onreset = nil
charset = nil
standby = nil
colspan = nil
charoff = nil
classid = nil
compact = nil
declare = nil
rowspan = nil
checked = nil
archive = nil
bgcolor = nil
content = nil
noshade = nil
summary = nil
headers = nil
onselect = nil
readonly = nil
tabindex = nil
onchange = nil
noresize = nil
disabled = nil
longdesc = nil
codebase = nil
language = nil
datetime = nil
selected = nil
hreflang = nil
onsubmit = nil
multiple = nil
onunload = nil
codetype = nil
scrolling = nil
onkeydown = nil
maxlength = nil
valuetype = nil
accesskey = nil
onmouseup = nil
onkeypress = nil
ondblclick = nil
onmouseout = nil
httpEquiv = nil
background = nil
onmousemove = nil
onmouseover = nil
cellpadding = nil
onmousedown = nil
frameborder = nil
placeholder = nil
marginwidth = nil
cellspacing = nil
marginheight = nil
acceptCharset = nil
inner = nil
ScopesBuffer[Process.TID] = (ScopesBuffer[Process.TID] ?? "") + "<" + node
// Save the current output before the nested scope evalutation.
var output = ScopesBuffer[Process.TID] ?? ""
// Clear the output buffer for the evalutation.
ScopesBuffer[Process.TID] = ""
// Evaluate the nested scope.
c()
// Render attributes set by the evalutation.
var mergedAttributes = [String: String?]()
if let idd = idd { mergedAttributes["id"] = idd }
if let dir = dir { mergedAttributes["dir"] = dir }
if let rel = rel { mergedAttributes["rel"] = rel }
if let rev = rev { mergedAttributes["rev"] = rev }
if let alt = alt { mergedAttributes["alt"] = alt }
if let forr = forr { mergedAttributes["for"] = forr }
if let src = src { mergedAttributes["src"] = src }
if let type = type { mergedAttributes["type"] = type }
if let href = href { mergedAttributes["href"] = href }
if let text = text { mergedAttributes["text"] = text }
if let abbr = abbr { mergedAttributes["abbr"] = abbr }
if let size = size { mergedAttributes["size"] = size }
if let face = face { mergedAttributes["face"] = face }
if let char = char { mergedAttributes["char"] = char }
if let cite = cite { mergedAttributes["cite"] = cite }
if let span = span { mergedAttributes["span"] = span }
if let data = data { mergedAttributes["data"] = data }
if let axis = axis { mergedAttributes["axis"] = axis }
if let Name = Name { mergedAttributes["Name"] = Name }
if let name = name { mergedAttributes["name"] = name }
if let code = code { mergedAttributes["code"] = code }
if let link = link { mergedAttributes["link"] = link }
if let lang = lang { mergedAttributes["lang"] = lang }
if let cols = cols { mergedAttributes["cols"] = cols }
if let rows = rows { mergedAttributes["rows"] = rows }
if let ismap = ismap { mergedAttributes["ismap"] = ismap }
if let shape = shape { mergedAttributes["shape"] = shape }
if let style = style { mergedAttributes["style"] = style }
if let alink = alink { mergedAttributes["alink"] = alink }
if let width = width { mergedAttributes["width"] = width }
if let rules = rules { mergedAttributes["rules"] = rules }
if let align = align { mergedAttributes["align"] = align }
if let frame = frame { mergedAttributes["frame"] = frame }
if let vlink = vlink { mergedAttributes["vlink"] = vlink }
if let deferr = deferr { mergedAttributes["defer"] = deferr }
if let color = color { mergedAttributes["color"] = color }
if let media = media { mergedAttributes["media"] = media }
if let title = title { mergedAttributes["title"] = title }
if let scope = scope { mergedAttributes["scope"] = scope }
if let classs = classs { mergedAttributes["class"] = classs }
if let value = value { mergedAttributes["value"] = value }
if let clear = clear { mergedAttributes["clear"] = clear }
if let start = start { mergedAttributes["start"] = start }
if let label = label { mergedAttributes["label"] = label }
if let action = action { mergedAttributes["action"] = action }
if let height = height { mergedAttributes["height"] = height }
if let method = method { mergedAttributes["method"] = method }
if let acceptt = acceptt { mergedAttributes["accept"] = acceptt }
if let object = object { mergedAttributes["object"] = object }
if let scheme = scheme { mergedAttributes["scheme"] = scheme }
if let coords = coords { mergedAttributes["coords"] = coords }
if let usemap = usemap { mergedAttributes["usemap"] = usemap }
if let onblur = onblur { mergedAttributes["onblur"] = onblur }
if let nohref = nohref { mergedAttributes["nohref"] = nohref }
if let nowrap = nowrap { mergedAttributes["nowrap"] = nowrap }
if let hspace = hspace { mergedAttributes["hspace"] = hspace }
if let border = border { mergedAttributes["border"] = border }
if let valign = valign { mergedAttributes["valign"] = valign }
if let vspace = vspace { mergedAttributes["vspace"] = vspace }
if let onload = onload { mergedAttributes["onload"] = onload }
if let target = target { mergedAttributes["target"] = target }
if let prompt = prompt { mergedAttributes["prompt"] = prompt }
if let onfocus = onfocus { mergedAttributes["onfocus"] = onfocus }
if let enctype = enctype { mergedAttributes["enctype"] = enctype }
if let onclick = onclick { mergedAttributes["onclick"] = onclick }
if let onkeyup = onkeyup { mergedAttributes["onkeyup"] = onkeyup }
if let profile = profile { mergedAttributes["profile"] = profile }
if let version = version { mergedAttributes["version"] = version }
if let onreset = onreset { mergedAttributes["onreset"] = onreset }
if let charset = charset { mergedAttributes["charset"] = charset }
if let standby = standby { mergedAttributes["standby"] = standby }
if let colspan = colspan { mergedAttributes["colspan"] = colspan }
if let charoff = charoff { mergedAttributes["charoff"] = charoff }
if let classid = classid { mergedAttributes["classid"] = classid }
if let compact = compact { mergedAttributes["compact"] = compact }
if let declare = declare { mergedAttributes["declare"] = declare }
if let rowspan = rowspan { mergedAttributes["rowspan"] = rowspan }
if let checked = checked { mergedAttributes["checked"] = checked }
if let archive = archive { mergedAttributes["archive"] = archive }
if let bgcolor = bgcolor { mergedAttributes["bgcolor"] = bgcolor }
if let content = content { mergedAttributes["content"] = content }
if let noshade = noshade { mergedAttributes["noshade"] = noshade }
if let summary = summary { mergedAttributes["summary"] = summary }
if let headers = headers { mergedAttributes["headers"] = headers }
if let onselect = onselect { mergedAttributes["onselect"] = onselect }
if let readonly = readonly { mergedAttributes["readonly"] = readonly }
if let tabindex = tabindex { mergedAttributes["tabindex"] = tabindex }
if let onchange = onchange { mergedAttributes["onchange"] = onchange }
if let noresize = noresize { mergedAttributes["noresize"] = noresize }
if let disabled = disabled { mergedAttributes["disabled"] = disabled }
if let longdesc = longdesc { mergedAttributes["longdesc"] = longdesc }
if let codebase = codebase { mergedAttributes["codebase"] = codebase }
if let language = language { mergedAttributes["language"] = language }
if let datetime = datetime { mergedAttributes["datetime"] = datetime }
if let selected = selected { mergedAttributes["selected"] = selected }
if let hreflang = hreflang { mergedAttributes["hreflang"] = hreflang }
if let onsubmit = onsubmit { mergedAttributes["onsubmit"] = onsubmit }
if let multiple = multiple { mergedAttributes["multiple"] = multiple }
if let onunload = onunload { mergedAttributes["onunload"] = onunload }
if let codetype = codetype { mergedAttributes["codetype"] = codetype }
if let scrolling = scrolling { mergedAttributes["scrolling"] = scrolling }
if let onkeydown = onkeydown { mergedAttributes["onkeydown"] = onkeydown }
if let maxlength = maxlength { mergedAttributes["maxlength"] = maxlength }
if let valuetype = valuetype { mergedAttributes["valuetype"] = valuetype }
if let accesskey = accesskey { mergedAttributes["accesskey"] = accesskey }
if let onmouseup = onmouseup { mergedAttributes["onmouseup"] = onmouseup }
if let onkeypress = onkeypress { mergedAttributes["onkeypress"] = onkeypress }
if let ondblclick = ondblclick { mergedAttributes["ondblclick"] = ondblclick }
if let onmouseout = onmouseout { mergedAttributes["onmouseout"] = onmouseout }
if let httpEquiv = httpEquiv { mergedAttributes["http-equiv"] = httpEquiv }
if let background = background { mergedAttributes["background"] = background }
if let onmousemove = onmousemove { mergedAttributes["onmousemove"] = onmousemove }
if let onmouseover = onmouseover { mergedAttributes["onmouseover"] = onmouseover }
if let cellpadding = cellpadding { mergedAttributes["cellpadding"] = cellpadding }
if let onmousedown = onmousedown { mergedAttributes["onmousedown"] = onmousedown }
if let frameborder = frameborder { mergedAttributes["frameborder"] = frameborder }
if let marginwidth = marginwidth { mergedAttributes["marginwidth"] = marginwidth }
if let cellspacing = cellspacing { mergedAttributes["cellspacing"] = cellspacing }
if let placeholder = placeholder { mergedAttributes["placeholder"] = placeholder }
if let marginheight = marginheight { mergedAttributes["marginheight"] = marginheight }
if let acceptCharset = acceptCharset { mergedAttributes["accept-charset"] = acceptCharset }
for item in attrs.enumerate() {
mergedAttributes.updateValue(item.element.1, forKey: item.element.0)
}
output = output + mergedAttributes.reduce("") {
if let value = $0.1.1 {
return $0.0 + " \($0.1.0)=\"\(value)\""
} else {
return $0.0
}
}
if let inner = inner {
ScopesBuffer[Process.TID] = output + ">" + (inner) + "</" + node + ">"
} else {
let current = ScopesBuffer[Process.TID] ?? ""
ScopesBuffer[Process.TID] = output + ">" + current + "</" + node + ">"
}
// Pop the attributes.
idd = stackid
dir = stackdir
rel = stackrel
rev = stackrev
alt = stackalt
forr = stackfor
src = stacksrc
type = stacktype
href = stackhref
text = stacktext
abbr = stackabbr
size = stacksize
face = stackface
char = stackchar
cite = stackcite
span = stackspan
data = stackdata
axis = stackaxis
Name = stackName
name = stackname
code = stackcode
link = stacklink
lang = stacklang
cols = stackcols
rows = stackrows
ismap = stackismap
shape = stackshape
style = stackstyle
alink = stackalink
width = stackwidth
rules = stackrules
align = stackalign
frame = stackframe
vlink = stackvlink
deferr = stackdefer
color = stackcolor
media = stackmedia
title = stacktitle
scope = stackscope
classs = stackclass
value = stackvalue
clear = stackclear
start = stackstart
label = stacklabel
action = stackaction
height = stackheight
method = stackmethod
acceptt = stackaccept
object = stackobject
scheme = stackscheme
coords = stackcoords
usemap = stackusemap
onblur = stackonblur
nohref = stacknohref
nowrap = stacknowrap
hspace = stackhspace
border = stackborder
valign = stackvalign
vspace = stackvspace
onload = stackonload
target = stacktarget
prompt = stackprompt
onfocus = stackonfocus
enctype = stackenctype
onclick = stackonclick
onkeyup = stackonkeyup
profile = stackprofile
version = stackversion
onreset = stackonreset
charset = stackcharset
standby = stackstandby
colspan = stackcolspan
charoff = stackcharoff
classid = stackclassid
compact = stackcompact
declare = stackdeclare
rowspan = stackrowspan
checked = stackchecked
archive = stackarchive
bgcolor = stackbgcolor
content = stackcontent
noshade = stacknoshade
summary = stacksummary
headers = stackheaders
onselect = stackonselect
readonly = stackreadonly
tabindex = stacktabindex
onchange = stackonchange
noresize = stacknoresize
disabled = stackdisabled
longdesc = stacklongdesc
codebase = stackcodebase
language = stacklanguage
datetime = stackdatetime
selected = stackselected
hreflang = stackhreflang
onsubmit = stackonsubmit
multiple = stackmultiple
onunload = stackonunload
codetype = stackcodetype
scrolling = stackscrolling
onkeydown = stackonkeydown
maxlength = stackmaxlength
valuetype = stackvaluetype
accesskey = stackaccesskey
onmouseup = stackonmouseup
onkeypress = stackonkeypress
ondblclick = stackondblclick
onmouseout = stackonmouseout
httpEquiv = stackhttpEquiv
background = stackbackground
onmousemove = stackonmousemove
onmouseover = stackonmouseover
cellpadding = stackcellpadding
onmousedown = stackonmousedown
frameborder = stackframeborder
placeholder = stackplaceholder
marginwidth = stackmarginwidth
cellspacing = stackcellspacing
marginheight = stackmarginheight
acceptCharset = stackacceptCharset
inner = stackinner
}
| mit | a5043c3f1dbb74d201a81998ad97320a | 35.575029 | 110 | 0.667147 | 4.007279 | false | false | false | false |
grogdj/toilet-paper-as-a-service | toilet-app/toilet-app/NewHomeController.swift | 1 | 2540 | //
// NewHomeController.swift
// toilet-app
//
// Created by Mauricio Salatino on 15/03/2016.
// Copyright © 2016 ToiletService. All rights reserved.
//
import UIKit
class NewHomeViewController: UIViewController {
@IBOutlet weak var homeNameText: UITextField!
@IBAction func saveNewHome(sender: AnyObject) {
let url = NSURL(string: "http://localhost:8083/api/homes/")!
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let postParams = ["name": homeNameText.text!,"persons": [], "bathrooms": []] as Dictionary<String, AnyObject>
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(postParams, options: NSJSONWritingOptions())
print(postParams)
} catch {
print("bad things happened")
}
// Make the POST call and handle it in a completion handler
session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure we get an OK response
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
// Read the JSON
if let postString = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String {
// Print what we got from the call
print("POST: " + postString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let secondViewController = (self.storyboard?.instantiateViewControllerWithIdentifier("main"))! as UIViewController
self.presentViewController(secondViewController, animated: true, completion: nil)
// self.navigationController?.pushViewController(secondViewController, animated: true)
})
// self.performSelectorOnMainThread("updatePostLabel:", withObject: postString, waitUntilDone: false)
}
}).resume()
}
override func viewDidAppear(animated: Bool) {
print("I'm in the NewHomeViewController")
}
} | apache-2.0 | 3b7c07f9bd847033be51595c94692955 | 35.285714 | 136 | 0.588027 | 5.543668 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Util/BidirectionalDictionary.swift | 1 | 5946 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
public final class AnyBidirectionalDictionary: NSObject, NSCoding {
fileprivate let forwardDictionary: Dictionary<AnyHashable, AnyHashable>
fileprivate let backwardDictionary: Dictionary<AnyHashable, AnyHashable>
public init<ElementOne: Hashable, ElementTwo: Hashable>(_ bidirectionalDictionary: BidirectionalDictionary<ElementOne, ElementTwo>) {
forwardDictionary = .init(uniqueKeysWithValues: bidirectionalDictionary.forwardDictionary.map {
(AnyHashable($0.key), AnyHashable($0.value))
})
backwardDictionary = .init(uniqueKeysWithValues: bidirectionalDictionary.backwardDictionary.map {
(AnyHashable($0.key), AnyHashable($0.value))
})
}
// MARK: - NSCoding
@objc public func encode(with aCoder: NSCoder) {
aCoder.encode(forwardDictionary, forKey: "forwardDictionary")
aCoder.encode(backwardDictionary, forKey: "backwardDictionary")
}
@objc public init?(coder aDecoder: NSCoder) {
forwardDictionary = aDecoder.decodeObject(forKey: "forwardDictionary") as? [AnyHashable: AnyHashable] ?? [:]
backwardDictionary = aDecoder.decodeObject(forKey: "backwardDictionary") as? [AnyHashable: AnyHashable] ?? [:]
guard forwardDictionary.count == backwardDictionary.count else {
owsFailDebug("incorrect backing values")
return nil
}
}
}
/// A dictionary that maintains a 1:1 key <-> value mapping and allows lookup by value or key.
public struct BidirectionalDictionary<ElementOne: Hashable, ElementTwo: Hashable> {
fileprivate typealias ForwardType = [ElementOne: ElementTwo]
fileprivate typealias BackwardType = [ElementTwo: ElementOne]
fileprivate var forwardDictionary: ForwardType
fileprivate var backwardDictionary: [ElementTwo: ElementOne]
public init() {
forwardDictionary = [:]
backwardDictionary = [:]
}
public init?(_ anyBidirectionalDictionary: AnyBidirectionalDictionary) {
guard let forwardDictionary = anyBidirectionalDictionary.forwardDictionary as? ForwardType,
let backwardDictionary = anyBidirectionalDictionary.backwardDictionary as? BackwardType else {
return nil
}
self.forwardDictionary = forwardDictionary
self.backwardDictionary = backwardDictionary
}
public init(uniqueKeysWithValues elements: [(ElementOne, ElementTwo)]) {
self.init()
elements.forEach { self[$0] = $1 }
}
public subscript(_ key: ElementOne) -> ElementTwo? {
get {
return forwardDictionary[key]
}
set {
guard let newValue = newValue else {
if let previousValue = forwardDictionary[key] {
backwardDictionary[previousValue] = nil
}
forwardDictionary[key] = nil
return
}
forwardDictionary[key] = newValue
backwardDictionary[newValue] = key
}
}
public subscript(_ key: ElementTwo) -> ElementOne? {
get {
return backwardDictionary[key]
}
set {
guard let newValue = newValue else {
if let previousValue = backwardDictionary[key] {
forwardDictionary[previousValue] = nil
}
backwardDictionary[key] = nil
return
}
backwardDictionary[key] = newValue
forwardDictionary[newValue] = key
}
}
public var count: Int {
assert(forwardDictionary.count == backwardDictionary.count)
return forwardDictionary.count
}
}
// MARK: - Collection
extension BidirectionalDictionary: Collection {
public typealias Index = DictionaryIndex<ElementOne, ElementTwo>
public var startIndex: Index {
return forwardDictionary.startIndex
}
public var endIndex: Index {
return forwardDictionary.endIndex
}
public subscript (position: Index) -> Iterator.Element {
precondition((startIndex ..< endIndex).contains(position), "out of bounds")
let element = forwardDictionary[position]
return (element.key, element.value)
}
public func index(after i: Index) -> Index {
return forwardDictionary.index(after: i)
}
}
// MARK: - Sequence
extension BidirectionalDictionary: Sequence {
public typealias Iterator = AnyIterator<(ElementOne, ElementTwo)>
public func makeIterator() -> Iterator {
var iterator = forwardDictionary.makeIterator()
return AnyIterator { iterator.next() }
}
}
// MARK: - Transforms
extension BidirectionalDictionary {
public func mapValues<T>(_ transform: (ElementTwo) throws -> T) rethrows -> BidirectionalDictionary<ElementOne, T> {
return try forwardDictionary.reduce(into: BidirectionalDictionary<ElementOne, T>()) { dict, pair in
dict[pair.key] = try transform(pair.value)
}
}
public func map<T>(_ transform: (ElementOne, ElementTwo) throws -> T) rethrows -> [T] {
return try forwardDictionary.map(transform)
}
public func filter(_ isIncluded: (ElementOne, ElementTwo) throws -> Bool) rethrows -> BidirectionalDictionary<ElementOne, ElementTwo> {
return try forwardDictionary.reduce(
into: BidirectionalDictionary<ElementOne, ElementTwo>()
) { dict, pair in
guard try isIncluded(pair.key, pair.value) else { return }
dict[pair.key] = pair.value
}
}
}
// MARK: -
extension BidirectionalDictionary: ExpressibleByDictionaryLiteral {
public typealias Key = ElementOne
public typealias Value = ElementTwo
public init(dictionaryLiteral elements: (ElementOne, ElementTwo)...) {
self.init(uniqueKeysWithValues: elements)
}
}
| gpl-3.0 | 287e9866ac3c41c7363a71668130a4b2 | 32.784091 | 139 | 0.659267 | 5.495379 | false | false | false | false |
EasyRequestSwift/EasyRequest | EasyRequest/EasyRequest/EasyRequest.swift | 1 | 3333 | //
// EasyRequestProtocol.swift
// EasyRequest
//
// Created by Guilherme Baldissera on 31/05/17.
// Copyright © 2017 BEPiD. All rights reserved.
//
import Foundation
enum EasyRequestMethods : String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
case patch = "PATCH"
}
protocol EasyRequestDelegate {
func delegateEasyRequestSuccess(body: Data?, headers: [AnyHashable: Any], status: Int)
func delegateEasyRequestError(error: Error)
}
class EasyRequest {
// MARK: - Attributes
private var baseUrl: URL
private var commonHeaders : [[String: String]] = []
private var environment: [[String: String]] = []
public var delegate: EasyRequestDelegate?
public init(baseUrl: String) {
self.baseUrl = URL(string: baseUrl)!
}
// MARK: - Manage Headers
// Function to add Headers to use in request
public func addCommonHeader(key: String, value: String) {
self.commonHeaders.append([key: value])
}
// Function to remove header
public func removeCommonHeader(named name: String) {
self.commonHeaders = self.commonHeaders.filter() { header in header.keys.first! != name }
}
// Function to set all headers at once
public func setCommonHeaders(headers: [[String: String]]) {
self.commonHeaders = headers
}
// MARK: - Requests
public func executeRequest(
to pathUrl: String,
withParameters params: [[String: String]],
usingMethod method: EasyRequestMethods,
andSpecificHeaders specificHeaders: [[String: String]],
sendingBody body: Data?)
{
let urlRequest = createURLRequest(to: "", withParameters: [], usingMethod: .get, andSpecificHeaders: [], sending: nil)
doRequest(withUrlRequest: urlRequest)
// Execute request withou parameters, use url setted in addUrl
}
// Function to finally execute request to url informatted
private func doRequest(withUrlRequest urlRequest: URLRequest) {
let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: urlRequest, completionHandler: sessionCompletionHandler)
dataTask.resume()
}
private func sessionCompletionHandler(data: Data?, response: URLResponse?, error: Error?) {
if let errorReceived = error {
self.delegate?.delegateEasyRequestError(error: errorReceived)
}
let headers = (response as! HTTPURLResponse).allHeaderFields
let status = (response as! HTTPURLResponse).statusCode
self.delegate?.delegateEasyRequestSuccess(body: data, headers: headers, status: status)
}
private func createURLRequest (
to pathUrl: String,
withParameters params: [[String: String]],
usingMethod method: EasyRequestMethods,
andSpecificHeaders specificHeaders: [[String: String]],
sending body: Data?) -> URLRequest
{
var request = URLRequest(url: URL(string: pathUrl, relativeTo: self.baseUrl)!)
request.httpMethod = method.rawValue
request.httpBody = body
let headers = (specificHeaders.count == 0) ? self.commonHeaders : specificHeaders
for header in headers {
request.setValue(header.values.first, forHTTPHeaderField: header.keys.first!)
}
return request
}
}
| mit | f28b9c124fd007cdf12c5b8e6a819880 | 30.140187 | 126 | 0.677371 | 4.533333 | false | false | false | false |
nathawes/swift | test/DebugInfo/shadow_copies.swift | 23 | 1365 | // RUN: %target-swift-frontend %s -Onone -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend %s -Onone -emit-ir -g -o - \
// RUN: -disable-debugger-shadow-copies | %FileCheck %s --check-prefix=NOCOPY
class ClassA
{
var x : Int64
var y : Float
init (_ input : Int64)
{
x = input
y = Float(input) + 0.5
}
}
class ClassB : ClassA
{
override init (_ input : Int64)
{
// CHECK: @"$s{{.*}}6ClassBCyACs5Int64Vcfc"
// NOCOPY: @"$s{{.*}}6ClassBCyACs5Int64Vcfc"
// CHECK: alloca {{.*}}ClassBC*
// NOCOPY: alloca {{.*}}ClassBC*
// CHECK: alloca i64
// CHECK-NOT: alloca
// NOCOPY-NOT: alloca
// CHECK: ret {{.*}}ClassBC
// NOCOPY: ret {{.*}}ClassBC
super.init (input)
}
}
let b = ClassB(1);
func use(_ x: Int) {}
class ClassC
{
// CHECK: define {{.*}}@"$s13shadow_copies6ClassCCACycfc"
// NOCOPY: define {{.*}}@"$s13shadow_copies6ClassCCACycfc"
init ()
{
// CHECK: alloca %T13shadow_copies6ClassCC*
// CHECK-NOT: alloca
// NOCOPY-NOT: alloca
// CHECK: call void @llvm.dbg.value(metadata i{{(64|32)}} 10
// NOCOPY: call void @llvm.dbg.value(metadata i{{(64|32)}} 10
let x = 10
use(x)
use(x)
// CHECK: ret
// NOCOPY: ret
}
}
let c = ClassC()
| apache-2.0 | 5ac31ce827cb6b61f2c78725052da41e | 21.016129 | 79 | 0.531136 | 3.273381 | false | false | false | false |
Idomeneus/duo-iOS | Duo/Duo/Question.swift | 1 | 3493 | //
// Question.swift
// Duo
//
// Created by Bobo on 10/15/15.
// Copyright © 2015 Boris Emorine. All rights reserved.
//
import Foundation
import CoreData
class Question: NSManagedObject {
convenience init(dict: Dictionary<String, AnyObject>, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
let entity = NSEntityDescription.entityForName("Question", inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)
questionId = dict["questionId"] as? String
updateWithDictionary(dict)
}
class func existingOrNewQuestionWithDictionary(dict: Dictionary<String, AnyObject>, inManageObjectContext context:NSManagedObjectContext!) -> Question {
let id: String? = dict["questionId"] as? String
var question: Question?
if (id == nil) {
question = Question(dict: dict, insertIntoManagedObjectContext: context)
} else {
question = existingOrNewQuestionWithId(id!, inManageObjectContext: context)
question!.updateWithDictionary(dict)
}
return question!
}
class func existingOrNewQuestionWithId(questionId: String, inManageObjectContext context:NSManagedObjectContext!) -> Question {
var question: Question? = getQuestionWithId(questionId, inManageObjectContext: context)
if (question == nil) {
let entity = NSEntityDescription.entityForName("Question", inManagedObjectContext: context)!
question = Question(entity: entity, insertIntoManagedObjectContext: context)
question?.questionId = questionId
}
return question!
}
class func getQuestionWithId(questionId: String, inManageObjectContext context:NSManagedObjectContext!) -> Question? {
if (questionId.characters.count <= 0) {
return nil
}
let request: NSFetchRequest = NSFetchRequest(entityName: "Question")
let predicate: NSPredicate = NSPredicate(format: "questionId == %@", questionId)
request.predicate = predicate
do {
let results: Array = try context.executeFetchRequest(request)
if (!results.isEmpty) {
return results[0] as? Question
}
} catch {
print(error)
}
return nil
}
func updateWithDictionary(dict: Dictionary<String, AnyObject>) {
if (questionId != dict["questionId"] as? String) {
print("Question: updateWithDictionary() - Trying to update question with different Id")
return
}
textBody = dict["textBody"] as? String
let unixDate: Double? = dict["createdAt"] as? Double
if (unixDate != nil) {
createdAt = NSDate(timeIntervalSince1970: unixDate!)
}
myVote = dict["myVote"] as? Int
imgURLs = dict["answer"]?["imgURLs"] as? [String]
votes = dict["answer"]?["votes"] as? [Int]
let userDict: Dictionary<String, AnyObject>? = dict["createdBy"] as? Dictionary<String, AnyObject>
if (userDict != nil) {
createdBy = User.existingOrNewUserWithDictionary(userDict!, inManageObjectContext: managedObjectContext)
}
}
}
| mit | 7192e2a82087c5e29d6f0f9ea2fd6912 | 32.576923 | 156 | 0.607102 | 5.5872 | false | false | false | false |
viWiD/Persist | Pods/Evergreen/Sources/Evergreen/Handler.swift | 1 | 3505 | //
// Handler.swift
// Evergreen
//
// Created by Nils Fischer on 12.10.14.
// Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved.
//
import Foundation
// MARK: - Record
public struct Record: CustomStringConvertible {
public let date: NSDate
public let description: String
}
// MARK: - Handler
public class Handler {
public var logLevel: LogLevel?
public var formatter: Formatter
public init(formatter: Formatter) {
self.formatter = formatter
}
/// Called by a logger to handle an event. The event's log level is checked against the handler's and the given formatter is used to obtain a record from the event. Subsequently, `emitRecord` is called to produce the output.
public final func emitEvent<M>(event: Event<M>) {
if let handlerLogLevel = self.logLevel,
let eventLogLevel = event.logLevel
where eventLogLevel < handlerLogLevel {
return
}
self.emitRecord(self.formatter.recordFromEvent(event))
}
/// Called to actually produce some output from a record. Override this method to send the record to an output stream of your choice. The default implementation simply prints the record to the console.
public func emitRecord(record: Record) {
print(record)
}
}
// MARK: - Console Handler Class
/// A handler that writes log records to the console.
public class ConsoleHandler: Handler {
public convenience init() {
self.init(formatter: Formatter(style: .Default))
}
override public func emitRecord(record: Record) {
// TODO: use debugPrintln?
print(record)
}
}
// MARK: - File Handler Class
/// A handler that writes log records to a file.
public class FileHandler: Handler, CustomStringConvertible {
private var file: NSFileHandle!
private let fileURL: NSURL
public convenience init?(fileURL: NSURL) {
self.init(fileURL: fileURL, formatter: Formatter(style: .Full))
}
public init?(fileURL: NSURL, formatter: Formatter) {
self.fileURL = fileURL
super.init(formatter: formatter)
let fileManager = NSFileManager.defaultManager()
guard let path = fileURL.filePathURL?.path else {
return nil
}
guard fileManager.createFileAtPath(path, contents: nil, attributes: nil) else {
return nil
}
guard let file = NSFileHandle(forWritingAtPath: path) else {
return nil
}
file.seekToEndOfFile()
self.file = file
}
override public func emitRecord(record: Record) {
if let recordData = (record.description + "\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
self.file.writeData(recordData)
} else {
// TODO
}
}
public var description: String {
return "FileHandler(\(fileURL))"
}
}
// MARK: Stenography Handler
/// A handler that appends log records to an array.
public class StenographyHandler: Handler {
// TODO: make sure there is no memory problem when this array becomes too large
/// All records logged to this handler
public private(set) var records: [Record] = []
public convenience init() {
self.init(formatter: Formatter(style: .Default))
}
override public func emitRecord(record: Record) {
self.records.append(record)
}
}
| mit | 1b9283a6d54e692e1d90f7d10a418752 | 26.170543 | 228 | 0.647361 | 4.624011 | false | false | false | false |
DeepestDesire/GC | ProductArchitecture/Modules/Market/MarketViewController.swift | 1 | 1081 | //
// ViewController.swift
// ProductArchitecture
//
// Created by GeorgeCharles on 11/18/16.
// Copyright © 2016 GeorgeCharles. All rights reserved.
//
import UIKit
import SVProgressHUD
import Alamofire
let KScreenWidth = UIScreen.main.bounds.width
class MarketViewController: UIViewController {
/// 懒加载 初始化
var buttonTitle: String = "TAP TO GO"
var model: MarketViewModelProtocol!
lazy var button: UIButton = {
let button = UIButton(type: .custom)
button.setTitle(self.buttonTitle, for: .normal)
button.setTitleColor(UIColor(netHex: 0x000000) , for: .normal)
button.setImage(UIImage(named: "ic_camera_alt") , for: .normal)
button.frame = CGRect(x: (KScreenWidth-200)/2, y: 200, width: 200, height: 200)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
model = MarketViewModel()
view.addSubview(button)
setPageInfo()
navigationItem
}
func setPageInfo() {
title = model.NaviTitle
}
}
| apache-2.0 | 8a8401a92130298e799b763574ddc151 | 24.428571 | 87 | 0.641386 | 4.204724 | false | false | false | false |
badparking/badparking-ios | BadParking/Classes/controls/ButtonNext.swift | 1 | 1916 | //
// ButtonNext.swift
// BadParking
//
// Created by Eugene Nagorny on 9/1/16.
// Copyright © 2016 BadParking. All rights reserved.
//
import Foundation
import UIKit
class NextButton: UIButton {
let mainLayer: CAShapeLayer! = CAShapeLayer.init()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// add border
self.layer.cornerRadius = 22;
self.layer.borderWidth = 2
self.layer.borderColor = UIColor.darkGray.withAlphaComponent(self.isEnabled ? 1.0 : 0.4).cgColor
// add green round rect
let bezierPath = UIBezierPath.init(roundedRect: CGRect.init(x: 4, y: 4, width: 92, height: 36), cornerRadius: 18)
mainLayer.path = bezierPath.cgPath
mainLayer.fillColor = UIColor(red:0.39, green:0.78, blue:0.00, alpha:self.isEnabled ? 1.0 : 0.4).cgColor
self.layer .addSublayer(mainLayer)
}
override var isHighlighted: Bool {
didSet {
if isHighlighted {
self.layer.borderColor = UIColor.darkGray.withAlphaComponent(0.7).cgColor
mainLayer.fillColor = UIColor(red:0.39, green:0.78, blue:0.00, alpha:0.7).cgColor
} else {
self.layer.borderColor = UIColor.darkGray.cgColor
mainLayer.fillColor = UIColor(red:0.39, green:0.78, blue:0.00, alpha:1.0).cgColor
}
}
}
override var isEnabled: Bool {
didSet {
if isEnabled {
self.layer.borderColor = UIColor.darkGray.cgColor
mainLayer.fillColor = UIColor(red:0.39, green:0.78, blue:0.00, alpha:1.0).cgColor
} else {
self.layer.borderColor = UIColor.darkGray.withAlphaComponent(0.4).cgColor
mainLayer.fillColor = UIColor(red:0.39, green:0.78, blue:0.00, alpha:0.4).cgColor
}
}
}
}
| apache-2.0 | caaac7398ccbfd3e52d9902f59acb26b | 33.818182 | 121 | 0.598433 | 4.006276 | false | false | false | false |
phenemann/Authentication | Sources/HMACAlgorithm.swift | 1 | 2591 | //
// HMACAlgorithm.swift
// Authentication
//
// Created by Pablo Henemann on 24/04/17.
// Copyright © 2017 Pablo Henemann. All rights reserved.
//
import Foundation
import CommonCrypto
enum HMACAlgorithm {
case md5, sha1, sha224, sha256, sha384, sha512
func toCCHmacAlgorithm() -> CCHmacAlgorithm {
var result: Int = 0
switch self {
case .md5:
result = kCCHmacAlgMD5
case .sha1:
result = kCCHmacAlgSHA1
case .sha224:
result = kCCHmacAlgSHA224
case .sha256:
result = kCCHmacAlgSHA256
case .sha384:
result = kCCHmacAlgSHA384
case .sha512:
result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
func digestLength() -> Int {
var result: CInt = 0
switch self {
case .md5:
result = CC_MD5_DIGEST_LENGTH
case .sha1:
result = CC_SHA1_DIGEST_LENGTH
case .sha224:
result = CC_SHA224_DIGEST_LENGTH
case .sha256:
result = CC_SHA256_DIGEST_LENGTH
case .sha384:
result = CC_SHA384_DIGEST_LENGTH
case .sha512:
result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
}
extension String {
func hmac(algorithm: HMACAlgorithm, key: String) -> String {
let cKey = key.cString(using: String.Encoding.utf8)
let cData = self.cString(using: String.Encoding.utf8)
var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength()))
CCHmac(algorithm.toCCHmacAlgorithm(), cKey!, Int(strlen(cKey!)), cData!, Int(strlen(cData!)), &result)
let hmacData:NSData = NSData(bytes: result, length: (Int(algorithm.digestLength())))
let hmacBase64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
return String(hmacBase64)
}
func hmac1(algorithm: HMACAlgorithm, key: String) -> String {
let cKey = key.cString(using: String.Encoding.utf8)
let cData = self.cString(using: String.Encoding.utf8)
var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength()))
CCHmac(algorithm.toCCHmacAlgorithm(), cKey!, Int(strlen(cKey!)), cData!, Int(strlen(cData!)), &result)
let hmacData:NSData = NSData(bytes: result, length: (Int(algorithm.digestLength())))
let hmacBase64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
return String(hmacBase64)
}
}
| mit | c7e95276e2e42d69a78aa68e207743bc | 33.533333 | 115 | 0.628185 | 4.104596 | false | false | false | false |
AaronBratcher/ALBNoSQLDB | ALBNoSQLDB/ALBNoSQLDB/DBObject.swift | 1 | 11796 | //
// DBObject.swift
// ALBNoSQLDB
//
// Created by Aaron Bratcher on 4/25/19.
// Copyright © 2019 Aaron Bratcher. All rights reserved.
//
import Foundation
public protocol DBObject: Codable {
static var table: DBTable { get }
var key: String { get set }
}
extension DBObject {
/**
Instantiate object and populate with values from the database. If instantiation fails, nil is returned.
- parameter db: Database object holding the data.
- parameter key: Key of the data entry.
*/
public init?(db: ALBNoSQLDB, key: String) {
guard let dictionaryValue = db.dictValueFromTable(Self.table, for: key)
, let dbObject: Self = Self.dbObjectWithDict(dictionaryValue, for: key)
else { return nil }
self = dbObject
}
/**
Save the object to the database. This will update the values in the database if the object is already present.
- parameter db: Database object to hold the data.
- parameter expiration: Optional Date specifying when the data is to be automatically deleted. Default value is nil specifying no automatic deletion.
- returns: Discardable Bool value of a successful save.
*/
@discardableResult
public func save(to db: ALBNoSQLDB, autoDeleteAfter expiration: Date? = nil) -> Bool {
guard let jsonValue = jsonValue
, db.setValueInTable(Self.table, for: key, to: jsonValue, autoDeleteAfter: expiration)
else { return false }
return true
}
/**
Remove the object from the database
- parameter db: Database object that holds the data.
- returns: Discardable Bool value of a successful deletion.
*/
@discardableResult
public func delete(from db: ALBNoSQLDB) -> Bool {
return db.deleteFromTable(Self.table, for: key)
}
/**
Asynchronously instantiate object and populate with values from the database before executing the passed block with object. If object could not be instantiated properly, block is not executed.
- parameter db: Database object to hold the data.
- parameter key: Key of the data entry.
- parameter queue: DispatchQueue to run the execution block on. Default value is nil specifying the main queue.
- parameter block: Block of code to execute with instantiated object.
- returns: DBCommandToken that can be used to cancel the call before it executes. Nil is returned if database could not be opened.
*/
@discardableResult
public static func loadObjectFromDB(_ db: ALBNoSQLDB, for key: String, queue: DispatchQueue? = nil, completion: @escaping (Self) -> Void) -> DBCommandToken? {
let token = db.dictValueFromTable(table, for: key, queue: queue, completion: { (results) in
if case .success(let dictionaryValue) = results
, let dbObject = dbObjectWithDict(dictionaryValue, for: key) {
completion(dbObject)
}
})
return token
}
private static func dbObjectWithDict(_ dictionaryValue: [String: AnyObject], for key: String) -> Self? {
var dictionaryValue = dictionaryValue
dictionaryValue["key"] = key as AnyObject
let decoder = DictDecoder(dictionaryValue)
return try? Self(from: decoder)
}
/**
JSON string value based on the what's saved in the encode method
*/
public var jsonValue: String? {
let jsonEncoder = JSONEncoder()
jsonEncoder.dateEncodingStrategy = .formatted(ALBNoSQLDB.dateFormatter)
do {
let jsonData = try jsonEncoder.encode(self)
let jsonString = String(data: jsonData, encoding: .utf8)
return jsonString
}
catch _ {
return nil
}
}
}
private enum DictDecoderError: Error {
case missingValueForKey(String)
case invalidDate(String)
case invalidURL(String)
case invalidUUID(String)
case invalidJSON(String)
}
private extension Bool {
init<T : Numeric>(_ number: T) {
if number == 0 {
self.init(false)
} else {
self.init(true)
}
}
init(_ string: String) {
self.init(string == "1" || string.uppercased() == "YES" || string.uppercased() == "TRUE")
}
}
private class DictKeyedContainer<K: CodingKey>: KeyedDecodingContainerProtocol {
typealias Key = K
typealias DBDict = [String: AnyObject]
let codingPath: [CodingKey] = []
var allKeys: [K] { return dict.keys.compactMap { K(stringValue: $0) } }
private var dict: [String: AnyObject]
init(_ dict: [String: AnyObject]) {
self.dict = dict
}
func contains(_ key: K) -> Bool {
return dict[key.stringValue] != nil
}
func decodeNil(forKey key: K) throws -> Bool {
if dict[key.stringValue] == nil {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
return false
}
func decode(_ type: Bool.Type, forKey key: K) throws -> Bool {
guard let value = dict[key.stringValue] else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
if let intValue = value as? Int {
return Bool(intValue)
}
if let stringValue = value as? String {
return Bool(stringValue)
}
throw DictDecoderError.missingValueForKey(key.stringValue)
}
func decode(_ type: Int.Type, forKey key: K) throws -> Int {
guard let value = dict[key.stringValue] else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
if let intValue = value as? Int {
return intValue
}
guard let stringValue = value as? String
, let intValue = Int(stringValue)
else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
return intValue
}
func decodeArray(_ type: [Int].Type, forKey key: K) throws -> [Int] {
guard let values = dict[key.stringValue] as? [AnyObject] else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
var intValues = [Int]()
for value in values {
if let intValue = value as? Int {
intValues.append(intValue)
continue
}
guard let stringValue = value as? String
, let intValue = Int(stringValue)
else { throw DictDecoderError.missingValueForKey(key.stringValue) }
intValues.append(intValue)
}
return intValues
}
func decode(_ type: Double.Type, forKey key: K) throws -> Double {
guard let value = dict[key.stringValue] else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
if let doubleValue = value as? Double {
return doubleValue
}
guard let stringValue = value as? String
, let doubleValue = Double(stringValue)
else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
return doubleValue
}
func decodeArray(_ type: [Double].Type, forKey key: K) throws -> [Double] {
guard let values = dict[key.stringValue] as? [AnyObject] else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
var doubleValues = [Double]()
for value in values {
if let doubleValue = value as? Double {
doubleValues.append(doubleValue)
continue
}
guard let stringValue = value as? String
, let doubleValue = Double(stringValue)
else { throw DictDecoderError.missingValueForKey(key.stringValue) }
doubleValues.append(doubleValue)
}
return doubleValues
}
func decode(_ type: String.Type, forKey key: K) throws -> String {
guard let value = dict[key.stringValue] as? String else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
return value
}
func decodeArray(_ type: [String].Type, forKey key: K) throws -> [String] {
guard let value = dict[key.stringValue] as? [String] else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
return value
}
func decode(_ type: Data.Type, forKey key: K) throws -> Data {
guard let value = dict[key.stringValue] as? Data else {
throw DictDecoderError.missingValueForKey(key.stringValue)
}
return value
}
func decode(_ type: Date.Type, forKey key: K) throws -> Date {
let string = try decode(String.self, forKey: key)
if let date = ALBNoSQLDB.dateFormatter.date(from: string) {
return date
} else {
throw DictDecoderError.invalidDate(string)
}
}
func decode(_ type: URL.Type, forKey key: K) throws -> URL {
let string = try decode(String.self, forKey: key)
if let url = URL(string: string) {
return url
} else {
throw DictDecoderError.invalidURL(string)
}
}
func decode(_ type: UUID.Type, forKey key: K) throws -> UUID {
let string = try decode(String.self, forKey: key)
if let uuid = UUID(uuidString: string) {
return uuid
} else {
throw DictDecoderError.invalidUUID(string)
}
}
func decode<T>(_ type: T.Type, forKey key: K) throws -> T where T: Decodable {
if Data.self == T.self {
return try decode(Data.self, forKey: key) as! T
} else if Date.self == T.self {
return try decode(Date.self, forKey: key) as! T
} else if URL.self == T.self {
return try decode(URL.self, forKey: key) as! T
} else if UUID.self == T.self {
return try decode(UUID.self, forKey: key) as! T
} else if Bool.self == T.self {
return try decode(Bool.self, forKey: key) as! T
} else if [Int].self == T.self {
let intArray = try decodeArray([Int].self, forKey: key)
guard let jsonData = try? JSONSerialization.data(withJSONObject: intArray, options: .prettyPrinted) else {
throw DictDecoderError.invalidJSON("Unknown data structure")
}
return try JSONDecoder().decode(T.self, from: jsonData)
} else if [Double].self == T.self {
let doubleArray = try decodeArray([Double].self, forKey: key)
guard let jsonData = try? JSONSerialization.data(withJSONObject: doubleArray, options: .prettyPrinted) else {
throw DictDecoderError.invalidJSON("Unknown data structure")
}
return try JSONDecoder().decode(T.self, from: jsonData)
} else if [String].self == T.self {
let stringArray = try decodeArray([String].self, forKey: key)
guard let jsonData = try? JSONSerialization.data(withJSONObject: stringArray, options: .prettyPrinted) else {
throw DictDecoderError.invalidJSON("Unknown data structure")
}
return try JSONDecoder().decode(T.self, from: jsonData)
} else if [Date].self == T.self {
let dateArray = try decodeArray([String].self, forKey: key)
guard let jsonData = try? JSONSerialization.data(withJSONObject: dateArray, options: .prettyPrinted) else {
throw DictDecoderError.invalidJSON("^^^ Unknown data structure")
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(ALBNoSQLDB.dateFormatter)
return try decoder.decode(T.self, from: jsonData)
} else {
let jsonText = try decode(String.self, forKey: key)
guard let jsonData = jsonText.data(using: .utf8) else {
throw DictDecoderError.invalidJSON(jsonText)
}
return try JSONDecoder().decode(T.self, from: jsonData)
}
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
fatalError("_KeyedContainer does not support nested containers.")
}
func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer {
fatalError("_KeyedContainer does not support nested containers.")
}
func superDecoder() throws -> Decoder {
fatalError("_KeyedContainer does not support nested containers.")
}
func superDecoder(forKey key: K) throws -> Decoder {
fatalError("_KeyedContainer does not support nested containers.")
}
}
private class DictDecoder: Decoder {
var codingPath: [CodingKey] = []
var userInfo: [CodingUserInfoKey: Any] = [:]
var dict: [String: AnyObject]?
init(_ dict: [String: AnyObject]) {
self.dict = dict
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
guard let row = self.dict else { fatalError() }
return KeyedDecodingContainer(DictKeyedContainer<Key>(row))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
fatalError("SQLiteDecoder doesn't support unkeyed decoding")
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
fatalError("SQLiteDecoder doesn't support single value decoding")
}
}
| mit | cc290cf01731197f8ed0f6e1d18de7e7 | 29.478036 | 197 | 0.710471 | 3.809755 | false | false | false | false |
gdelarosa/Safe-Reach | Safe Reach/HealthVC.swift | 1 | 6950 | //
// HealthVC.swift
// Safe Reach
//
// Created by Gina De La Rosa on 12/11/16.
// Copyright © 2016 Gina De La Rosa. All rights reserved.
//
import UIKit
class HealthVC: UITableViewController {
let imageList = ["amassi",
"ahf",
"apla",
"ascpasadena",
"asfoc",
"ahh",
"apait",
"apait",
"beingalive",
"bai",
"commonground",
"dappalmsprings",
"elawomenscenter",
"fap",
"fap",
"fap",
"fap",
"fap",
"lifegroup",
"lapublichealth",
"minorityap",
"reachla",
"redcircle",
"thewall",
"whittierrio",
"youthclinic"]
let titleList = ["African American AIDS Support Services",
"AIDS Healthcare Foundation",
"AIDS Project Los Angeles",
"AIDS Service Center",
"AIDS Servcies Foundation Orange County",
"Alliance for Housing and Healing",
"Asian Pacific AIDS Intervention Team Garden Grove",
"Asian Pacific AIDS Intervention Team Los Angeles",
"Being Alive People with HIV/AIDS Action Coalition",
"Black AIDS Institute",
"Common Ground",
"Desert AIDS Project",
"East Los Angeles Women's Center",
"Foothill AIDS Project Claremont",
"Foothill AIDS Project Hesperia",
"Foothill AIDS Project Pasadena",
"Foothill AIDS Project Riverside",
"Foothill AIDS Project San Bernardino",
"Life Group Los Angeles",
"Los Angeles Department of Public Health",
"Minority AIDS Project",
"Reach Los Angeles",
"Red Circle Project",
"The Wall Las Memorias Project",
"Transgender Youth Clinic",
"Whittier Rio Hondo AIDS Project"]
let descriptionList =
["Provides opportunity for diverse people of African descent.",
"Free HIV/STD checking for men at the AHF's Men's Wellness Center",
"Leadership in prevention, advocacy, and service.",
"AIDS services.",
"AIDS support services for PWAs living below the poverty line.",
"Formerly Long Beach AIDS Foundation.",
"AIDS services. Sponsors social group for GLBT Asian people.",
"AIDS prevention, education, and outreach to the Asian community.",
"AIDS support services.",
"Education, prevention, and outreach to the black community.",
"AIDS/HIV Services",
"AIDS services.",
"AIDS and domestic violence services to Latina women.",
"AIDS/HIV services",
"AIDS/HIV services",
"AIDS/HIV services",
"AIDS/HIV services",
"AIDS/HIV services",
"AIDS support services",
"Education, outreach, and public policy",
"Support services and education for African American and Latino PWA's.",
"To motivate LGBT people of color, ages 16-29, to increase self-care by providing social and sexual health services through an empowering community engagement process, employing the visual and performing arts.",
"The only HIV prevention program in Los Angeles County that specifically provides services to the Native American /Alaska Native Community.",
"The Wall-Las Memorias Project is a community health and wellness organization dedicated to serving Latino, LGBT and other underserved populations through advocacy, education and building the next generation of leadership.",
"The Center for Transyouth Health and Development promotes healthy futures for transyouth by providing services, research, training and capacity building that is developmentally informed, affirmative, compassionate and holistic for gender non-conforming children and transyouth.",
"AIDS services"]
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: UIImage(named: "Triangle"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
}
// MARK: - Tableview
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "Health") as! TableViewCell
cell.healthTitle.text = titleList[(indexPath as NSIndexPath).row]
cell.healthDescription.text = descriptionList[(indexPath as NSIndexPath).row]
let imageName = UIImage(named: imageList[(indexPath as NSIndexPath).row])
cell.healthImage.image = imageName
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// store information into string before push to detail view
if (segue.identifier == "HealthDetail")
{
// reference detailVC in this vc
let dvc = segue.destination as! HealthDetailVC
if let indexPath = self.tableView.indexPathForSelectedRow
{
// convert to string to place in our sent data
let title = titleList[(indexPath as NSIndexPath).row] as String
// now we reference objects in the dvc
dvc.sentTitleData = title
// convert to string to place in our sent data
let description = descriptionList[(indexPath as NSIndexPath).row] as String
// now we reference objects in the dvc
dvc.sentDescriptionData = description
// convert to string to place in our sent data
let imageView = imageList[(indexPath as NSIndexPath).row] as String
// now we reference objects in the dvc
dvc.sentImageData = imageView
}
}
}
}
| mit | 0f0e001b4604e95b19fb92cac9a9c52c | 44.123377 | 289 | 0.567851 | 5.361883 | false | false | false | false |
neonichu/Wunderschnell | Phone App/SphereIOClient.swift | 1 | 11163 | //
// SphereIOClient.swift
// WatchButton
//
// Created by Boris Bügling on 09/05/15.
// Copyright (c) 2015 Boris Bügling. All rights reserved.
//
import Alamofire
import Foundation
import Result
private extension Int {
func toNumber() -> NSNumber {
return NSNumber(int: Int32(self))
}
}
// Somehow using `NSURLAuthenticationChallenge` didn't work against the Sphere API 😭
private struct AuthRequest: URLRequestConvertible {
private let clientId: String
private let clientSecret: String
private let project: String
var URLRequest: NSURLRequest {
if let URL = NSURL(string: "https://auth.sphere.io/oauth/token") {
let URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.HTTPMethod = Method.POST.rawValue
let parameters = [ "grant_type": "client_credentials", "scope": "manage_project:\(project)" ]
let auth = String(format: "%@:%@", clientId, clientSecret).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let header = auth.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
URLRequest.setValue("Basic \(header)", forHTTPHeaderField: "Authorization")
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
fatalError("Broken Authentication URL...")
}
}
private typealias OAuthResult = Result<String, NSError>
private typealias OAuthClosure = (result: OAuthResult) -> Void
public typealias SphereResult = Result<[String:AnyObject], NSError>
public typealias SphereClosure = (result: SphereResult) -> Void
public struct Address {
private let firstName: String
private let lastName: String
private let streetName: String
private let streetNumber: String
private let postalCode: String
private let city: String
private let country: String
public init(firstName: String, lastName: String, streetName: String, streetNumber: String, postalCode: String, city: String, country: String) {
self.firstName = firstName
self.lastName = lastName
self.streetName = streetName
self.streetNumber = streetNumber
self.postalCode = postalCode
self.city = city
self.country = country
}
func toDictionary() -> [String:String] {
var dictionary = [String:String]()
let mirror = reflect(self)
for index in 0 ..< mirror.count {
let (childKey, childMirror) = mirror[index]
if let value = childMirror.value as? String {
dictionary[childKey] = value
}
}
return dictionary
}
}
public enum OrderState: String {
case Open = "Open"
case Complete = "Complete"
case Cancelled = "Cancelled"
}
public enum PaymentState: String {
case BalanceDue = "BalanceDue"
case Failed = "Failed"
case Pending = "Pending"
case CreditOwed = "CreditOwed"
case Paid = "Paid"
}
public class SphereIOClient {
private let baseURL = "https://api.sphere.io"
private let clientId: String
private let clientSecret: String
private let project: String
private var token: String?
private func getToken(completion: OAuthClosure) {
Alamofire.request(AuthRequest(clientId: clientId, clientSecret: clientSecret, project: project))
.responseJSON { (_, _, JSON, error) in
if let json = JSON as? [String:AnyObject], token = json["access_token"] as? String {
completion(result: OAuthResult(value: token))
return
}
if let error = error {
completion(result: OAuthResult(error: error))
return
}
fatalError("Didn't even get an error...")
}
}
private func performAuthenticatedRequest(completion: SphereClosure, _ endpoint: String, _ method: Alamofire.Method = .GET, _ parameters: [String: AnyObject]? = nil) {
if !validateToken(performAuthenticatedRequest, completion, endpoint, method, parameters) {
return
}
Alamofire.request(sphereRequest(endpoint, method, parameters)).responseJSON { (_, _, JSON, error) in
self.sphereCompletion(completion, JSON, error)
}
}
private func sphereCompletion(completion: SphereClosure, _ JSON: AnyObject?, _ error: NSError?) {
if let json = JSON as? [String:AnyObject] {
completion(result: SphereResult(value: json))
return
}
if let error = error {
completion(result: SphereResult(error: error))
return
}
fatalError("Didn't even get an error...")
}
private func sphereRequest(endpoint: String, _ method: Alamofire.Method, _ parameters: [String: AnyObject]?) -> URLRequestConvertible {
assert(token != nil, "")
if let token = token, URL = NSURL(string: "\(baseURL)/\(endpoint)") {
let URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.HTTPMethod = method.rawValue
URLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let encoding = Alamofire.ParameterEncoding.JSON
return encoding.encode(URLRequest, parameters: parameters).0
}
fatalError("Could not create valid request.")
}
private func validateToken(function: (completion: SphereClosure, endpoint: String, method: Alamofire.Method, parameters: [String: AnyObject]?) -> Void, _ completion: SphereClosure, _ endpoint: String, _ method: Alamofire.Method, _ parameters: [String: AnyObject]?) -> Bool {
if token == nil {
getToken() { (result) in
result.analysis(ifSuccess: { (token) in
self.token = token
function(completion: completion, endpoint: endpoint, method: method, parameters: parameters)
}, ifFailure: { (error) in
completion(result: SphereResult(error: error))
})
}
return false
}
return true
}
// MARK: - Action helpers
private func performAction(action: [String:AnyObject], onCart cart: [String:AnyObject], _ completion: SphereClosure) {
if let cartId = cart["id"] as? String, cartVersion = cart["version"] as? Int {
performAuthenticatedRequest(completion, "\(project)/carts/\(cartId)", .POST, ["version": cartVersion.toNumber(), "actions": [action]])
} else {
fatalError("Could not perform action on cart.")
}
}
private func performAction(action: [String:AnyObject], onOrder order: [String:AnyObject], _ completion: SphereClosure) {
if let orderId = order["id"] as? String, orderVersion = order["version"] as? Int {
performAuthenticatedRequest(completion, "\(project)/orders/\(orderId)", .POST, ["version": orderVersion.toNumber(), "actions": [action]])
} else {
fatalError("Could not perform action on order.")
}
}
// MARK: - Public API
public init(clientId: String, clientSecret: String, project: String) {
self.clientId = clientId
self.clientSecret = clientSecret
self.project = project
}
public func fetchProductData(completion: SphereClosure) {
performAuthenticatedRequest(completion, "\(project)/product-projections")
}
// MARK: - Public API for Carts
public func addProduct(product: [String:AnyObject], quantity: Int, toCart cart: [String:AnyObject], _ completion: SphereClosure) {
if let productId = product["id"] as? String, masterVariant = product["masterVariant"] as? [String:AnyObject], variantId = masterVariant["id"] as? Int {
performAction(["action": "addLineItem", "productId": productId, "variantId": variantId.toNumber(), "quantity": quantity.toNumber()], onCart: cart, completion)
} else {
fatalError("Could not add product to cart")
}
}
public func addShippingAddress(address: Address, toCart cart: [String:AnyObject], _ completion: SphereClosure) {
performAction(["action": "setShippingAddress", "address": address.toDictionary()], onCart: cart, completion)
}
public func createCart(currency: String, _ completion: SphereClosure) {
performAuthenticatedRequest(completion, "\(project)/carts", .POST, ["currency": currency])
}
public func queryCart(cartId: String, _ completion: SphereClosure) {
performAuthenticatedRequest(completion, "\(project)/carts/\(cartId)")
}
public func recalculateCart(forCart cart: [String:AnyObject], _ completion: SphereClosure) {
performAction(["action": "recalculate"], onCart: cart, completion)
}
public func setShippingMethod(forCart cart: [String:AnyObject], _ completion: SphereClosure) {
performAction(["action": "setShippingMethod"], onCart: cart, completion)
}
// MARK - Public API for Orders
public func createOrder(forCart cart: [String:AnyObject], _ completion: SphereClosure) {
if let cartId = cart["id"] as? String, cartVersion = cart["version"] as? Int {
performAuthenticatedRequest(completion, "\(project)/orders", .POST, ["version": cartVersion.toNumber(), "id": cartId, "orderNumber": cartId])
} else {
fatalError("Could not create order for cart")
}
}
public func queryOrder(orderId: String, _ completion: SphereClosure) {
performAuthenticatedRequest(completion, "\(project)/orders/\(orderId)")
}
public func quickOrder(# product: [String:AnyObject], to address: Address, _ completion: SphereClosure) {
let currency = address.country == "DE" ? "EUR" : "USD"
createCart(currency) { (result) in
result.analysis(ifSuccess: { (cart) in
self.addProduct(product, quantity: 1, toCart: cart) { (result2) in
result2.analysis(ifSuccess: { (cart2) in
self.addShippingAddress(address, toCart: cart2) { (result3) in
result3.analysis(ifSuccess: { (cart3) in
self.createOrder(forCart: cart3, completion)
} , ifFailure: { (error) in completion(result: SphereResult(error: error)) })
}
}, ifFailure: { (error) in completion(result: SphereResult(error: error)) })
}
}, ifFailure: { (error) in completion(result: SphereResult(error: error)) })
}
}
public func setPaymentState(state: PaymentState, forOrder order: [String:AnyObject], _ completion: SphereClosure) {
performAction(["action": "changePaymentState", "paymentState": state.rawValue], onOrder: order, completion)
}
public func setState(state: OrderState, forOrder order: [String:AnyObject], _ completion: SphereClosure) {
performAction(["action": "changeOrderState", "orderState": state.rawValue], onOrder: order, completion)
}
}
| mit | d2b0423e24768077f8f1d378e5f2a9df | 39.136691 | 278 | 0.63515 | 4.81987 | false | false | false | false |
Shivol/Swift-CS333 | playgrounds/swift/SwiftBasics.playground/Pages/Tuples.xcplaygroundpage/Contents.swift | 2 | 1634 | /*:
## Tuples
[Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
****
*/
var pair: (String, Int)
pair.0 = "Swift"
pair.1 = 333
pair
var namedPair: (name: String, age: Int)
namedPair.name = "Ilya"
namedPair.age = 28
namedPair
//: Type inferrence
let point = (x: 0.0, y: -1.0)
type(of: point)
let area = (bottomLeft: (-1.0, -1.0), topRight: (1.0, 1.0))
type(of: area)
//: Tuples of the same type are comparable. Tuples are compared from left to right.
if point > area.bottomLeft && point < area.topRight {
"point is inside the (\(area.bottomLeft), \(area.topRight)) area"
}
if point == (0.0, 0.0) {
"point is zero"
} else if point.x > 0.0 {
if point.y > 0.0 {
"point is in first quarter"
} else {
"point is in fourth quarter"
}
} else {
if point.y < 0.0 {
"point is in third quarter"
} else {
"point is in second quarter"
}
}
//: _Tuples can be decomposed into a set of variables:_
var (first, second) = point
"first: \(first); second: \(second)"
type(of: first)
(first, second) = (second, first)
"swapped first: \(first); second: \(second)"
//: _Underscore `_` can be used to ignore some of tuple values._
let (onlyFirst, _) = point
"first: \(onlyFirst)"
//: _It can also be used in switch cases:_
switch point {
case (0.0, 0.0):
break
case (0.0, _):
"point belongs to the X axis"
case (_, 0.0):
"point belongs to the Y axis"
default:
break
}
//: _(Type) ~ Type_
type(of: ("Hello, Tuple!"))
type(of: (42))
type(of: ()) // () ~ Void
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
| mit | ab11e473cff185de1a285f85793f9c7d | 22.285714 | 83 | 0.603681 | 3.012939 | false | false | false | false |
qimuyunduan/ido_ios | ido_ios/SetPwdController.swift | 1 | 2472 | //
// SetPwdController.swift
// ido_ios
//
// Created by qimuyunduan on 16/6/8.
// Copyright © 2016年 qimuyunduan. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class SetPwdController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var setPwd: UITextField!
@IBOutlet weak var confirmPwd: UITextField!
@IBOutlet weak var confirmButton: UIButton!
var personName :String?
override func viewDidLoad() {
super.viewDidLoad()
confirmPwd.delegate = self
confirmButton.addTarget(self, action: #selector(SetPwdController.login), forControlEvents: UIControlEvents.TouchUpInside)
}
func textFieldDidBeginEditing(textField: UITextField) {
confirmButton.setBackgroundImage(UIImage(named: "loginEnabled"), forState: UIControlState.Normal)
}
func login() -> Void {
if setPwd.text == confirmPwd.text && setPwd.text?.characters.count >= 6 {
let destinationController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("myTableViewController") as! MyTableViewController
newUser()
// if newUser()["result"] == "200" {
// let userDefaults = NSUserDefaults.standardUserDefaults()
// userDefaults.setBool(true, forKey: "registered")
// userDefaults.setObject(personName, forKey: "userName")
// destinationController.personalInfo["name"] = personName
// destinationController.personalInfo["insureCompany"] = "ido cor"
// destinationController.personalInfo["moneyLeft"] = "0"
// self.presentViewController(destinationController, animated: false, completion: nil)
// }
}
}
func newUser() -> Void {
let paras = ["userName":personName!,"password":String(setPwd.text),"salt":String(setPwd.text),"phone":personName!]
Alamofire.request(.POST, HOST+"user",parameters:paras).responseJSON{
response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
print(json)
}
case .Failure(let error):
print(error)
}
}
}
}
| mit | cefb96ace5a6e9839e9a3b834a6c50df | 32.821918 | 170 | 0.593358 | 5.154489 | false | false | false | false |
AlanHasty/SwiftSensorTag | SwiftSensorTag/ViewController.swift | 1 | 11138 | //
// ViewController.swift
// SwiftSensorTag
//
// Created by Anas Imtiaz on 26/01/2015.
// Copyright (c) 2015 Anas Imtiaz. All rights reserved.
//
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDataSource, UITableViewDelegate {
// Title labels
var titleLabel : UILabel!
var statusLabel : UILabel!
// BLE
var centralManager : CBCentralManager!
var sensorTagPeripheral : CBPeripheral!
// Table View
var sensorTagTableView : UITableView!
// Sensor Values
var allSensorLabels : [String] = []
var allSensorValues : [Double] = []
var ambientTemperature : Double!
var objectTemperature : Double!
var accelerometerX : Double!
var accelerometerY : Double!
var accelerometerZ : Double!
var relativeHumidity : Double!
var magnetometerX : Double!
var magnetometerY : Double!
var magnetometerZ : Double!
var gyroscopeX : Double!
var gyroscopeY : Double!
var gyroscopeZ : Double!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Initialize central manager on load
centralManager = CBCentralManager(delegate: self, queue: nil)
// Set up title label
titleLabel = UILabel()
titleLabel.text = "Sensor Tag"
titleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
titleLabel.sizeToFit()
titleLabel.center = CGPoint(x: self.view.frame.midX, y: self.titleLabel.bounds.midY+28)
self.view.addSubview(titleLabel)
// Set up status label
statusLabel = UILabel()
statusLabel.textAlignment = NSTextAlignment.Center
statusLabel.text = "Loading..."
statusLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12)
statusLabel.sizeToFit()
//statusLabel.center = CGPoint(x: self.view.frame.midX, y: (titleLabel.frame.maxY + statusLabel.bounds.height/2) )
statusLabel.frame = CGRect(x: self.view.frame.origin.x, y: self.titleLabel.frame.maxY, width: self.view.frame.width, height: self.statusLabel.bounds.height)
self.view.addSubview(statusLabel)
// Set up table view
setupSensorTagTableView()
// Initialize all sensor values and labels
allSensorLabels = SensorTag.getSensorLabels()
for (var i=0; i<allSensorLabels.count; i++) {
allSensorValues.append(0)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/******* CBCentralManagerDelegate *******/
// Check status of BLE hardware
func centralManagerDidUpdateState(central: CBCentralManager!) {
if central.state == CBCentralManagerState.PoweredOn {
// Scan for peripherals if BLE is turned on
central.scanForPeripheralsWithServices(nil, options: nil)
self.statusLabel.text = "Searching for BLE Devices"
}
else {
// Can have different conditions for all states if needed - show generic alert for now
showAlertWithText(header: "Error", message: "Bluetooth switched off or not initialized")
}
}
// Check out the discovered peripherals to find Sensor Tag
func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
if SensorTag.sensorTagFound(advertisementData) == true {
// Update Status Label
self.statusLabel.text = "Sensor Tag Found"
// Stop scanning, set as the peripheral to use and establish connection
self.centralManager.stopScan()
self.sensorTagPeripheral = peripheral
self.sensorTagPeripheral.delegate = self
self.centralManager.connectPeripheral(peripheral, options: nil)
}
else {
self.statusLabel.text = "Sensor Tag NOT Found"
//showAlertWithText(header: "Warning", message: "SensorTag Not Found")
}
}
// Discover services of the peripheral
func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
self.statusLabel.text = "Discovering peripheral services"
peripheral.discoverServices(nil)
}
// If disconnected, start searching again
func centralManager(central: CBCentralManager!, didDisconnectPeripheral peripheral: CBPeripheral!, error: NSError!) {
self.statusLabel.text = "Disconnected"
central.scanForPeripheralsWithServices(nil, options: nil)
}
/******* CBCentralPeripheralDelegate *******/
// Check if the service discovered is valid i.e. one of the following:
// IR Temperature Service
// Accelerometer Service
// Humidity Service
// Magnetometer Service
// Barometer Service
// Gyroscope Service
// (Others are not implemented)
func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) {
self.statusLabel.text = "Looking at peripheral services"
for service in peripheral.services {
let thisService = service as CBService
if SensorTag.validService(thisService) {
// Discover characteristics of all valid services
peripheral.discoverCharacteristics(nil, forService: thisService)
}
}
}
// Enable notification and sensor for each characteristic of valid service
func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) {
self.statusLabel.text = "Enabling sensors"
var enableValue = 1
let enablyBytes = NSData(bytes: &enableValue, length: sizeof(UInt8))
for charateristic in service.characteristics {
let thisCharacteristic = charateristic as CBCharacteristic
if SensorTag.validDataCharacteristic(thisCharacteristic) {
// Enable Sensor Notification
self.sensorTagPeripheral.setNotifyValue(true, forCharacteristic: thisCharacteristic)
}
if SensorTag.validConfigCharacteristic(thisCharacteristic) {
// Enable Sensor
self.sensorTagPeripheral.writeValue(enablyBytes, forCharacteristic: thisCharacteristic, type: CBCharacteristicWriteType.WithResponse)
}
}
}
// Get data values when they are updated
func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
self.statusLabel.text = "Connected"
if characteristic.UUID == IRTemperatureDataUUID {
self.ambientTemperature = SensorTag.getAmbientTemperature(characteristic.value)
self.objectTemperature = SensorTag.getObjectTemperature(characteristic.value, ambientTemperature: self.ambientTemperature)
self.allSensorValues[0] = self.ambientTemperature
self.allSensorValues[1] = self.objectTemperature
}
else if characteristic.UUID == AccelerometerDataUUID {
let allValues = SensorTag.getAccelerometerData(characteristic.value)
self.accelerometerX = allValues[0]
self.accelerometerY = allValues[1]
self.accelerometerZ = allValues[2]
self.allSensorValues[2] = self.accelerometerX
self.allSensorValues[3] = self.accelerometerY
self.allSensorValues[4] = self.accelerometerZ
}
else if characteristic.UUID == HumidityDataUUID {
self.relativeHumidity = SensorTag.getRelativeHumidity(characteristic.value)
self.allSensorValues[5] = self.relativeHumidity
}
else if characteristic.UUID == MagnetometerDataUUID {
let allValues = SensorTag.getMagnetometerData(characteristic.value)
self.magnetometerX = allValues[0]
self.magnetometerY = allValues[1]
self.magnetometerZ = allValues[2]
self.allSensorValues[6] = self.magnetometerX
self.allSensorValues[7] = self.magnetometerY
self.allSensorValues[8] = self.magnetometerZ
}
else if characteristic.UUID == GyroscopeDataUUID {
let allValues = SensorTag.getGyroscopeData(characteristic.value)
self.gyroscopeX = allValues[0]
self.gyroscopeY = allValues[1]
self.gyroscopeZ = allValues[2]
self.allSensorValues[9] = self.gyroscopeX
self.allSensorValues[10] = self.gyroscopeY
self.allSensorValues[11] = self.gyroscopeZ
}
else if characteristic.UUID == BarometerDataUUID {
//println("BarometerDataUUID")
}
self.sensorTagTableView.reloadData()
}
/******* UITableViewDataSource *******/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allSensorLabels.count
}
/******* UITableViewDelegate *******/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var thisCell = tableView.dequeueReusableCellWithIdentifier("sensorTagCell") as SensorTagTableViewCell
thisCell.sensorNameLabel.text = allSensorLabels[indexPath.row]
var valueString = NSString(format: "%.2f", allSensorValues[indexPath.row])
thisCell.sensorValueLabel.text = valueString
return thisCell
}
/******* Helper *******/
// Show alert
func showAlertWithText (header : String = "Warning", message : String) {
var alert = UIAlertController(title: header, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
alert.view.tintColor = UIColor.redColor()
self.presentViewController(alert, animated: true, completion: nil)
}
// Set up Table View
func setupSensorTagTableView () {
self.sensorTagTableView = UITableView()
self.sensorTagTableView.delegate = self
self.sensorTagTableView.dataSource = self
self.sensorTagTableView.frame = CGRect(x: self.view.bounds.origin.x, y: self.statusLabel.frame.maxY+20, width: self.view.bounds.width, height: self.view.bounds.height)
self.sensorTagTableView.registerClass(SensorTagTableViewCell.self, forCellReuseIdentifier: "sensorTagCell")
self.sensorTagTableView.tableFooterView = UIView() // to hide empty lines after cells
self.view.addSubview(self.sensorTagTableView)
}
}
| mit | d4be129870805c45776e0e8fe09e45b6 | 38.637011 | 175 | 0.65308 | 5.467845 | false | false | false | false |
Quick/Nimble | Sources/Nimble/Matchers/SatisfyAllOf.swift | 4 | 2679 | /// A Nimble matcher that succeeds when the actual value matches with all of the matchers
/// provided in the variable list of matchers.
public func satisfyAllOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> {
return satisfyAllOf(predicates)
}
/// A Nimble matcher that succeeds when the actual value matches with all of the matchers
/// provided in the array of matchers.
public func satisfyAllOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return Predicate.define { actualExpression in
var postfixMessages = [String]()
var status: PredicateStatus = .matches
for predicate in predicates {
let result = try predicate.satisfies(actualExpression)
if result.status == .fail {
status = .fail
} else if result.status == .doesNotMatch, status != .fail {
status = .doesNotMatch
}
postfixMessages.append("{\(result.message.expectedMessage)}")
}
var msg: ExpectationMessage
if let actualValue = try actualExpression.evaluate() {
msg = .expectedCustomValueTo(
"match all of: " + postfixMessages.joined(separator: ", and "),
actual: "\(actualValue)"
)
} else {
msg = .expectedActualValueTo(
"match all of: " + postfixMessages.joined(separator: ", and ")
)
}
return PredicateResult(status: status, message: msg)
}
}
public func && <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return satisfyAllOf(left, right)
}
#if canImport(Darwin)
import class Foundation.NSObject
extension NMBPredicate {
@objc public class func satisfyAllOfMatcher(_ predicates: [NMBPredicate]) -> NMBPredicate {
return NMBPredicate { actualExpression in
if predicates.isEmpty {
return NMBPredicateResult(
status: NMBPredicateStatus.fail,
message: NMBExpectationMessage(
fail: "satisfyAllOf must be called with at least one matcher"
)
)
}
var elementEvaluators = [Predicate<NSObject>]()
for predicate in predicates {
let elementEvaluator = Predicate<NSObject> { expression in
return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift()
}
elementEvaluators.append(elementEvaluator)
}
return try satisfyAllOf(elementEvaluators).satisfies(actualExpression).toObjectiveC()
}
}
}
#endif
| apache-2.0 | de0ee8bcb4abf078b024ad74d781352c | 36.732394 | 124 | 0.602837 | 5.294466 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Tests/SwiftProtobufTests/Test_OneofFields_Access_Proto3.swift | 11 | 15010 | // Test/Sources/TestSuite/Test_OneofFields_Access_Proto3.swift
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Exercises the apis for fields within a oneof.
///
// -----------------------------------------------------------------------------
import XCTest
import Foundation
// NOTE: The generator changes what is generated based on the number/types
// of fields (using a nested storage class or not), to be completel, all
// these tests should be done once with a message that gets that storage
// class and a second time with messages that avoid that.
class Test_OneofFields_Access_Proto3: XCTestCase {
// Accessing one field.
// - Returns default
// - Accepts/Captures value
// - Resets
// - Accepts/Captures default value
func testOneofInt32() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofInt32, 0)
XCTAssertNil(msg.o)
msg.oneofInt32 = 51
XCTAssertEqual(msg.oneofInt32, 51)
XCTAssertEqual(msg.o, .oneofInt32(51))
msg.o = nil
XCTAssertEqual(msg.oneofInt32, 0)
XCTAssertNil(msg.o)
msg.oneofInt32 = 0
XCTAssertEqual(msg.oneofInt32, 0)
XCTAssertEqual(msg.o, .oneofInt32(0))
}
func testOneofInt64() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofInt64, 0)
XCTAssertNil(msg.o)
msg.oneofInt64 = 52
XCTAssertEqual(msg.oneofInt64, 52)
XCTAssertEqual(msg.o, .oneofInt64(52))
msg.o = nil
XCTAssertEqual(msg.oneofInt64, 0)
XCTAssertNil(msg.o)
msg.oneofInt64 = 0
XCTAssertEqual(msg.oneofInt64, 0)
XCTAssertEqual(msg.o, .oneofInt64(0))
}
func testOneofUint32() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofUint32, 0)
XCTAssertNil(msg.o)
msg.oneofUint32 = 53
XCTAssertEqual(msg.oneofUint32, 53)
XCTAssertEqual(msg.o, .oneofUint32(53))
msg.o = nil
XCTAssertEqual(msg.oneofUint32, 0)
XCTAssertNil(msg.o)
msg.oneofUint32 = 0
XCTAssertEqual(msg.oneofUint32, 0)
XCTAssertEqual(msg.o, .oneofUint32(0))
}
func testOneofUint64() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofUint64, 0)
XCTAssertNil(msg.o)
msg.oneofUint64 = 54
XCTAssertEqual(msg.oneofUint64, 54)
XCTAssertEqual(msg.o, .oneofUint64(54))
msg.o = nil
XCTAssertEqual(msg.oneofUint64, 0)
XCTAssertNil(msg.o)
msg.oneofUint64 = 0
XCTAssertEqual(msg.oneofUint64, 0)
XCTAssertEqual(msg.o, .oneofUint64(0))
}
func testOneofSint32() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofSint32, 0)
XCTAssertNil(msg.o)
msg.oneofSint32 = 55
XCTAssertEqual(msg.oneofSint32, 55)
XCTAssertEqual(msg.o, .oneofSint32(55))
msg.o = nil
XCTAssertEqual(msg.oneofSint32, 0)
XCTAssertNil(msg.o)
msg.oneofSint32 = 0
XCTAssertEqual(msg.oneofSint32, 0)
XCTAssertEqual(msg.o, .oneofSint32(0))
}
func testOneofSint64() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofSint64, 0)
XCTAssertNil(msg.o)
msg.oneofSint64 = 56
XCTAssertEqual(msg.oneofSint64, 56)
XCTAssertEqual(msg.o, .oneofSint64(56))
msg.o = nil
XCTAssertEqual(msg.oneofSint64, 0)
XCTAssertNil(msg.o)
msg.oneofSint64 = 0
XCTAssertEqual(msg.oneofSint64, 0)
XCTAssertEqual(msg.o, .oneofSint64(0))
}
func testOneofFixed32() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofFixed32, 0)
XCTAssertNil(msg.o)
msg.oneofFixed32 = 57
XCTAssertEqual(msg.oneofFixed32, 57)
XCTAssertEqual(msg.o, .oneofFixed32(57))
msg.o = nil
XCTAssertEqual(msg.oneofFixed32, 0)
XCTAssertNil(msg.o)
msg.oneofFixed32 = 0
XCTAssertEqual(msg.oneofFixed32, 0)
XCTAssertEqual(msg.o, .oneofFixed32(0))
}
func testOneofFixed64() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofFixed64, 0)
XCTAssertNil(msg.o)
msg.oneofFixed64 = 58
XCTAssertEqual(msg.oneofFixed64, 58)
XCTAssertEqual(msg.o, .oneofFixed64(58))
msg.o = nil
XCTAssertEqual(msg.oneofFixed64, 0)
XCTAssertNil(msg.o)
msg.oneofFixed64 = 0
XCTAssertEqual(msg.oneofFixed64, 0)
XCTAssertEqual(msg.o, .oneofFixed64(0))
}
func testOneofSfixed32() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofSfixed32, 0)
XCTAssertNil(msg.o)
msg.oneofSfixed32 = 59
XCTAssertEqual(msg.oneofSfixed32, 59)
XCTAssertEqual(msg.o, .oneofSfixed32(59))
msg.o = nil
XCTAssertEqual(msg.oneofSfixed32, 0)
XCTAssertNil(msg.o)
msg.oneofSfixed32 = 0
XCTAssertEqual(msg.oneofSfixed32, 0)
XCTAssertEqual(msg.o, .oneofSfixed32(0))
}
func testOneofSfixed64() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofSfixed64, 0)
XCTAssertNil(msg.o)
msg.oneofSfixed64 = 60
XCTAssertEqual(msg.oneofSfixed64, 60)
XCTAssertEqual(msg.o, .oneofSfixed64(60))
msg.o = nil
XCTAssertEqual(msg.oneofSfixed64, 0)
XCTAssertNil(msg.o)
msg.oneofSfixed64 = 0
XCTAssertEqual(msg.oneofSfixed64, 0)
XCTAssertEqual(msg.o, .oneofSfixed64(0))
}
func testOneofFloat() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofFloat, 0.0)
XCTAssertNil(msg.o)
msg.oneofFloat = 61.0
XCTAssertEqual(msg.oneofFloat, 61.0)
XCTAssertEqual(msg.o, .oneofFloat(61.0))
msg.o = nil
XCTAssertEqual(msg.oneofFloat, 0.0)
XCTAssertNil(msg.o)
msg.oneofFloat = 0.0
XCTAssertEqual(msg.oneofFloat, 0.0)
XCTAssertEqual(msg.o, .oneofFloat(0.0))
}
func testOneofDouble() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofDouble, 0.0)
XCTAssertNil(msg.o)
msg.oneofDouble = 62.0
XCTAssertEqual(msg.oneofDouble, 62.0)
XCTAssertEqual(msg.o, .oneofDouble(62.0))
msg.o = nil
XCTAssertEqual(msg.oneofDouble, 0.0)
XCTAssertNil(msg.o)
msg.oneofDouble = 0.0
XCTAssertEqual(msg.oneofDouble, 0.0)
XCTAssertEqual(msg.o, .oneofDouble(0.0))
}
func testOneofBool() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofBool, false)
XCTAssertNil(msg.o)
msg.oneofBool = true
XCTAssertEqual(msg.oneofBool, true)
XCTAssertEqual(msg.o, .oneofBool(true))
msg.o = nil
XCTAssertEqual(msg.oneofBool, false)
XCTAssertNil(msg.o)
msg.oneofBool = false
XCTAssertEqual(msg.oneofBool, false)
XCTAssertEqual(msg.o, .oneofBool(false))
}
func testOneofString() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofString, "")
XCTAssertNil(msg.o)
msg.oneofString = "64"
XCTAssertEqual(msg.oneofString, "64")
XCTAssertEqual(msg.o, .oneofString("64"))
msg.o = nil
XCTAssertEqual(msg.oneofString, "")
XCTAssertNil(msg.o)
msg.oneofString = ""
XCTAssertEqual(msg.oneofString, "")
XCTAssertEqual(msg.o, .oneofString(""))
}
func testOneofBytes() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofBytes, Data())
XCTAssertNil(msg.o)
msg.oneofBytes = Data([65])
XCTAssertEqual(msg.oneofBytes, Data([65]))
XCTAssertEqual(msg.o, .oneofBytes(Data([65])))
msg.o = nil
XCTAssertEqual(msg.oneofBytes, Data())
XCTAssertNil(msg.o)
msg.oneofBytes = Data()
XCTAssertEqual(msg.oneofBytes, Data())
XCTAssertEqual(msg.o, .oneofBytes(Data()))
}
// No group.
func testOneofMessage() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofMessage.optionalInt32, 0)
XCTAssertNil(msg.o)
var subMsg = ProtobufUnittest_Message3()
subMsg.optionalInt32 = 66
msg.oneofMessage = subMsg
XCTAssertEqual(msg.oneofMessage.optionalInt32, 66)
XCTAssertEqual(msg.oneofMessage, subMsg)
if case .oneofMessage(let v)? = msg.o {
XCTAssertEqual(v.optionalInt32, 66)
XCTAssertEqual(v, subMsg)
} else {
XCTFail("Wasn't the right case")
}
msg.o = nil
XCTAssertEqual(msg.oneofMessage.optionalInt32, 0)
XCTAssertNil(msg.o)
// Default within the message
var subMsg2 = ProtobufUnittest_Message3()
subMsg2.optionalInt32 = 0
msg.oneofMessage = subMsg2
XCTAssertEqual(msg.oneofMessage.optionalInt32, 0)
XCTAssertEqual(msg.oneofMessage, subMsg2)
if case .oneofMessage(let v)? = msg.o {
XCTAssertEqual(v.optionalInt32, 0)
XCTAssertEqual(v, subMsg2)
} else {
XCTFail("Wasn't the right case")
}
msg.o = nil
// Message with nothing set.
let subMsg3 = ProtobufUnittest_Message3()
msg.oneofMessage = subMsg3
XCTAssertEqual(msg.oneofMessage.optionalInt32, 0)
XCTAssertEqual(msg.oneofMessage, subMsg3)
if case .oneofMessage(let v)? = msg.o {
XCTAssertEqual(v.optionalInt32, 0)
XCTAssertEqual(v, subMsg3)
} else {
XCTFail("Wasn't the right case")
}
}
func testOneofEnum() {
var msg = ProtobufUnittest_Message3()
XCTAssertEqual(msg.oneofEnum, .foo)
XCTAssertNil(msg.o)
msg.oneofEnum = .bar
XCTAssertEqual(msg.oneofEnum, .bar)
XCTAssertEqual(msg.o, .oneofEnum(.bar))
msg.o = nil
XCTAssertEqual(msg.oneofEnum, .foo)
XCTAssertNil(msg.o)
msg.oneofEnum = .foo
XCTAssertEqual(msg.oneofEnum, .foo)
XCTAssertEqual(msg.o, .oneofEnum(.foo))
}
// Chaining. Set each item in the oneof clear the previous one.
func testOneofOnlyOneSet() {
var msg = ProtobufUnittest_Message3()
func assertRightFiledSet(_ i: Int) {
// Make sure the case is correct for the enum based access.
switch msg.o {
case nil:
XCTAssertEqual(i, 0)
case .oneofInt32(let v)?:
XCTAssertEqual(i, 1)
XCTAssertEqual(v, 51)
case .oneofInt64(let v)?:
XCTAssertEqual(i, 2)
XCTAssertEqual(v, 52)
case .oneofUint32(let v)?:
XCTAssertEqual(i, 3)
XCTAssertEqual(v, 53)
case .oneofUint64(let v)?:
XCTAssertEqual(i, 4)
XCTAssertEqual(v, 54)
case .oneofSint32(let v)?:
XCTAssertEqual(i, 5)
XCTAssertEqual(v, 55)
case .oneofSint64(let v)?:
XCTAssertEqual(i, 6)
XCTAssertEqual(v, 56)
case .oneofFixed32(let v)?:
XCTAssertEqual(i, 7)
XCTAssertEqual(v, 57)
case .oneofFixed64(let v)?:
XCTAssertEqual(i, 8)
XCTAssertEqual(v, 58)
case .oneofSfixed32(let v)?:
XCTAssertEqual(i, 9)
XCTAssertEqual(v, 59)
case .oneofSfixed64(let v)?:
XCTAssertEqual(i, 10)
XCTAssertEqual(v, 60)
case .oneofFloat(let v)?:
XCTAssertEqual(i, 11)
XCTAssertEqual(v, 61.0)
case .oneofDouble(let v)?:
XCTAssertEqual(i, 12)
XCTAssertEqual(v, 62.0)
case .oneofBool(let v)?:
XCTAssertEqual(i, 13)
XCTAssertEqual(v, true)
case .oneofString(let v)?:
XCTAssertEqual(i, 14)
XCTAssertEqual(v, "64")
case .oneofBytes(let v)?:
XCTAssertEqual(i, 15)
XCTAssertEqual(v, Data([65]))
// No group.
case .oneofMessage(let v)?:
XCTAssertEqual(i, 17)
XCTAssertEqual(v.optionalInt32, 68)
case .oneofEnum(let v)?:
XCTAssertEqual(i, 18)
XCTAssertEqual(v, .bar)
}
// Check direct field access (gets the right value or the default)
if i == 1 {
XCTAssertEqual(msg.oneofInt32, 51)
} else {
XCTAssertEqual(msg.oneofInt32, 0, "i = \(i)")
}
if i == 2 {
XCTAssertEqual(msg.oneofInt64, 52)
} else {
XCTAssertEqual(msg.oneofInt64, 0, "i = \(i)")
}
if i == 3 {
XCTAssertEqual(msg.oneofUint32, 53)
} else {
XCTAssertEqual(msg.oneofUint32, 0, "i = \(i)")
}
if i == 4 {
XCTAssertEqual(msg.oneofUint64, 54)
} else {
XCTAssertEqual(msg.oneofUint64, 0, "i = \(i)")
}
if i == 5 {
XCTAssertEqual(msg.oneofSint32, 55)
} else {
XCTAssertEqual(msg.oneofSint32, 0, "i = \(i)")
}
if i == 6 {
XCTAssertEqual(msg.oneofSint64, 56)
} else {
XCTAssertEqual(msg.oneofSint64, 0, "i = \(i)")
}
if i == 7 {
XCTAssertEqual(msg.oneofFixed32, 57)
} else {
XCTAssertEqual(msg.oneofFixed32, 0, "i = \(i)")
}
if i == 8 {
XCTAssertEqual(msg.oneofFixed64, 58)
} else {
XCTAssertEqual(msg.oneofFixed64, 0, "i = \(i)")
}
if i == 9 {
XCTAssertEqual(msg.oneofSfixed32, 59)
} else {
XCTAssertEqual(msg.oneofSfixed32, 0, "i = \(i)")
}
if i == 10 {
XCTAssertEqual(msg.oneofSfixed64, 60)
} else {
XCTAssertEqual(msg.oneofSfixed64, 0, "i = \(i)")
}
if i == 11 {
XCTAssertEqual(msg.oneofFloat, 61.0)
} else {
XCTAssertEqual(msg.oneofFloat, 0.0, "i = \(i)")
}
if i == 12 {
XCTAssertEqual(msg.oneofDouble, 62.0)
} else {
XCTAssertEqual(msg.oneofDouble, 0.0, "i = \(i)")
}
if i == 13 {
XCTAssertEqual(msg.oneofBool, true)
} else {
XCTAssertEqual(msg.oneofBool, false, "i = \(i)")
}
if i == 14 {
XCTAssertEqual(msg.oneofString, "64")
} else {
XCTAssertEqual(msg.oneofString, "", "i = \(i)")
}
if i == 15 {
XCTAssertEqual(msg.oneofBytes, Data([65]))
} else {
XCTAssertEqual(msg.oneofBytes, Data(), "i = \(i)")
}
// No group
if i == 17 {
XCTAssertEqual(msg.oneofMessage.optionalInt32, 68)
} else {
XCTAssertEqual(msg.oneofMessage.optionalInt32, 0, "i = \(i)")
}
if i == 18 {
XCTAssertEqual(msg.oneofEnum, .bar)
} else {
XCTAssertEqual(msg.oneofEnum, .foo, "i = \(i)")
}
}
// Now cycle through the cases.
assertRightFiledSet(0)
msg.oneofInt32 = 51
assertRightFiledSet(1)
msg.oneofInt64 = 52
assertRightFiledSet(2)
msg.oneofUint32 = 53
assertRightFiledSet(3)
msg.oneofUint64 = 54
assertRightFiledSet(4)
msg.oneofSint32 = 55
assertRightFiledSet(5)
msg.oneofSint64 = 56
assertRightFiledSet(6)
msg.oneofFixed32 = 57
assertRightFiledSet(7)
msg.oneofFixed64 = 58
assertRightFiledSet(8)
msg.oneofSfixed32 = 59
assertRightFiledSet(9)
msg.oneofSfixed64 = 60
assertRightFiledSet(10)
msg.oneofFloat = 61
assertRightFiledSet(11)
msg.oneofDouble = 62
assertRightFiledSet(12)
msg.oneofBool = true
assertRightFiledSet(13)
msg.oneofString = "64"
assertRightFiledSet(14)
msg.oneofBytes = Data([65])
assertRightFiledSet(15)
// No group
msg.oneofMessage.optionalInt32 = 68
assertRightFiledSet(17)
msg.oneofEnum = .bar
assertRightFiledSet(18)
}
}
| gpl-3.0 | ac3f5dbf038b07cefdf1657124c413d9 | 28.547244 | 80 | 0.635909 | 3.922132 | false | true | false | false |
illescasDaniel/Questions | Questions/ViewControllers/ImageDetailsViewController.swift | 1 | 2896 | //
// ImageDetailsViewController.swift
// Questions
//
// Created by Daniel Illescas Romero on 27/03/2018.
// Copyright © 2018 Daniel Illescas Romero. All rights reserved.
//
import UIKit
class ImageDetailsViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var closeViewButton: UIButton!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet var customPanGesture: UIPanGestureRecognizer!
private var originalBGColor: UIColor {
if #available(iOS 13, *) {
return .secondarySystemBackground
}
return UIColor.themeStyle(dark: .black, light: .white)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = originalBGColor
self.closeViewButton.backgroundColor = .themeStyle(dark: .orange, light: .defaultTintColor)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.navigationController?.navigationBar.tintColor = .themeStyle(dark: .orange, light: .defaultTintColor)
self.view.backgroundColor = originalBGColor
self.closeViewButton.backgroundColor = .themeStyle(dark: .orange, light: .defaultTintColor)
}
// MARK: - Actions
@IBAction func closeViewAction(_ sender: UIButton) {
self.dismiss(animated: true)
}
@IBAction func panGestureOverImageView(_ sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: self.imageView)
self.imageView.transform = CGAffineTransform(translationX: translation.x, y: translation.y)
let translationFromCenter = abs(translation.y / self.view.center.y)
self.view.backgroundColor = self.originalBGColor.withAlphaComponent(1 - translationFromCenter)
if sender.state == .ended {
let velocity = sender.velocity(in: self.imageView)
if translationFromCenter >= 0.8 || abs(velocity.x) > 1000 || abs(velocity.y) > 1000 {
self.dismiss(animated: true)
return
}
UIView.transition(with: self.imageView, duration: 0.15, options: [.curveEaseIn], animations: {
self.imageView.transform = .identity
self.view.backgroundColor = self.originalBGColor
})
}
}
@IBAction func doubleTapToZoomAction(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
let zoomLevel = (self.scrollView.zoomScale > 1.0) ? self.scrollView.minimumZoomScale : 2.0
self.scrollView.setZoomScale(zoomLevel, animated: true)
}
}
override var prefersStatusBarHidden: Bool {
return true
}
}
extension ImageDetailsViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
scrollView.isScrollEnabled = true
if scrollView.zoomScale == 1.0 {
self.customPanGesture.isEnabled = true
} else {
self.customPanGesture.isEnabled = false
}
}
}
| mit | 7209eb9ce17abe4c8c4c40e4b3cd32d4 | 29.15625 | 107 | 0.746459 | 4.135714 | false | false | false | false |
SwiftBond/Bond | Sources/Bond/AppKit/NSProgressIndicator.swift | 2 | 2498 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Tony Arnold (@tonyarnold)
//
// 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.
//
#if os(macOS)
import AppKit
import ReactiveKit
public extension ReactiveExtensions where Base: NSProgressIndicator {
public var isAnimating: Bond<Bool> {
return bond {
if $1 {
$0.startAnimation(nil)
} else {
$0.stopAnimation(nil)
}
}
}
public var doubleValue: Bond<Double> {
return bond { $0.doubleValue = $1 }
}
public var isIndeterminate: Bond<Bool> {
return bond { $0.isIndeterminate = $1 }
}
public var minValue: Bond<Double> {
return bond { $0.minValue = $1 }
}
public var maxValue: Bond<Double> {
return bond { $0.maxValue = $1 }
}
public var controlTint: Bond<NSControlTint> {
return bond { $0.controlTint = $1 }
}
public var controlSize: Bond<NSControl.ControlSize> {
return bond { $0.controlSize = $1 }
}
public var style: Bond<NSProgressIndicator.Style> {
return bond { $0.style = $1 }
}
public var isDisplayedWhenStopped: Bond<Bool> {
return bond { $0.isDisplayedWhenStopped = $1 }
}
}
extension NSProgressIndicator: BindableProtocol {
public func bind(signal: Signal<Double, NoError>) -> Disposable {
return reactive.doubleValue.bind(signal: signal)
}
}
#endif
| mit | 81193b86505cde9e69937359af50a08a | 29.463415 | 81 | 0.664131 | 4.198319 | false | false | false | false |
benlangmuir/swift | test/Concurrency/Runtime/task_creation.swift | 7 | 819 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library)
// REQUIRES: executable_test
// REQUIRES: concurrency
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
enum SomeError: Error {
case bad
}
@available(SwiftStdlib 5.1, *)
@main struct Main {
static func main() async {
let condition = false
let t1 = Task {
return 5
}
let t2 = Task { () -> Int in
if condition {
throw SomeError.bad
}
return 7
}
let t3 = Task.detached {
return 9
}
let t4 = Task.detached { () -> Int in
if condition {
throw SomeError.bad
}
return 11
}
let result = try! await t1.get() + t2.get() + t3.get() + t4.get()
assert(result == 32)
}
}
| apache-2.0 | 2809c0fe517559ad600bd19dd26d41ec | 16.804348 | 94 | 0.58486 | 3.60793 | false | false | false | false |
einsteinx2/iSub | Classes/Data Model/SongRepository.swift | 1 | 13790 | //
// SongRepository.swift
// iSub
//
// Created by Benjamin Baron on 1/15/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
struct SongRepository: ItemRepository {
static let si = SongRepository()
fileprivate let gr = GenericItemRepository.si
let table = "songs"
let cachedTable = "cachedSongs"
let itemIdField = "songId"
func song(songId: Int64, serverId: Int64, loadSubItems: Bool = false) -> Song? {
return gr.item(repository: self, itemId: songId, serverId: serverId, loadSubItems: loadSubItems)
}
func allSongs(serverId: Int64? = nil, isCachedTable: Bool = false, loadSubItems: Bool = false) -> [Song] {
return gr.allItems(repository: self, serverId: serverId, isCachedTable: isCachedTable, loadSubItems: loadSubItems)
}
@discardableResult func deleteAllSongs(serverId: Int64?) -> Bool {
return gr.deleteAllItems(repository: self, serverId: serverId)
}
func isPersisted(song: Song, isCachedTable: Bool = false) -> Bool {
return gr.isPersisted(repository: self, item: song, isCachedTable: isCachedTable)
}
func isPersisted(songId: Int64, serverId: Int64, isCachedTable: Bool = false) -> Bool {
return gr.isPersisted(repository: self, itemId: songId, serverId: serverId, isCachedTable: isCachedTable)
}
func hasCachedSubItems(song: Song) -> Bool {
return gr.hasCachedSubItems(repository: self, item: song)
}
func delete(song: Song, isCachedTable: Bool = false) -> Bool {
return gr.delete(repository: self, item: song, isCachedTable: isCachedTable)
}
func lastPlayed(songId: Int64, serverId: Int64, isCachedTable: Bool = false) -> Date? {
var lastPlayed: Date? = nil
Database.si.read.inDatabase { db in
let table = tableName(repository: self, isCachedTable: isCachedTable)
let query = "SELECT lastPlayed FROM \(table) WHERE songId = ? AND serverId = ?"
lastPlayed = db.dateForQuery(query, songId, serverId)
}
return lastPlayed
}
@discardableResult func deleteRootSongs(mediaFolderId: Int64?, serverId: Int64, isCachedTable: Bool = false) -> Bool {
var success = true
Database.si.read.inDatabase { db in
let table = tableName(repository: self, isCachedTable: isCachedTable)
var query = "DELETE FROM \(table) WHERE folderId IS NULL AND serverId = ?"
do {
if let mediaFolderId = mediaFolderId {
query += " AND mediaFolderId = ?"
try db.executeUpdate(query, serverId, mediaFolderId)
} else {
try db.executeUpdate(query, serverId)
}
} catch {
success = false
printError(error)
}
}
return success
}
func rootSongs(mediaFolderId: Int64?, serverId: Int64, isCachedTable: Bool = false) -> [Song] {
var songs = [Song]()
Database.si.read.inDatabase { db in
let table = tableName(repository: self, isCachedTable: isCachedTable)
var query = "SELECT * FROM \(table) WHERE folderId IS NULL AND serverId = ?"
do {
let result: FMResultSet
if let mediaFolderId = mediaFolderId {
query += " AND mediaFolderId = ?"
result = try db.executeQuery(query, serverId, mediaFolderId)
} else {
result = try db.executeQuery(query, serverId)
}
while result.next() {
let song = Song(result: result)
songs.append(song)
}
result.close()
} catch {
printError(error)
}
}
return songs
}
func songs(albumId: Int64, serverId: Int64, isCachedTable: Bool = false) -> [Song] {
var songs = [Song]()
Database.si.read.inDatabase { db in
let table = tableName(repository: self, isCachedTable: isCachedTable)
let query = "SELECT * FROM \(table) WHERE albumId = ? AND serverId = ?"
do {
let result = try db.executeQuery(query, albumId, serverId)
while result.next() {
let song = Song(result: result)
songs.append(song)
}
result.close()
} catch {
printError(error)
}
}
return songs
}
func songs(folderId: Int64, serverId: Int64, isCachedTable: Bool = false) -> [Song] {
var songs = [Song]()
Database.si.read.inDatabase { db in
let table = tableName(repository: self, isCachedTable: isCachedTable)
let query = "SELECT * FROM \(table) WHERE folderId = ? AND serverId = ?"
do {
let result = try db.executeQuery(query, folderId, serverId)
while result.next() {
let song = Song(result: result)
songs.append(song)
}
result.close()
} catch {
printError(error)
}
}
return songs
}
func replace(song: Song, isCachedTable: Bool = false) -> Bool {
var success = true
Database.si.write.inDatabase { db in
do {
let table = tableName(repository: self, isCachedTable: isCachedTable)
let query = "REPLACE INTO \(table) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
try db.executeUpdate(query, song.songId, song.serverId, song.contentTypeId, n2N(song.transcodedContentTypeId), n2N(song.mediaFolderId), n2N(song.folderId), n2N(song.artistId), n2N(song.albumId), n2N(song.genreId), n2N(song.coverArtId), song.title, n2N(song.duration), n2N(song.bitRate), n2N(song.trackNumber), n2N(song.discNumber), n2N(song.year), song.size, song.path, n2N(song.lastPlayed), n2N(song.artistName), n2N(song.albumName))
} catch {
success = false
printError(error)
}
}
return success
}
func loadSubItems(song: Song) {
if let folderId = song.folderId {
song.folder = FolderRepository.si.folder(folderId: folderId, serverId: song.serverId)
}
if let artistId = song.artistId {
song.artist = ArtistRepository.si.artist(artistId: artistId, serverId: song.serverId)
}
if let albumId = song.albumId {
song.album = AlbumRepository.si.album(albumId: albumId, serverId: song.serverId)
}
if let genreId = song.genreId {
song.genre = GenreRepository.si.genre(genreId: genreId)
}
song.contentType = ContentTypeRepository.si.contentType(contentTypeId: song.contentTypeId)
if let transcodedContentTypeId = song.transcodedContentTypeId {
song.transcodedContentType = ContentTypeRepository.si.contentType(contentTypeId: transcodedContentTypeId)
}
}
}
extension Song {
var isFullyCached: Bool {
get {
let query = "SELECT fullyCached FROM cachedSongsMetadata WHERE songId = ? AND serverId = ?"
return Database.si.read.boolForQuery(query, songId, serverId)
}
set {
// TODO: Handle pinned column
Database.si.write.inDatabase { db in
let query = "REPLACE INTO cachedSongsMetadata VALUES (?, ?, ?, ?, ?)"
try? db.executeUpdate(query, self.songId, self.serverId, false, true, false)
}
// Add subItems to cache db
loadSubItems()
folder?.cache()
artist?.cache()
album?.cache()
cache()
}
}
var isPartiallyCached: Bool {
get {
let query = "SELECT partiallyCached FROM cachedSongsMetadata WHERE songId = ? AND serverId = ?"
return Database.si.read.boolForQuery(query, songId, serverId)
}
set {
// TODO: Handle pinned column
Database.si.write.inDatabase { db in
let query = "REPLACE INTO cachedSongsMetadata VALUES (?, ?, ?, ?, ?)"
try? db.executeUpdate(query, self.songId, self.serverId, true, false, false)
}
}
}
}
extension Song: PersistedItem {
convenience init(result: FMResultSet, repository: ItemRepository = SongRepository.si) {
let songId = result.longLongInt(forColumnIndex: 0)
let serverId = result.longLongInt(forColumnIndex: 1)
let contentTypeId = result.longLongInt(forColumnIndex: 2)
let transcodedContentTypeId = result.object(forColumnIndex: 3) as? Int64
let mediaFolderId = result.object(forColumnIndex: 4) as? Int64
let folderId = result.object(forColumnIndex: 5) as? Int64
let artistId = result.object(forColumnIndex: 6) as? Int64
let albumId = result.object(forColumnIndex: 7) as? Int64
let genreId = result.object(forColumnIndex: 8) as? Int64
let coverArtId = result.string(forColumnIndex: 9)
let title = result.string(forColumnIndex: 10) ?? ""
let duration = result.object(forColumnIndex: 11) as? Int
let bitRate = result.object(forColumnIndex: 12) as? Int
let trackNumber = result.object(forColumnIndex: 13) as? Int
let discNumber = result.object(forColumnIndex: 14) as? Int
let year = result.object(forColumnIndex: 15) as? Int
let size = result.longLongInt(forColumnIndex: 16)
let path = result.string(forColumnIndex: 17) ?? ""
let lastPlayed = result.date(forColumnIndex: 18)
let artistName = result.string(forColumnIndex: 19)
let albumName = result.string(forColumnIndex: 20)
let repository = repository as! SongRepository
// Preload genre object
var genre: Genre?
if let genreId = genreId, let maybeGenre = GenreRepository.si.genre(genreId: genreId) {
genre = maybeGenre
}
// Preload content type objects
let contentType = ContentTypeRepository.si.contentType(contentTypeId: contentTypeId)
var transcodedContentType: ContentType? = nil
if let transcodedContentTypeId = transcodedContentTypeId {
transcodedContentType = ContentTypeRepository.si.contentType(contentTypeId: transcodedContentTypeId)
}
self.init(songId: songId, serverId: serverId, contentTypeId: contentTypeId, transcodedContentTypeId: transcodedContentTypeId, mediaFolderId: mediaFolderId, folderId: folderId, artistId: artistId, artistName: artistName, albumId: albumId, albumName: albumName, genreId: genreId, coverArtId: coverArtId, title: title, duration: duration, bitRate: bitRate, trackNumber: trackNumber, discNumber: discNumber, year: year, size: size, path: path, lastPlayed: lastPlayed, genre: genre, contentType: contentType, transcodedContentType: transcodedContentType, repository: repository)
}
class func item(itemId: Int64, serverId: Int64, repository: ItemRepository = SongRepository.si) -> Item? {
return (repository as? SongRepository)?.song(songId: itemId, serverId: serverId)
}
var isPersisted: Bool {
return repository.isPersisted(song: self)
}
var hasCachedSubItems: Bool {
return repository.hasCachedSubItems(song: self)
}
@discardableResult func replace() -> Bool {
return repository.replace(song: self)
}
@discardableResult func cache() -> Bool {
return repository.replace(song: self, isCachedTable: true)
}
@discardableResult func delete() -> Bool {
return repository.delete(song: self)
}
@discardableResult func deleteCache() -> Bool {
var success = true
Database.si.write.inDatabase { db in
var queries = [String]()
// Remove the metadata entry
queries.append("DELETE FROM cachedSongsMetadata WHERE songId = ? AND serverId = ?")
// Remove the song table entry
queries.append("DELETE FROM cachedSongs WHERE songId = ? AND serverId = ?")
// Remove artist/album/folder entries if no other songs reference them
queries.append("DELETE FROM cachedFolders WHERE NOT EXISTS (SELECT 1 FROM cachedSongs WHERE folderId = cachedFolders.folderId AND serverId = cachedFolders.serverId)")
queries.append("DELETE FROM cachedArtists WHERE NOT EXISTS (SELECT 1 FROM cachedSongs WHERE artistId = cachedArtists.artistId AND serverId = cachedArtists.serverId)")
queries.append("DELETE FROM cachedAlbums WHERE NOT EXISTS (SELECT 1 FROM cachedSongs WHERE albumId = cachedAlbums.albumId AND serverId = cachedAlbums.serverId)")
for query in queries {
do {
try db.executeUpdate(query, self.songId, self.serverId)
} catch {
success = false
printError(error)
}
}
}
return success
}
func loadSubItems() {
repository.loadSubItems(song: self)
}
}
| gpl-3.0 | 14c2c1a01000a53c8256be16303b1044 | 43.054313 | 581 | 0.58844 | 4.94939 | false | false | false | false |
dogo/AKSideMenu | Sources/AKSideMenu/UIViewController+AKSideMenu.swift | 1 | 1187 | //
// UIViewController+AKSideMenu.swift
// AKSideMenu
//
// Created by Diogo Autilio on 6/3/16.
// Copyright © 2016 AnyKey Entertainment. All rights reserved.
//
import UIKit
// MARK: - UIViewController+AKSideMenu
extension UIViewController {
public var sideMenuViewController: AKSideMenu? {
guard var iterator = self.parent else { return nil }
guard let strClass = String(describing: type(of: iterator)).components(separatedBy: ".").last else { return nil }
while strClass != nibName {
if iterator is AKSideMenu {
return iterator as? AKSideMenu
} else if let parent = iterator.parent, parent != iterator {
iterator = parent
} else {
break
}
}
return nil
}
// MARK: - Public
// MARK: - IBAction Helper methods
@IBAction public func presentLeftMenuViewController(_ sender: AnyObject) {
self.sideMenuViewController?.presentLeftMenuViewController()
}
@IBAction public func presentRightMenuViewController(_ sender: AnyObject) {
self.sideMenuViewController?.presentRightMenuViewController()
}
}
| mit | c102c63d9851b94d50c365aea764bfda | 27.926829 | 121 | 0.641653 | 5.046809 | false | false | false | false |
oyvind-hauge/OHCircleSegue | OHCircleSegue/OHCircleSegue.swift | 1 | 5538 | //
// OHCircleSegue.swift
// OHCircleSegue
//
// Created by Øyvind Hauge on 10/01/16.
// Copyright © 2016 Øyvind Hauge. All rights reserved.
//
import UIKit
class OHCircleSegue: UIStoryboardSegue, CAAnimationDelegate {
private static let expandDur: CFTimeInterval = 0.35 // Change to make transition faster/slower
private static let contractDur: CFTimeInterval = 0.15 // Change to make transition faster/slower
private static let stack = Stack()
private static var isAnimating = false
var circleOrigin: CGPoint
private var shouldUnwind: Bool
override init(identifier: String?, source: UIViewController, destination: UIViewController) {
// By default, transition starts from the center of the screen,
// so let's find the center when segue is first initialized
let centerX = UIScreen.main.bounds.width*0.5
let centerY = UIScreen.main.bounds.height*0.5
let centerOfScreen = CGPoint(x:centerX, y:centerY)
// Initialize properties
circleOrigin = centerOfScreen
shouldUnwind = false
super.init(identifier: identifier, source: source, destination: destination)
}
override func perform() {
if OHCircleSegue.isAnimating {
return
}
if OHCircleSegue.stack.peek() !== destination {
OHCircleSegue.stack.push(vc: source)
} else {
OHCircleSegue.stack.pop()
shouldUnwind = true
}
let sourceView = source.view as UIView!
let destView = destination.view as UIView!
// Add source (or destination) controller's view to the main application
// window depending of if this is a normal or unwind segue
let window = UIApplication.shared.keyWindow
if !shouldUnwind {
window?.insertSubview(destView!, aboveSubview: sourceView!)
} else {
window?.insertSubview(destView!, at:0)
}
let paths = startAndEndPaths(shouldUnwind: !shouldUnwind)
// Create circle mask and apply it to the view of the destination controller
let mask = CAShapeLayer()
mask.anchorPoint = CGPoint(x: 0.5, y: 0.5)
mask.position = circleOrigin
mask.path = paths.start
(shouldUnwind ? sourceView : destView)?.layer.mask = mask
// Call method for creating animation and add it to the view's mask
(shouldUnwind ? sourceView : destView)?.layer.mask?.add(scalingAnimation(destinationPath: paths.end), forKey: nil)
}
// MARK: Animation delegate
func animationDidStart(_ anim: CAAnimation) {
OHCircleSegue.isAnimating = true
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
OHCircleSegue.isAnimating = false
if !shouldUnwind {
source.present(destination, animated: false, completion: nil)
} else {
source.dismiss(animated: false, completion: nil)
}
}
// MARK: Helper methods
private func scalingAnimation(destinationPath: CGPath) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "path")
animation.toValue = destinationPath
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeBoth
animation.duration = shouldUnwind ? OHCircleSegue.contractDur : OHCircleSegue.expandDur
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.delegate = self
return animation
}
private func startAndEndPaths(shouldUnwind: Bool) -> (start: CGPath, end: CGPath) {
// The hypothenuse is the diagonal of the screen. Further, we use this diagonal as
// the diameter of the big circle. This way we are always certain that the big circle
// will cover the whole screen.
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height
let rw = width + fabs(width/2 - circleOrigin.x)
let rh = height + fabs(height/2 - circleOrigin.y)
let h1 = hypot(width/2 - circleOrigin.x, height/2 - circleOrigin.y)
let hyp = CGFloat(sqrtf(powf(Float(rw), 2) + powf(Float(rh), 2)))
let dia = h1 + hyp
// The two circle sizes we will animate to/from
let path1 = UIBezierPath(ovalIn: CGRect.zero).cgPath
let path2 = UIBezierPath(ovalIn: CGRect(x:-dia/2, y:-dia/2, width:dia, height:dia)).cgPath
// If shouldUnwind flag is true, we should go from big to small circle, or else go from small to big
return shouldUnwind ? (path1, path2) : (path2, path1)
}
// MARK: Stack implementation
// Simple stack implementation for keeping track of our view controllers
private class Stack {
private var stackArray = Array<UIViewController>()
private var size: Int {
get {
return stackArray.count
}
}
func push(vc: UIViewController) {
stackArray.append(vc)
}
func pop() -> UIViewController? {
if let last = stackArray.last {
stackArray.removeLast()
return last
}
return nil
}
func peek() -> UIViewController? {
return stackArray.last
}
}
}
| mit | a44e42a99b4690a7132f94c70196c281 | 35.414474 | 122 | 0.618428 | 5.045579 | false | false | false | false |
OpenStreetMap-Monitoring/OsMoiOs | iOsmo/ChatMessage.swift | 2 | 810 | //
// ChatMessage.swift
// iOsMo
//
// Created by Alexey Sirotkin on 03.03.2019.
// Copyright © 2019 Alexey Sirotkin. All rights reserved.
//
import Foundation
class ChatMessage : NSObject {
var time: Date;
var text: String;
var user: String;
init(json: Dictionary<String, AnyObject>) {
self.text = json["text"] as? String ?? ""
self.user = json["name"] as? String ?? ""
let uTime = (json["time"] as? Double) ?? atof(json["time"] as? String ?? "0")
if uTime > 0 {
self.time = Date(timeIntervalSince1970: uTime)
} else {
self.time = Date()
}
}
init(text:String) {
self.text = text;
self.time = Date()
self.user = SettingsManager.getKey(SettingKeys.user)! as String
}
}
| gpl-3.0 | 3b604b8b0bb2bbd4956896db1393564d | 24.28125 | 86 | 0.559951 | 3.644144 | false | false | false | false |
Mozharovsky/BouncingMenu-iOS-8 | Bouncing Menu/ViewController.swift | 1 | 2049 | //
// ViewController.swift
// Bouncing Menu
//
// Created by E. Mozharovsky on 10/18/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class ViewController: UIViewController, BouncingMenuDelegate {
var bouncingMenuController: BouncingMenuViewController?
var offstageAlpha = 0.6 as CGFloat
var offstageBackground = UIColor.blackColor()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.groupTableViewBackgroundColor()
self.bouncingMenuController = BouncingMenuViewController(delegate: self, enabledOffstage: EnabledOffstage.DefaultOffstage)
}
@IBAction func tapped() {
if self.bouncingMenuController?.isOffstagePresenting == false {
self.bouncingMenuController?.invokeBouncingMenu(0.5)
} else {
self.bouncingMenuController?.withdrawBouncingMenu(0.5)
}
}
// MARK:- Bouncing menu delegate
func offstageTouched() {
self.bouncingMenuController?.withdrawBouncingMenu(0.5)
}
func numberOfSections(tableView: UITableView) -> Int {
return 1
}
func totalCountOfRows() -> Int {
return 3
}
func numberOfRows(tableView: UITableView, section: Int) -> Int {
return 3
}
func tableViewHeight() -> CGFloat {
return 150
}
func bouncingMenu(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.bouncingMenuController!.identifier) as UITableViewCell
cell.textLabel?.text = "Menu Item #\(cellForRowAtIndexPath.row)"
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
func rowSelected(tableView: UITableView, indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.bouncingMenuController?.withdrawBouncingMenu(0.5)
}
} | mit | 54bda0114d76f05ec15dbb05017a6f05 | 29.597015 | 130 | 0.673987 | 5.30829 | false | false | false | false |
ZhangMingNan/MNMeiTuan | 15-MeiTuan/Alamofire-master/Source/Manager.swift | 2 | 21069 | // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
:returns: The default header values.
*/
public static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see http://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see http://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as! [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return join(",", components)
}()
// User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString as! String
}
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// The session delegate handling all the task and session delegate callbacks.
public let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/// The background completion handler closure provided by the UIApplicationDelegate `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation will automatically call the handler. If you need to handle your own events before the handler is called, then you need to override the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. `nil` by default.
public var backgroundCompletionHandler: (() -> Void)?
// MARK: - Lifecycle
/**
:param: configuration The configuration used to construct the managed session.
*/
required public init(configuration: NSURLSessionConfiguration? = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
self.delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
if let strongSelf = self {
strongSelf.backgroundCompletionHandler?()
}
}
}
deinit {
self.session.invalidateAndCancel()
}
// MARK: - Request
/**
Creates a request for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:param: headers The HTTP headers. `nil` by default.
:returns: The created request.
*/
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask?
dispatch_sync(queue) {
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
}
let request = Request(session: session, task: dataTask!)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: - SessionDelegate
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) {
subdelegate = self.subdelegates[task.taskIdentifier]
}
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
}
// MARK: - NSURLSessionDelegate
// MARK: Override Closures
/// NSURLSessionDelegate override closure for `URLSession:didBecomeInvalidWithError:` method.
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
/// NSURLSessionDelegate override closure for `URLSession:didReceiveChallenge:completionHandler:` method.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
/// NSURLSessionDelegate override closure for `URLSessionDidFinishEventsForBackgroundURLSession:` method.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
// MARK: Delegate Methods
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
if let sessionDidReceiveChallenge = self.sessionDidReceiveChallenge {
completionHandler(sessionDidReceiveChallenge(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
public func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = self.taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
if let taskDidReceiveChallenge = self.taskDidReceiveChallenge {
completionHandler(taskDidReceiveChallenge(session, task, challenge))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
if let taskNeedNewBodyStream = self.taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let taskDidSendBodyData = self.taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidComplete = self.taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
// MARK: Delegate Methods
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = self.dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
if let dataTaskDidBecomeDownloadTask = self.dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = self.dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
if let dataTaskWillCacheResponse = self.dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler)
} else {
completionHandler(proposedResponse)
}
}
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let downloadTaskDidFinishDownloadingToURL = self.downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
}
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let downloadTaskDidWriteData = self.downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
}
public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let downloadTaskDidResumeAtOffset = self.downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
}
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
| apache-2.0 | b86258a5dadf84649075c47c08633b29 | 49.886473 | 563 | 0.695305 | 6.355053 | false | false | false | false |
rudkx/swift | stdlib/public/core/StringCharacterView.swift | 1 | 9692 | //===--- StringCharacterView.swift - String's Collection of Characters ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// String is-not-a Sequence or Collection, but it exposes a
// collection of characters.
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#70 : The character string view should have a custom iterator type
// to allow performance optimizations of linear traversals.
import SwiftShims
extension String: BidirectionalCollection {
public typealias SubSequence = Substring
public typealias Element = Character
/// The position of the first character in a nonempty string.
///
/// In an empty string, `startIndex` is equal to `endIndex`.
@inlinable @inline(__always)
public var startIndex: Index { return _guts.startIndex }
/// A string's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// In an empty string, `endIndex` is equal to `startIndex`.
@inlinable @inline(__always)
public var endIndex: Index { return _guts.endIndex }
/// The number of characters in a string.
@inline(__always)
public var count: Int {
return distance(from: startIndex, to: endIndex)
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Index) -> Index {
_precondition(i < endIndex, "String index is out of bounds")
// TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.
let i = _guts.scalarAlign(i)
let stride = _characterStride(startingAt: i)
let nextOffset = i._encodedOffset &+ stride
let nextStride = _characterStride(
startingAt: Index(_encodedOffset: nextOffset)._scalarAligned)
return Index(
encodedOffset: nextOffset, characterStride: nextStride)._scalarAligned
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Index) -> Index {
// TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.
// Note: bounds checking in `index(before:)` is tricky as scalar aligning an
// index may need to access storage, but it may also move it closer towards
// the `startIndex`. Therefore, we must check against the `endIndex` before
// aligning, but we need to delay the `i > startIndex` check until after.
_precondition(i <= endIndex, "String index is out of bounds")
let i = _guts.scalarAlign(i)
_precondition(i > startIndex, "String index is out of bounds")
let stride = _characterStride(endingAt: i)
let priorOffset = i._encodedOffset &- stride
return Index(
encodedOffset: priorOffset, characterStride: stride)._scalarAligned
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Returns: An index offset by `distance` from the index `i`. If
/// `distance` is positive, this is the same value as the result of
/// `distance` calls to `index(after:)`. If `distance` is negative, this
/// is the same value as the result of `abs(distance)` calls to
/// `index(before:)`.
/// - Complexity: O(*n*), where *n* is the absolute value of `distance`.
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy distance: Int) -> Index {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _index(i, offsetBy: distance)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If
/// `distance > 0`, a limit that is less than `i` has no effect.
/// Likewise, if `distance < 0`, a limit that is greater than `i` has no
/// effect.
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the absolute value of `distance`.
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _index(i, offsetBy: distance, limitedBy: limit)
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
///
/// - Complexity: O(*n*), where *n* is the resulting distance.
@inlinable @inline(__always)
public func distance(from start: Index, to end: Index) -> Int {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _distance(from: _guts.scalarAlign(start), to: _guts.scalarAlign(end))
}
/// Accesses the character at the given position.
///
/// You can use the same indices for subscripting a string and its substring.
/// For example, this code finds the first letter after the first space:
///
/// let str = "Greetings, friend! How are you?"
/// let firstSpace = str.firstIndex(of: " ") ?? str.endIndex
/// let substr = str[firstSpace...]
/// if let nextCapital = substr.firstIndex(where: { $0 >= "A" && $0 <= "Z" }) {
/// print("Capital after a space: \(str[nextCapital])")
/// }
/// // Prints "Capital after a space: H"
///
/// - Parameter i: A valid index of the string. `i` must be less than the
/// string's end index.
@inlinable @inline(__always)
public subscript(i: Index) -> Character {
_boundsCheck(i)
let i = _guts.scalarAlign(i)
let distance = _characterStride(startingAt: i)
return _guts.errorCorrectedCharacter(
startingAt: i._encodedOffset, endingAt: i._encodedOffset &+ distance)
}
@inlinable @inline(__always)
internal func _characterStride(startingAt i: Index) -> Int {
_internalInvariant_5_1(i._isScalarAligned)
// Fast check if it's already been measured, otherwise check resiliently
if let d = i.characterStride { return d }
if i == endIndex { return 0 }
return _guts._opaqueCharacterStride(startingAt: i._encodedOffset)
}
@inlinable @inline(__always)
internal func _characterStride(endingAt i: Index) -> Int {
_internalInvariant_5_1(i._isScalarAligned)
if i == startIndex { return 0 }
return _guts._opaqueCharacterStride(endingAt: i._encodedOffset)
}
}
extension String {
@frozen
public struct Iterator: IteratorProtocol, Sendable {
@usableFromInline
internal var _guts: _StringGuts
@usableFromInline
internal var _position: Int = 0
@usableFromInline
internal var _end: Int
@inlinable
internal init(_ guts: _StringGuts) {
self._end = guts.count
self._guts = guts
}
@inlinable
public mutating func next() -> Character? {
guard _fastPath(_position < _end) else { return nil }
let len = _guts._opaqueCharacterStride(startingAt: _position)
let nextPosition = _position &+ len
let result = _guts.errorCorrectedCharacter(
startingAt: _position, endingAt: nextPosition)
_position = nextPosition
return result
}
}
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_guts)
}
}
| apache-2.0 | 4644ac2d008b27e926362a868c0fbd51 | 36.420849 | 85 | 0.647132 | 4.190229 | false | false | false | false |
danielmartinprieto/AudioPlayer | AudioPlayer/AudioPlayer/player/extensions/AudioPlayer+PlayerEvent.swift | 1 | 5463 | //
// AudioPlayer+PlayerEvent.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 03/04/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import CoreMedia
extension AudioPlayer {
/// Handles player events.
///
/// - Parameters:
/// - producer: The event producer that generated the player event.
/// - event: The player event.
func handlePlayerEvent(from producer: EventProducer, with event: PlayerEventProducer.PlayerEvent) {
switch event {
case .endedPlaying(let error):
if let error = error {
state = .failed(.foundationError(error))
} else {
nextOrStop()
}
case .interruptionBegan where state.isPlaying || state.isBuffering:
//We pause the player when an interruption is detected
backgroundHandler.beginBackgroundTask()
pausedForInterruption = true
pause()
case .interruptionEnded(let shouldResume) where pausedForInterruption:
if resumeAfterInterruption && shouldResume {
resume()
}
pausedForInterruption = false
backgroundHandler.endBackgroundTask()
case .loadedDuration(let time):
if let currentItem = currentItem, let time = time.ap_timeIntervalValue {
updateNowPlayingInfoCenter()
delegate?.audioPlayer(self, didFindDuration: time, for: currentItem)
}
case .loadedMetadata(let metadata):
if let currentItem = currentItem, !metadata.isEmpty {
currentItem.parseMetadata(metadata)
delegate?.audioPlayer(self, didUpdateEmptyMetadataOn: currentItem, withData: metadata)
}
case .loadedMoreRange:
if let currentItem = currentItem, let currentItemLoadedRange = currentItemLoadedRange {
delegate?.audioPlayer(self, didLoad: currentItemLoadedRange, for: currentItem)
if bufferingStrategy == .playWhenPreferredBufferDurationFull && state == .buffering,
let currentItemLoadedAhead = currentItemLoadedAhead,
currentItemLoadedAhead.isNormal,
currentItemLoadedAhead >= self.preferredBufferDurationBeforePlayback {
playImmediately()
}
}
case .progressed(let time):
if let currentItemProgression = time.ap_timeIntervalValue, let item = player?.currentItem,
item.status == .readyToPlay {
//This fixes the behavior where sometimes the `playbackLikelyToKeepUp` isn't
//changed even though it's playing (happens mostly at the first play though).
if state.isBuffering || state.isPaused {
if shouldResumePlaying {
stateBeforeBuffering = nil
state = .playing
player?.rate = rate
} else {
player?.rate = 0
state = .paused
}
backgroundHandler.endBackgroundTask()
}
//Then we can call the didUpdateProgressionTo: delegate method
let itemDuration = currentItemDuration ?? 0
let percentage = (itemDuration > 0 ? Float(currentItemProgression / itemDuration) * 100 : 0)
delegate?.audioPlayer(self, didUpdateProgressionTo: currentItemProgression, percentageRead: percentage)
}
case .readyToPlay:
//There is enough data in the buffer
if shouldResumePlaying {
stateBeforeBuffering = nil
state = .playing
player?.rate = rate
playImmediately()
} else {
player?.rate = 0
state = .paused
}
//TODO: where to start?
retryEventProducer.stopProducingEvents()
backgroundHandler.endBackgroundTask()
case .routeChanged:
//In some route changes, the player pause automatically
//TODO: there should be a check if state == playing
if let currentItemTimebase = player?.currentItem?.timebase, CMTimebaseGetRate(currentItemTimebase) == 0 {
state = .paused
}
case .sessionMessedUp:
#if os(iOS) || os(tvOS)
//We reenable the audio session directly in case we're in background
setAudioSession(active: true)
//Aaaaand we: restart playing/go to next
state = .stopped
qualityAdjustmentEventProducer.interruptionCount += 1
retryOrPlayNext()
#endif
case .startedBuffering:
//The buffer is empty and player is loading
if case .playing = state, !qualityIsBeingChanged {
qualityAdjustmentEventProducer.interruptionCount += 1
}
stateBeforeBuffering = state
if reachability.isReachable() || (currentItem?.soundURLs[currentQuality]?.ap_isOfflineURL ?? false) {
state = .buffering
} else {
state = .waitingForConnection
}
backgroundHandler.beginBackgroundTask()
default:
break
}
}
}
| mit | 6945704eb99203e5793d1a4d8ce3cda2 | 38.57971 | 119 | 0.571219 | 5.86681 | false | false | false | false |
ios-ximen/DYZB | 斗鱼直播/Pods/Kingfisher/Sources/Filter.swift | 143 | 5475 | //
// Filter.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/31.
//
// Copyright (c) 2017 Wei Wang <[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 CoreImage
import Accelerate
// Reuse the same CI Context for all CI drawing.
private let ciContext = CIContext(options: nil)
/// Transformer method which will be used in to provide a `Filter`.
public typealias Transformer = (CIImage) -> CIImage?
/// Supply a filter to create an `ImageProcessor`.
public protocol CIImageProcessor: ImageProcessor {
var filter: Filter { get }
}
extension CIImageProcessor {
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.apply(filter)
case .data(_):
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Wrapper for a `Transformer` of CIImage filters.
public struct Filter {
let transform: Transformer
public init(tranform: @escaping Transformer) {
self.transform = tranform
}
/// Tint filter which will apply a tint color to images.
public static var tint: (Color) -> Filter = {
color in
Filter { input in
let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
let colorImage = colorFilter.outputImage
let filter = CIFilter(name: "CISourceOverCompositing")!
filter.setValue(colorImage, forKey: kCIInputImageKey)
filter.setValue(input, forKey: kCIInputBackgroundImageKey)
return filter.outputImage?.cropping(to: input.extent)
}
}
public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
/// Color control filter which will apply color control change to images.
public static var colorControl: (ColorElement) -> Filter = {
brightness, contrast, saturation, inputEV in
Filter { input in
let paramsColor = [kCIInputBrightnessKey: brightness,
kCIInputContrastKey: contrast,
kCIInputSaturationKey: saturation]
let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor)
let paramsExposure = [kCIInputEVKey: inputEV]
return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure)
}
}
}
extension Kingfisher where Base: Image {
/// Apply a `Filter` containing `CIImage` transformer to `self`.
///
/// - parameter filter: The filter used to transform `self`.
///
/// - returns: A transformed image by input `Filter`.
///
/// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
public func apply(_ filter: Filter) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
return base
}
let inputImage = CIImage(cgImage: cgImage)
guard let outputImage = filter.transform(inputImage) else {
return base
}
guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
assertionFailure("[Kingfisher] Can not make an tint image within context.")
return base
}
#if os(macOS)
return fixedForRetinaPixel(cgImage: result, to: size)
#else
return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
#endif
}
}
public extension Image {
/// Apply a `Filter` containing `CIImage` transformer to `self`.
///
/// - parameter filter: The filter used to transform `self`.
///
/// - returns: A transformed image by input `Filter`.
///
/// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.apply` instead.",
renamed: "kf.apply")
public func kf_apply(_ filter: Filter) -> Image {
return kf.apply(filter)
}
}
| mit | 7c4878b5e894888d2d03daf5a13c25ab | 36.758621 | 118 | 0.658995 | 4.785839 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Pods/MobilePlayer/MobilePlayer/Config/ElementConfig.swift | 1 | 4187 | //
// ElementConfig.swift
// MobilePlayer
//
// Created by Baris Sencan on 9/17/15.
// Copyright (c) 2015 MovieLaLa. All rights reserved.
//
import Foundation
/// Determines the type of an element.
public enum ElementType: String {
/// Element type is unknown, it won't be added to the UI hierarchy.
case Unknown = "unknown"
/// Element is a label.
case Label = "label"
/// Element is a button.
case Button = "button"
/// Element is a button that can be toggled between two states. (e.g. Play/pause button)
case ToggleButton = "toggleButton"
/// Element is a slider.
case Slider = "slider"
}
/// Determines how an element's width will be calculated.
public enum ElementWidthCalculation: String {
/// Element width will always be as defined in its `width` property.
case AsDefined = "asDefined"
/// Element width will be adjusted to fit its contents.
case Fit = "fit"
/// Element width will be adjusted to fill the remaining horizontal space in its container.
case Fill = "fill"
}
/// Holds basic element configuration values.
public class ElementConfig {
/// Type of the element. Default value is `.Unknown`.
public let type: ElementType
/// Identifier of the element.
///
/// * Special identifiers are:
/// * Labels
/// * "title"
/// * "currentTime"
/// * "remainingTime"
/// * "duration"
/// * Buttons
/// * "close"
/// * "action"
/// * Toggle Buttons
/// * "play"
/// * Sliders
/// * "playback"
public let identifier: String?
/// How the width of the element will be calculated. Default value is `.Fill` for title label and playback slider,
/// `.Fit` for other labels, and `.AsDefined` for the rest.
public let widthCalculation: ElementWidthCalculation
/// Element width, effective only if `widthCalculation` is set to `.AsDefined`. Default value is `40`.
public let width: CGFloat
/// The horizontal space to the left of this element that will be left empty. Default value is `0`.
public let marginLeft: CGFloat
/// The horizontal space to the right of this element that will be left empty. Default value is `0`.
public let marginRight: CGFloat
/// Initializes using default values.
public convenience init() {
self.init(dictionary: [String: Any]())
}
/// Initializes using a dictionary.
///
/// * Key for `type` is `"type"` and its value should be a raw `ElementType` enum value.
/// * Key for `identifier` is `"identifier"` and its value should be a string.
/// * Key for `widthCalculation` is `"widthCalculation"` and its value should be a raw `ElementWidthCalculation` enum
/// value.
/// * Key for `width` is `"width"` and its value should be a number.
/// * Key for `marginLeft` is `"marginLeft"` and its value should be a number.
/// * Key for `marginRight` is `"marginRight"` and its value should be a number.
///
/// - parameters:
/// - dictionary: Element configuration dictionary.
public init(dictionary: [String: Any]) {
// Values need to be AnyObject for type conversions to work correctly.
let dictionary = dictionary as [String: AnyObject]
if
let elementTypeString = dictionary["type"] as? String,
let elementType = ElementType(rawValue: elementTypeString) {
type = elementType
} else {
type = .Unknown
}
let id = dictionary["identifier"] as? String
self.identifier = id
let isTitleLabel = (type == .Label && id == "title")
let isPlaybackSlider = (type == .Slider && id == "playback")
if
let elementWidthCalculationString = dictionary["widthCalculation"] as? String,
let elementWidthCalculation = ElementWidthCalculation(rawValue: elementWidthCalculationString) {
widthCalculation = elementWidthCalculation
} else if isTitleLabel || isPlaybackSlider {
widthCalculation = .Fill
} else if type == .Label {
widthCalculation = .Fit
} else {
widthCalculation = .AsDefined
}
width = (dictionary["width"] as? CGFloat) ?? 40
marginLeft = (dictionary["marginLeft"] as? CGFloat) ?? 0
marginRight = (dictionary["marginRight"] as? CGFloat) ?? 0
}
}
| mit | 291c2a05878c3c33cf7eebe29fa866ff | 31.457364 | 119 | 0.662766 | 4.307613 | false | false | false | false |
darrinhenein/firefox-ios | Storage/StorageTests/TestReadingListTable.swift | 3 | 4927 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCTest
class TestReadingListTable: XCTestCase {
var db: SwiftData!
var readingListTable: ReadingListTable<ReadingListItem>!
override func setUp() {
let files = MockFiles()
files.remove("TestReadingListTable.db")
db = SwiftData(filename: files.get("TestReadingListTable.db")!)
readingListTable = ReadingListTable<ReadingListItem>()
db.withConnection(SwiftData.Flags.ReadWriteCreate, cb: { (db) -> NSError? in
XCTAssertTrue(self.readingListTable.create(db, version: 1))
return nil
})
}
func testInsertQueryDelete() {
// Insert some entries, make sure they got ids
let items = [
ReadingListItem(url: "http://one.com", title: "One"),
ReadingListItem(url: "http://two.com", title: "Two"),
ReadingListItem(url: "http://thr.com", title: "Thr")
]
var insertedItems = [ReadingListItem]()
for item in items {
let r = addItem(item)
XCTAssertNil(r.error)
XCTAssertNotNil(r.item.id)
insertedItems.append(r.item)
}
// Retrieve them, make sure they are equal
db.withConnection(.ReadOnly, cb: { (connection) -> NSError? in
var cursor = self.readingListTable.query(connection, options: nil)
XCTAssertEqual(cursor.status, CursorStatus.Success)
XCTAssertEqual(cursor.count, 3)
for index in 0..<cursor.count {
if let item = cursor[index] as? ReadingListItem {
XCTAssertEqual(item.id!, insertedItems[countElements(insertedItems)-index-1].id!)
XCTAssertEqual(item.clientLastModified, insertedItems[countElements(insertedItems)-index-1].clientLastModified)
} else {
XCTFail("Did not get a ReadingListItem back (nil or wrong type)")
}
}
return nil
})
// Delete them, make sure they are gone
db.withConnection(.ReadWrite, cb: { (connection) -> NSError? in
for item in insertedItems {
var error: NSError?
self.readingListTable.delete(connection, item: item, err: &error)
XCTAssertNil(error)
}
return nil
})
db.withConnection(.ReadOnly, cb: { (connection) -> NSError? in
var cursor = self.readingListTable.query(connection, options: nil)
XCTAssertEqual(cursor.status, CursorStatus.Success)
XCTAssertEqual(cursor.count, 0)
return nil
})
}
func testUpdate() {
// Insert a new item
let (item, error) = addItem(ReadingListItem(url: "http://one.com", title: "One"))
XCTAssertNotNil(item)
XCTAssertNil(error)
XCTAssert(item.clientLastModified != 0)
XCTAssert(item.isUnread == true)
// Mark it as read and update it
item.isUnread = false
db.withConnection(.ReadWrite, cb: { (connection) -> NSError? in
var error: NSError?
self.readingListTable.update(connection, item: item, err: &error)
XCTAssertNil(error)
return nil
})
// Fetch the item, see if it has updated
let (updatedItem, success) = getItem(item.id!)
XCTAssertTrue(success)
XCTAssertNotNil(updatedItem)
XCTAssertEqual(item.id!, updatedItem!.id!)
XCTAssertTrue(updatedItem!.clientLastModified != 0)
//XCTAssertTrue(item.clientLastModified < updatedItem!.clientLastModified) // TODO: See bug 1132504
XCTAssert(updatedItem!.isUnread == false)
}
private func addItem(var item: ReadingListItem) -> (item: ReadingListItem, error: NSError?) {
var error: NSError?
db.withConnection(.ReadWrite, cb: { (connection) -> NSError? in
item.id = self.readingListTable.insert(connection, item: item, err: &error)
return nil
})
return (item, error)
}
private func getItem(id: Int) -> (item: ReadingListItem?, success: Bool) {
var item: ReadingListItem?
var success: Bool = false
db.withConnection(.ReadOnly, cb: { (connection) -> NSError? in
var cursor = self.readingListTable.query(connection, options: QueryOptions(filter: id, filterType: FilterType.None, sort: QuerySort.None))
if cursor.status == .Success {
success = true
if cursor.count == 1 {
item = cursor[0] as ReadingListItem?
}
}
return nil
})
return (item, success)
}
} | mpl-2.0 | 4922382621a717e17b5621f837111a8b | 34.710145 | 150 | 0.594479 | 4.806829 | false | true | false | false |
gmoral/SwiftTraining2016 | Pods/ImageLoader/ImageLoader/Manager.swift | 1 | 7475 | //
// Manager.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 12/7/15.
// Copyright © 2015 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
/**
Responsible for creating and managing `Loader` objects and controlling of `NSURLSession` and `ImageCache`
*/
public class Manager {
let session: NSURLSession
let cache: ImageLoaderCache
let delegate: SessionDataDelegate = SessionDataDelegate()
public var automaticallyAdjustsSize = true
public var automaticallyAddTransition = true
/**
Use to kill or keep a fetching image loader when it's blocks is to empty by imageview or anyone.
*/
public var shouldKeepLoader = false
private let decompressingQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
public init(configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
cache: ImageLoaderCache = Diskcached()
) {
session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
self.cache = cache
}
// MARK: state
var state: State {
return delegate.isEmpty ? .Ready : .Running
}
// MARK: loading
func load(URL: URLLiteralConvertible) -> Loader {
if let loader = delegate[URL.imageLoaderURL] {
loader.resume()
return loader
}
let request = NSMutableURLRequest(URL: URL.imageLoaderURL)
request.setValue("image/*", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request)
let loader = Loader(task: task, delegate: self)
delegate[URL.imageLoaderURL] = loader
return loader
}
func suspend(URL: URLLiteralConvertible) -> Loader? {
if let loader = delegate[URL.imageLoaderURL] {
loader.suspend()
return loader
}
return nil
}
func cancel(URL: URLLiteralConvertible, block: Block? = nil) -> Loader? {
return cancel(URL, identifier: block?.identifier)
}
func cancel(URL: URLLiteralConvertible, identifier: Int?) -> Loader? {
if let loader = delegate[URL.imageLoaderURL] {
if let identifier = identifier {
loader.remove(identifier)
}
if !shouldKeepLoader && loader.blocks.isEmpty {
loader.cancel()
delegate.remove(URL.imageLoaderURL)
}
return loader
}
return nil
}
class SessionDataDelegate: NSObject, NSURLSessionDataDelegate {
private let _ioQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
var loaders: [NSURL: Loader] = [:]
subscript (URL: NSURL) -> Loader? {
get {
var loader : Loader?
dispatch_sync(_ioQueue) {
loader = self.loaders[URL]
}
return loader
}
set {
if let newValue = newValue {
dispatch_barrier_async(_ioQueue) {
self.loaders[URL] = newValue
}
}
}
}
var isEmpty: Bool {
var isEmpty = false
dispatch_sync(_ioQueue) {
isEmpty = self.loaders.isEmpty
}
return isEmpty
}
private func remove(URL: NSURL) -> Loader? {
if let loader = loaders[URL] {
loaders[URL] = nil
return loader
}
return nil
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let URL = dataTask.originalRequest?.URL, loader = self[URL] {
loader.receive(data)
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
completionHandler(.Allow)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let URL = task.originalRequest?.URL, loader = loaders[URL] {
loader.complete(error) { [unowned self] in
self.remove(URL)
}
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) {
completionHandler(nil)
}
}
deinit {
session.invalidateAndCancel()
}
}
/**
Responsible for sending a request and receiving the response and calling blocks for the request.
*/
public class Loader {
unowned let delegate: Manager
let task: NSURLSessionDataTask
var receivedData = NSMutableData()
var blocks: [Block] = []
init (task: NSURLSessionDataTask, delegate: Manager) {
self.task = task
self.delegate = delegate
resume()
}
var state: NSURLSessionTaskState {
return task.state
}
public func completionHandler(completionHandler: CompletionHandler) -> Self {
let identifier = (blocks.last?.identifier ?? 0) + 1
return self.completionHandler(identifier, completionHandler: completionHandler)
}
public func completionHandler(identifier: Int, completionHandler: CompletionHandler) -> Self {
let block = Block(identifier: identifier, completionHandler: completionHandler)
return appendBlock(block)
}
func appendBlock(block: Block) -> Self {
blocks.append(block)
return self
}
// MARK: task
public func suspend() {
task.suspend()
}
public func resume() {
task.resume()
}
public func cancel() {
task.cancel()
}
private func remove(identifier: Int) {
// needs to queue with sync
blocks = blocks.filter{ $0.identifier != identifier }
}
private func receive(data: NSData) {
receivedData.appendData(data)
}
private func complete(error: NSError?, completionHandler: () -> Void) {
if let URL = task.originalRequest?.URL {
if let error = error {
failure(URL, error: error, completionHandler: completionHandler)
return
}
dispatch_async(delegate.decompressingQueue) { [weak self] in
guard let wSelf = self else {
return
}
wSelf.success(URL, data: wSelf.receivedData, completionHandler: completionHandler)
}
}
}
private func success(URL: NSURL, data: NSData, completionHandler: () -> Void) {
let image = UIImage.decode(data)
_toCache(URL, data: data)
for block in blocks {
block.completionHandler(URL, image, nil, .None)
}
blocks = []
completionHandler()
}
private func failure(URL: NSURL, error: NSError, completionHandler: () -> Void) {
for block in blocks {
block.completionHandler(URL, nil, error, .None)
}
blocks = []
completionHandler()
}
private func _toCache(URL: NSURL, data: NSData?) {
if let data = data {
delegate.cache[URL] = data
}
}
} | mit | 91fe822a115ed4e273e151a5fa177067 | 28.199219 | 188 | 0.591651 | 5.193885 | false | false | false | false |
schibsted/layout | LayoutTests/ColorExpressionTests.swift | 1 | 5198 | // Copyright © 2017 Schibsted. All rights reserved.
import XCTest
@testable import Layout
extension UIColor {
@objc static let testColor = UIColor.brown
}
class ColorExpressionTests: XCTestCase {
func testRed() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "red", for: node)
let expected = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
XCTAssertEqual(try expression?.evaluate() as? UIColor, expected)
}
func testRedOrBlue() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "true ? #f00 : #00f", for: node)
let expected = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
XCTAssertEqual(try expression?.evaluate() as? UIColor, expected)
}
func testRedOrBlue2() {
let node = LayoutNode(state: ["foo": true])
let expression = LayoutExpression(colorExpression: "foo ? red : blue", for: node)
let expected = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
XCTAssertEqual(try expression?.evaluate() as? UIColor, expected)
}
func testCustomStaticColor() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "test", for: node)
XCTAssertEqual(try expression?.evaluate() as? UIColor, .testColor)
}
func testCustomStaticColor2() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "testColor", for: node)
XCTAssertEqual(try expression?.evaluate() as? UIColor, .testColor)
}
func testCustomStaticColor3() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "{UIColor.testColor}", for: node)
XCTAssertEqual(try expression?.evaluate() as? UIColor, .testColor)
}
func testCustomStaticColor4() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "{testColor}", for: node)
XCTAssertEqual(try expression?.evaluate() as? UIColor, .testColor)
}
func testNilColor() {
let null: UIColor? = nil
let node = LayoutNode(constants: ["color": null as Any])
let expression = LayoutExpression(colorExpression: "color", for: node)
XCTAssertThrowsError(try expression?.evaluate()) { error in
XCTAssert("\(error)".contains("nil"))
}
}
func testRGBColorWithClashingConstant() {
let node = LayoutNode(constants: ["red": 255])
let expression = LayoutExpression(colorExpression: "rgb(red,0,0)", for: node)
XCTAssertThrowsError(try expression?.evaluate()) { error in
XCTAssert("\(error)".lowercased().contains("type"))
}
}
func testSetBackgroundColor() {
let node = LayoutNode(expressions: ["backgroundColor": "red"])
node.update()
let expected = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
XCTAssertEqual(node.view.backgroundColor, expected)
}
func testSetLayerBackgroundColor() {
let node = LayoutNode(expressions: ["layer.backgroundColor": "red"])
node.update()
let expected = UIColor(red: 1, green: 0, blue: 0, alpha: 1).cgColor
XCTAssertEqual(node.view.layer.backgroundColor, expected)
}
func testSetLayerBackgroundColorWithCGColorConstant() {
let color = UIColor(red: 1, green: 0, blue: 0, alpha: 1).cgColor
let node = LayoutNode(
constants: ["color": color],
expressions: ["layer.backgroundColor": "color"]
)
node.update()
XCTAssertEqual(node.view.layer.backgroundColor, color)
}
func testSetLayerBackgroundColorWithUIColorConstant() {
let color = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
let node = LayoutNode(
constants: ["color": color],
expressions: ["layer.backgroundColor": "color"]
)
node.update()
XCTAssertEqual(node.view.layer.backgroundColor, color.cgColor)
}
func testBracedColor() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "{red}", for: node)
let expected = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
XCTAssertEqual(try expression?.evaluate() as? UIColor, expected)
}
func testNamedColorAsset() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "com.LayoutTests:MyColor", for: node)
XCTAssertThrowsError(try expression?.evaluate() as? UIColor) { error in
if #available(iOS 11.0, *) {
XCTAssert("\(error)".contains("in bundle"))
} else {
XCTAssert("\(error)".contains("iOS 11"))
}
}
}
func testNamedColorAssetExpression() {
let node = LayoutNode()
let expression = LayoutExpression(colorExpression: "MyColor{1}", for: node)
XCTAssertThrowsError(try expression?.evaluate() as? UIColor) { error in
if #available(iOS 11.0, *) {
XCTAssert("\(error)".contains("Invalid color name"))
} else {
XCTAssert("\(error)".contains("iOS 11"))
}
}
}
}
| mit | 83fc0bdcf370276d548a94eb596b28e6 | 36.934307 | 96 | 0.621512 | 4.611358 | false | true | false | false |
UncleJoke/Spiral | Spiral/AppDelegate.swift | 2 | 3364 | //
// AppDelegate.swift
// Spiral
//
// Created by 杨萧玉 on 14-7-12.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import SpriteKit
import CoreMotion
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
// Override point for customization after application launch.
WXApi.registerApp("wxeeaeb81c5f737329")
Fabric.with([Crashlytics()])
SKNode.yxy_swizzleAddChild()
SKNode.yxy_swizzleRemoveFromParent()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
return WXApi.handleOpenURL(url, delegate: self)
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return WXApi.handleOpenURL(url, delegate: self)
}
func onReq(req: BaseReq!) {
}
func onResp(resp: BaseResp!) {
if let response = resp as? SendMessageToWXResp {
if response.errCode == -2{
let alert = UIAlertController(title: "错误", message: "分享失败", preferredStyle: .Alert)
let action = UIAlertAction(title: "哦", style: .Default, handler: nil)
alert.addAction(action)
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
}
}
}
| mit | 72d99fdb32f6afd0f219678a6af0baf1 | 41.227848 | 285 | 0.69964 | 5.278481 | false | false | false | false |
eselkin/DirectionFieldiOS | Pods/GRDB.swift/GRDB/Core/SelectStatement.swift | 1 | 3774 | /// A subclass of Statement that fetches database rows.
///
/// You create SelectStatement with the Database.selectStatement() method:
///
/// dbQueue.inDatabase { db in
/// let statement = db.selectStatement("SELECT * FROM persons WHERE age > ?")
/// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
/// The number of columns in the resulting rows.
public lazy var columnCount: Int = { [unowned self] in
Int(sqlite3_column_count(self.sqliteStatement))
}()
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = { [unowned self] in
(0..<self.columnCount).map { index in
return String.fromCString(sqlite3_column_name(self.sqliteStatement, Int32(index)))!
}
}()
// MARK: - Not public
/// The DatabaseSequence builder.
func fetch<T>(arguments arguments: StatementArguments, yield: () -> T) -> DatabaseSequence<T> {
if !arguments.isDefault {
self.arguments = arguments
}
validateArguments()
return DatabaseSequence(statement: self, yield: yield)
}
/// The column index, case insensitive.
func indexForColumn(named name: String) -> Int? {
return lowercaseColumnIndexes[name] ?? lowercaseColumnIndexes[name.lowercaseString]
}
/// Support for indexForColumn(named:)
private lazy var lowercaseColumnIndexes: [String: Int] = { [unowned self] in
var indexes = [String: Int]()
let count = self.columnCount
// Reverse so that we return indexes for the leftmost columns.
// SELECT 1 AS a, 2 AS a -> lowercaseColumnIndexes["a”] = 0
for (index, columnName) in self.columnNames.reverse().enumerate() {
indexes[columnName.lowercaseString] = count - index - 1
}
return indexes
}()
}
/// A sequence of elements fetched from the database.
public struct DatabaseSequence<T>: SequenceType {
private let generateImpl: () -> DatabaseGenerator<T>
private init(statement: SelectStatement, yield: () -> T) {
generateImpl = {
let preconditionValidQueue = statement.database.preconditionValidQueue
let sqliteStatement = statement.sqliteStatement
// Check that sequence is built on a valid queue.
preconditionValidQueue()
// DatabaseSequence can be restarted:
statement.reset()
return DatabaseGenerator {
// Check that generator is used on a valid queue.
preconditionValidQueue()
let code = sqlite3_step(sqliteStatement)
switch code {
case SQLITE_DONE:
return nil
case SQLITE_ROW:
return yield()
default:
fatalError(DatabaseError(code: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments).description)
}
}
}
}
init() {
generateImpl = { return DatabaseGenerator { return nil } }
}
/// Return a *generator* over the elements of this *sequence*.
@warn_unused_result
public func generate() -> DatabaseGenerator<T> {
return generateImpl()
}
}
/// A generator of elements fetched from the database.
public struct DatabaseGenerator<T>: GeneratorType {
private let nextImpl: () -> T?
public mutating func next() -> T? {
return nextImpl()
}
}
| gpl-3.0 | fdaee2fb195ebff6eedc8fe8142e63d7 | 35.621359 | 167 | 0.603924 | 5.0563 | false | false | false | false |
aleph7/HDF5Kit | Source/FloatDataset.swift | 1 | 6562 | // Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of HDF5Kit. The full HDF5Kit copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#if SWIFT_PACKAGE
import CHDF5
#endif
public class FloatDataset: Dataset {
public subscript(slices: HyperslabIndexType...) -> [Float] {
// There is a problem with Swift where it gives a compiler error if `set` is implemented here
return (try? read(slices)) ?? []
}
public subscript(slices: [HyperslabIndexType]) -> [Float] {
get {
return (try? read(slices)) ?? []
}
set {
try! write(newValue, to: slices)
}
}
public func read(_ slices: [HyperslabIndexType]) throws -> [Float] {
let filespace = space
filespace.select(slices)
return try read(memSpace: Dataspace(dims: filespace.selectionDims), fileSpace: filespace)
}
public func write(_ data: [Float], to slices: [HyperslabIndexType]) throws {
let filespace = space
filespace.select(slices)
try write(data, memSpace: Dataspace(dims: filespace.selectionDims), fileSpace: filespace)
}
/// Append data to the table
public func append(_ data: [Float], dimensions: [Int], axis: Int = 0) throws {
let oldExtent = extent
extent[axis] += dimensions[axis]
for (index, dim) in dimensions.enumerated() {
if dim > oldExtent[index] {
extent[index] = dim
}
}
var start = [Int](repeating: 0, count: oldExtent.count)
start[axis] = oldExtent[axis]
let fileSpace = space
fileSpace.select(start: start, stride: nil, count: dimensions, block: nil)
try write(data, memSpace: Dataspace(dims: dimensions), fileSpace: fileSpace)
}
/// Read data using an optional memory Dataspace and an optional file Dataspace
///
/// - precondition: The `selectionSize` of the memory Dataspace is the same as for the file Dataspace
public func read(memSpace: Dataspace? = nil, fileSpace: Dataspace? = nil) throws -> [Float] {
let size: Int
if let memspace = memSpace {
size = memspace.size
} else if let filespace = fileSpace {
size = filespace.selectionSize
} else {
size = space.selectionSize
}
var result = [Float](repeating: 0.0, count: size)
try result.withUnsafeMutableBufferPointer() { (pointer: inout UnsafeMutableBufferPointer) in
try read(into: pointer.baseAddress!, memSpace: memSpace, fileSpace: fileSpace)
}
return result
}
/// Read data using an optional memory Dataspace and an optional file Dataspace
///
/// - precondition: The `selectionSize` of the memory Dataspace is the same as for the file Dataspace and there is enough memory available for it
public func read(into pointer: UnsafeMutablePointer<Float>, memSpace: Dataspace? = nil, fileSpace: Dataspace? = nil) throws {
try super.read(into: pointer, type: .float, memSpace: memSpace, fileSpace: fileSpace)
}
/// Write data using an optional memory Dataspace and an optional file Dataspace
///
/// - precondition: The `selectionSize` of the memory Dataspace is the same as for the file Dataspace and the same as `data.count`
public func write(_ data: [Float], memSpace: Dataspace? = nil, fileSpace: Dataspace? = nil) throws {
let size: Int
if let memspace = memSpace {
size = memspace.size
} else if let filespace = fileSpace {
size = filespace.selectionSize
} else {
size = space.selectionSize
}
precondition(data.count == size, "Data size doesn't match Dataspace dimensions")
try data.withUnsafeBufferPointer() { bufferPointer in
try write(from: bufferPointer.baseAddress!, memSpace: memSpace, fileSpace: fileSpace)
}
}
/// Write data using an optional memory Dataspace and an optional file Dataspace
///
/// - precondition: The `selectionSize` of the memory Dataspace is the same as for the file Dataspace
public func write(from pointer: UnsafePointer<Float>, memSpace: Dataspace? = nil, fileSpace: Dataspace? = nil) throws {
try super.write(from: pointer, type: .float, memSpace: memSpace, fileSpace: fileSpace)
}
}
// MARK: GroupType extension for FloatDataset
extension GroupType {
/// Create a FloatDataset
public func createFloatDataset(_ name: String, dataspace: Dataspace) -> FloatDataset? {
guard let datatype = Datatype(type: Float.self) else {
return nil
}
let datasetID = name.withCString { name in
return H5Dcreate2(id, name, datatype.id, dataspace.id, 0, 0, 0)
}
return FloatDataset(id: datasetID)
}
/// Create a chunked FloatDataset
public func createFloatDataset(_ name: String, dataspace: Dataspace, chunkDimensions: [Int]) -> FloatDataset? {
guard let datatype = Datatype(type: Float.self) else {
return nil
}
precondition(dataspace.dims.count == chunkDimensions.count)
let plist = H5Pcreate(H5P_CLS_DATASET_CREATE_ID_g)
H5Pset_char_encoding(plist, H5T_CSET_UTF8)
let chunkDimensions64 = chunkDimensions.map({ hsize_t(bitPattern: hssize_t($0)) })
chunkDimensions64.withUnsafeBufferPointer { (pointer) -> Void in
H5Pset_chunk(plist, Int32(chunkDimensions.count), pointer.baseAddress)
}
defer {
H5Pclose(plist)
}
let datasetID = name.withCString{ name in
return H5Dcreate2(id, name, datatype.id, dataspace.id, 0, plist, 0)
}
return FloatDataset(id: datasetID)
}
/// Create a Float Dataset and write data
public func createAndWriteDataset(_ name: String, dims: [Int], data: [Float]) throws -> FloatDataset {
let space = Dataspace.init(dims: dims)
let set = createFloatDataset(name, dataspace: space)!
try set.write(data)
return set
}
/// Open an existing FloatDataset
public func openFloatDataset(_ name: String) -> FloatDataset? {
let datasetID = name.withCString{ name in
return H5Dopen2(id, name, 0)
}
guard datasetID >= 0 else {
return nil
}
return FloatDataset(id: datasetID)
}
}
| mit | 3c9c78ad76b47924dd1280dddb16348b | 38.287425 | 149 | 0.638775 | 4.484621 | false | false | false | false |
frootloops/swift | test/ClangImporter/objc_parse.swift | 1 | 23547 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify
// REQUIRES: objc_interop
import AppKit
import AVFoundation
import Newtype
import objc_ext
import TestProtocols
import TypeAndValue
import ObjCParseExtras
import ObjCParseExtrasToo
import ObjCParseExtrasSystem
func markUsed<T>(_ t: T) {}
func testAnyObject(_ obj: AnyObject) {
_ = obj.nsstringProperty
}
// Construction
func construction() {
_ = B()
}
// Subtyping
func treatBAsA(_ b: B) -> A {
return b
}
// Instance method invocation
func instanceMethods(_ b: B) {
var i = b.method(1, with: 2.5 as Float)
i = i + b.method(1, with: 2.5 as Double)
// BOOL
b.setEnabled(true)
// SEL
b.perform(#selector(NSObject.isEqual(_:)), with: b)
if let result = b.perform(#selector(B.getAsProto), with: nil) {
_ = result.takeUnretainedValue()
}
// Renaming of redundant parameters.
b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}} {{32-32=withValue:4, }} {{44-57=}}
b.performAdd(1, withValue:2, withValue:4, withValue2: 3)
b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }}
// Both class and instance methods exist.
_ = b.description
b.instanceTakesObjectClassTakesFloat(b)
b.instanceTakesObjectClassTakesFloat(2.0)
// Instance methods with keyword components
var obj = NSObject()
var prot = NSObjectProtocol.self
b.`protocol`(prot, hasThing:obj)
b.doThing(obj, protocol: prot)
}
// Class method invocation
func classMethods(_ b: B, other: NSObject) {
var i = B.classMethod()
i += B.classMethod(1)
i += B.classMethod(1, with: 2)
i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}}
// Both class and instance methods exist.
B.description()
B.instanceTakesObjectClassTakesFloat(2.0)
B.instanceTakesObjectClassTakesFloat(other) // expected-error{{cannot convert value of type 'NSObject' to expected argument type 'Float'}}
// Call an instance method of NSObject.
var c: AnyClass = B.myClass() // no-warning
c = b.myClass() // no-warning
}
// Instance method invocation on extensions
func instanceMethodsInExtensions(_ b: B) {
b.method(1, onCat1:2.5)
b.method(1, onExtA:2.5)
b.method(1, onExtB:2.5)
b.method(1, separateExtMethod:3.5)
let m1 = b.method(_:onCat1:)
_ = m1(1, 2.5)
let m2 = b.method(_:onExtA:)
_ = m2(1, 2.5)
let m3 = b.method(_:onExtB:)
_ = m3(1, 2.5)
let m4 = b.method(_:separateExtMethod:)
_ = m4(1, 2.5)
}
func dynamicLookupMethod(_ b: AnyObject) {
if let m5 = b.method(_:separateExtMethod:) {
_ = m5(1, 2.5)
}
}
// Properties
func properties(_ b: B) {
var i = b.counter
b.counter = i + 1
i = i + b.readCounter
b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}}
b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}}
// Informal properties in Objective-C map to methods, not variables.
b.informalProp()
// An informal property cannot be made formal in a subclass. The
// formal property is simply ignored.
b.informalMadeFormal()
b.informalMadeFormal = i // expected-error{{cannot assign to property: 'informalMadeFormal' is a method}}
b.setInformalMadeFormal(5)
b.overriddenProp = 17
// Dynamic properties.
var obj : AnyObject = b
var optStr = obj.nsstringProperty
if optStr != nil {
var s : String = optStr!
}
// Properties that are Swift keywords
var prot = b.`protocol`
// Properties whose accessors run afoul of selector splitting.
_ = SelectorSplittingAccessors()
}
// Construction.
func newConstruction(_ a: A, aproxy: AProxy) {
var b : B = B()
b = B(int: 17)
b = B(int:17)
b = B(double:17.5, 3.14159)
b = B(bbb:b)
b = B(forWorldDomination:())
b = B(int: 17, andDouble : 3.14159)
b = B.new(with: a)
B.alloc()._initFoo()
b.notAnInit()
// init methods are not imported by themselves.
b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}}
// init methods on non-NSObject-rooted classes
AProxy(int: 5) // expected-warning{{unused}}
}
// Indexed subscripting
func indexedSubscripting(_ b: B, idx: Int, a: A) {
b[idx] = a
_ = b[idx] as! A
}
// Keyed subscripting
func keyedSubscripting(_ b: B, idx: A, a: A) {
b[a] = a
var a2 = b[a] as! A
let dict = NSMutableDictionary()
dict[NSString()] = a
let value = dict[NSString()]
dict[nil] = a // expected-error {{cannot assign value of type 'A' to type 'Any?'}}
let q = dict[nil] // expected-error {{ambiguous subscript}}
_ = q
}
// Typed indexed subscripting
func checkHive(_ hive: Hive, b: Bee) {
let b2 = hive.bees[5] as Bee
b2.buzz()
}
// Protocols
func testProtocols(_ b: B, bp: BProto) {
var bp2 : BProto = b
var b2 : B = bp // expected-error{{cannot convert value of type 'BProto' to specified type 'B'}}
bp.method(1, with: 2.5 as Float)
bp.method(1, withFoo: 2.5) // expected-error{{incorrect argument label in call (have '_:withFoo:', expected '_:with:')}}
bp2 = b.getAsProto()
var c1 : Cat1Proto = b
var bcat1 = b.getAsProtoWithCat()!
c1 = bcat1
bcat1 = c1 // expected-error{{value of type 'Cat1Proto' does not conform to 'BProto & Cat1Proto' in assignment}}
}
// Methods only defined in a protocol
func testProtocolMethods(_ b: B, p2m: P2.Type) {
b.otherMethod(1, with: 3.14159)
b.p2Method()
b.initViaP2(3.14159, second: 3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}}
// Imported constructor.
var b2 = B(viaP2: 3.14159, second: 3.14159)
_ = p2m.init(viaP2:3.14159, second: 3.14159)
}
func testId(_ x: AnyObject) {
x.perform!("foo:", with: x) // expected-warning{{no method declared with Objective-C selector 'foo:'}}
// expected-warning @-1 {{result of call is unused, but produces 'Unmanaged<AnyObject>!'}}
_ = x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4)
_ = x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4)
_ = x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4)
}
class MySubclass : B {
// Override a regular method.
override func anotherMethodOnB() {}
// Override a category method
override func anotherCategoryMethod() {}
}
func getDescription(_ array: NSArray) {
_ = array.description
}
// Method overriding with unfortunate ordering.
func overridingTest(_ srs: SuperRefsSub) {
let rs : RefedSub
rs.overridden()
}
func almostSubscriptableValueMismatch(_ as1: AlmostSubscriptable, a: A) {
as1[a] // expected-error{{type 'AlmostSubscriptable' has no subscript members}}
}
func almostSubscriptableKeyMismatch(_ bc: BadCollection, key: NSString) {
// FIXME: We end up importing this as read-only due to the mismatch between
// getter/setter element types.
var _ : Any = bc[key]
}
func almostSubscriptableKeyMismatchInherited(_ bc: BadCollectionChild,
key: String) {
var value : Any = bc[key] // no-warning, inherited from parent
bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
func almostSubscriptableKeyMismatchInherited(_ roc: ReadOnlyCollectionChild,
key: String) {
var value : Any = roc[key] // no-warning, inherited from parent
roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
// Use of 'Class' via dynamic lookup.
func classAnyObject(_ obj: NSObject) {
_ = obj.myClass().description!()
}
// Protocol conformances
class Wobbler : NSWobbling { // expected-note{{candidate has non-matching type '()'}}
@objc func wobble() { }
func returnMyself() -> Self { return self } // expected-error{{non-'@objc' method 'returnMyself()' does not satisfy requirement of '@objc' protocol 'NSWobbling'}}{{none}}
// expected-error@-1{{method cannot be an implementation of an @objc requirement because its result type cannot be represented in Objective-C}}
}
extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}}
}
@objc class Wobbler2 : NSObject, NSWobbling { // expected-note{{candidate has non-matching type '()'}}
func wobble() { }
func returnMyself() -> Self { return self }
}
extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}}
}
func optionalMemberAccess(_ w: NSWobbling) {
w.wobble()
w.wibble() // expected-error{{value of optional type '(() -> Void)?' not unwrapped; did you mean to use '!' or '?'?}} {{11-11=!}}
let x = w[5]!!
_ = x
}
func protocolInheritance(_ s: NSString) {
var _: NSCoding = s
}
func ivars(_ hive: Hive) {
var d = hive.bees.description
hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}}
}
class NSObjectable : NSObjectProtocol {
@objc var description : String { return "" }
@objc(conformsToProtocol:) func conforms(to _: Protocol) -> Bool { return false }
@objc(isKindOfClass:) func isKind(of aClass: AnyClass) -> Bool { return false }
}
// Properties with custom accessors
func customAccessors(_ hive: Hive, bee: Bee) {
markUsed(hive.isMakingHoney)
markUsed(hive.makingHoney()) // expected-error{{cannot call value of non-function type 'Bool'}}{{28-30=}}
hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}}
_ = (hive.`guard` as AnyObject).description // okay
_ = (hive.`guard` as AnyObject).description! // no-warning
hive.`guard` = bee // no-warning
}
// instancetype/Dynamic Self invocation.
func testDynamicSelf(_ queen: Bee, wobbler: NSWobbling) {
var hive = Hive()
// Factory method with instancetype result.
var hive1 = Hive(queen: queen)
hive1 = hive
hive = hive1
// Instance method with instancetype result.
var hive2 = hive!.visit()
hive2 = hive
hive = hive2
// Instance method on a protocol with instancetype result.
var wobbler2 = wobbler.returnMyself()!
var wobbler: NSWobbling = wobbler2
wobbler2 = wobbler
// Instance method on a base class with instancetype result, called on the
// class itself.
// FIXME: This should be accepted.
let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself()
// expected-error@-1 {{instance member 'returnMyself' cannot be used on type 'Base'}}
}
func testRepeatedProtocolAdoption(_ w: NSWindow) {
_ = w.description
}
class ProtocolAdopter1 : FooProto {
@objc var bar: CInt // no-warning
init() { bar = 5 }
}
class ProtocolAdopter2 : FooProto {
@objc var bar: CInt {
get { return 42 }
set { /* do nothing! */ }
}
}
class ProtocolAdopterBad1 : FooProto { // expected-error {{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}}
@objc var bar: Int = 0 // expected-note {{candidate has non-matching type 'Int'}}
}
class ProtocolAdopterBad2 : FooProto { // expected-error {{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}}
let bar: CInt = 0 // expected-note {{candidate is not settable, but protocol requires it}}
}
class ProtocolAdopterBad3 : FooProto { // expected-error {{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}}
var bar: CInt { // expected-note {{candidate is not settable, but protocol requires it}}
return 42
}
}
@objc protocol RefinedFooProtocol : FooProto {}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: NSObject) {
// FIXME: We shouldn't need the ": Bool" type annotation here.
// <rdar://problem/18006008>
let _: Bool = NSObject.isEqual(obj)
_ = NSObject.isEqual(obj) as (NSObject?) -> Bool // no-warning
}
func testPropertyAndMethodCollision(_ obj: PropertyAndMethodCollision,
rev: PropertyAndMethodReverseCollision) {
obj.object = nil
obj.object(obj, doSomething:#selector(getter: NSMenuItem.action))
type(of: obj).classRef = nil
type(of: obj).classRef(obj, doSomething:#selector(getter: NSMenuItem.action))
rev.object = nil
rev.object(rev, doSomething:#selector(getter: NSMenuItem.action))
type(of: rev).classRef = nil
type(of: rev).classRef(rev, doSomething:#selector(getter: NSMenuItem.action))
var value: Any
value = obj.protoProp()
value = obj.protoPropRO()
value = type(of: obj).protoClassProp()
value = type(of: obj).protoClassPropRO()
_ = value
}
func testPropertyAndMethodCollisionInOneClass(
obj: PropertyAndMethodCollisionInOneClass,
rev: PropertyAndMethodReverseCollisionInOneClass
) {
obj.object = nil
obj.object()
type(of: obj).classRef = nil
type(of: obj).classRef()
rev.object = nil
rev.object()
type(of: rev).classRef = nil
type(of: rev).classRef()
}
func testSubscriptAndPropertyRedeclaration(_ obj: SubscriptAndProperty) {
_ = obj.x
obj.x = 5
_ = obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}}
obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testSubscriptAndPropertyWithProtocols(_ obj: SubscriptAndPropertyWithProto) {
_ = obj.x
obj.x = 5
obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testProtocolMappingSameModule(_ obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) {
markUsed(p.enablePostProcessing)
markUsed(obj.enablePostProcessing)
_ = obj.backgroundColor
}
func testProtocolMappingDifferentModules(_ obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) {
markUsed(p.thisIsTheProto)
markUsed(obj.thisClassHasAnAwfulName)
let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}}
_ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'ClassInHelper' cannot be constructed because it has no accessible initializers}}
_ = ObjCParseExtrasToo.ProtoInHelper()
_ = ObjCParseExtrasTooHelper.ClassInHelper()
_ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'ProtoInHelper' cannot be constructed because it has no accessible initializers}}
}
func testProtocolClassShadowing(_ obj: ClassInHelper, p: ProtoInHelper) {
let _: ObjCParseExtrasToo.ClassInHelper = obj
let _: ObjCParseExtrasToo.ProtoInHelper = p
}
func testDealloc(_ obj: NSObject) {
// dealloc is subsumed by deinit.
// FIXME: Special-case diagnostic in the type checker?
obj.dealloc() // expected-error{{value of type 'NSObject' has no member 'dealloc'}}
}
func testConstantGlobals() {
markUsed(MAX)
markUsed(SomeImageName)
markUsed(SomeNumber.description)
MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}}
SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}}
SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}}
}
func testWeakVariable() {
let _: AnyObject = globalWeakVar
}
class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}}
// expected-error@-1{{type 'IncompleteProtocolAdopter' does not conform to protocol 'Incomplete'}}
@objc func getObject() -> AnyObject { return self } // expected-note{{candidate has non-matching type '() -> AnyObject'}}
}
func testNullarySelectorPieces(_ obj: AnyObject) {
obj.foo(1, bar: 2, 3) // no-warning
obj.foo(1, 2, bar: 3) // expected-error{{cannot invoke 'foo' with an argument list of type '(Int, Int, bar: Int)'}}
}
func testFactoryMethodAvailability() {
_ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}}
}
func testRepeatedMembers(_ obj: RepeatedMembers) {
obj.repeatedMethod()
}
// rdar://problem/19726164
class FooDelegateImpl : NSObject, FooDelegate {
var _started = false
var isStarted: Bool {
get { return _started }
@objc(setStarted:) set { _started = newValue }
}
}
class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto {
var foo: Any? // no errors about conformance
var bar: Any? // no errors about conformance
}
func testUnusedResults(_ ur: UnusedResults) {
_ = ur.producesResult()
ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}}
}
func testStrangeSelectors(obj: StrangeSelectors) {
StrangeSelectors.cStyle(0, 1, 2) // expected-error{{type 'StrangeSelectors' has no member 'cStyle'}}
_ = StrangeSelectors(a: 0, b: 0) // okay
obj.empty(1, 2) // okay
}
func testProtocolQualified(_ obj: CopyableNSObject, cell: CopyableSomeCell,
plainObj: NSObject, plainCell: SomeCell) {
_ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol') is not convertible to 'NSObject'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = obj as NSObjectProtocol
_ = obj as NSCopying
_ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol') is not convertible to 'SomeCell'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = cell as NSObject
_ = cell as NSObjectProtocol
_ = cell as NSCopying // expected-error {{'CopyableSomeCell' (aka 'SomeCell') is not convertible to 'NSCopying'; did you mean to use 'as!' to force downcast?}} {{12-14=as!}}
_ = cell as SomeCell
_ = plainObj as CopyableNSObject // expected-error {{'NSObject' is not convertible to 'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol'); did you mean to use 'as!' to force downcast?}} {{16-18=as!}}
_ = plainCell as CopyableSomeCell // FIXME: This is not really typesafe.
}
extension Printing {
func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
static func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
}
// <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated.
func testSetInitializers() {
let a: [AnyObject] = [NSObject()]
let _ = NSCountedSet(array: a)
let _ = NSMutableSet(array: a)
}
func testNSUInteger(_ obj: NSUIntegerTests, uint: UInt, int: Int) {
obj.consumeUnsigned(uint) // okay
obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay
obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(uint, andAnother: int) // okay
do {
let x = obj.unsignedProducer()
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.unsignedProducer(uint, fromCount: int) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.normalProducer(int, fromUnsigned: uint)
let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
}
let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
do {
testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = testUnsigned(uint, uint) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
// NSNumber
let num = NSNumber(value: uint)
let _: String = num.uintValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
class NewtypeUser {
@objc func stringNewtype(a: SNTErrorDomain) {} // expected-error {{'SNTErrorDomain' has been renamed to 'ErrorDomain'}}{{31-45=ErrorDomain}}
@objc func stringNewtypeOptional(a: SNTErrorDomain?) {} // expected-error {{'SNTErrorDomain' has been renamed to 'ErrorDomain'}}{{39-53=ErrorDomain}}
@objc func intNewtype(a: MyInt) {}
@objc func intNewtypeOptional(a: MyInt?) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func testTypeAndValue() {
_ = testStruct()
_ = testStruct(value: 0)
let _: (testStruct) -> Void = testStruct
let _: () -> testStruct = testStruct.init
let _: (CInt) -> testStruct = testStruct.init
}
// rdar://problem/34913507
func testBridgedTypedef(bt: BridgedTypedefs) {
let _: Int = bt.arrayOfArrayOfStrings // expected-error{{'[[String]]'}}
}
func testBridgeFunctionPointerTypedefs(fptrTypedef: FPTypedef) {
// See also print_clang_bool_bridging.swift.
let _: Int = fptrTypedef // expected-error{{'@convention(c) (String) -> String'}}
let _: Int = getFP() // expected-error{{'@convention(c) (String) -> String'}}
}
| apache-2.0 | 5198fd3345fa85b79acada83af0a2a55 | 35.170507 | 214 | 0.69563 | 3.899801 | false | true | false | false |
codelynx/silvershadow | Silvershadow/CoreGraphics+Z.swift | 1 | 4132 | //
// CoreGraphics+Z.swift
// ZKit
//
// Created by Kaz Yoshikawa on 12/12/16.
// Copyright © 2016 Electricwoods LLC. All rights reserved.
//
import Foundation
import CoreGraphics
extension CGRect {
init(size: CGSize) {
self.init(origin: .zero, size: size)
}
var cgPath: CGPath {
return CGPath(rect: self, transform: nil)
}
func cgPath(cornerRadius: CGFloat) -> CGPath {
// +7-------------6+
// 0 5
// | |
// 1 4
// +2-------------3+
let cornerRadius = min(size.width * 0.5, size.height * 0.5, cornerRadius)
let path = CGMutablePath()
path.move(to: minXmidY + CGPoint(x: 0, y: cornerRadius)) // (0)
path.addLine(to: minXmaxY - CGPoint(x: 0, y: cornerRadius)) // (1)
path.addQuadCurve(to: minXmaxY + CGPoint(x: cornerRadius, y: 0), control: minXmaxY) // (2)
path.addLine(to: maxXmaxY - CGPoint(x: cornerRadius, y: 0)) // (3)
path.addQuadCurve(to: maxXmaxY - CGPoint(x: 0, y: cornerRadius), control: maxXmaxY) // (4)
path.addLine(to: maxXminY + CGPoint(x: 0, y: cornerRadius)) // (5)
path.addQuadCurve(to: maxXminY - CGPoint(x: cornerRadius, y: 0), control: maxXminY) // (6)
path.addLine(to: minXminY + CGPoint(x: cornerRadius, y: 0)) // (7)
path.addQuadCurve(to: minXminY + CGPoint(x: 0, y: cornerRadius), control: minXminY) // (0)
path.closeSubpath()
return path
}
var minXminY: CGPoint { return CGPoint(x: minX, y: minY) }
var midXminY: CGPoint { return CGPoint(x: midX, y: minY) }
var maxXminY: CGPoint { return CGPoint(x: maxX, y: minY) }
var minXmidY: CGPoint { return CGPoint(x: minX, y: midY) }
var midXmidY: CGPoint { return CGPoint(x: midX, y: midY) }
var maxXmidY: CGPoint { return CGPoint(x: maxX, y: midY) }
var minXmaxY: CGPoint { return CGPoint(x: minX, y: maxY) }
var midXmaxY: CGPoint { return CGPoint(x: midX, y: maxY) }
var maxXmaxY: CGPoint { return CGPoint(x: maxX, y: maxY) }
func aspectFill(_ size: CGSize) -> CGRect {
let result: CGRect
let margin: CGFloat
let horizontalRatioToFit = size.width / size.width
let verticalRatioToFit = size.height / size.height
let imageHeightWhenItFitsHorizontally = horizontalRatioToFit * size.height
let imageWidthWhenItFitsVertically = verticalRatioToFit * size.width
if (imageHeightWhenItFitsHorizontally > size.height) {
margin = (imageHeightWhenItFitsHorizontally - size.height) * 0.5
result = CGRect(x: minX, y: minY - margin, width: size.width * horizontalRatioToFit, height: size.height * horizontalRatioToFit)
}
else {
margin = (imageWidthWhenItFitsVertically - size.width) * 0.5
result = CGRect(x: minX - margin, y: minY, width: size.width * verticalRatioToFit, height: size.height * verticalRatioToFit)
}
return result
}
func aspectFit(_ size: CGSize) -> CGRect {
let widthRatio = self.size.width / size.width
let heightRatio = self.size.height / size.height
let ratio = min(widthRatio, heightRatio)
let width = size.width * ratio
let height = size.height * ratio
let xmargin = (self.size.width - width) / 2.0
let ymargin = (self.size.height - height) / 2.0
return CGRect(x: minX + xmargin, y: minY + ymargin, width: width, height: height)
}
func transform(to rect: CGRect) -> CGAffineTransform {
var t = CGAffineTransform.identity
t = t.translatedBy(x: -minX, y: -minY)
t = t.scaledBy(x: 1 / width, y: 1 / height)
t = t.scaledBy(x: rect.width, y: rect.height)
t = t.translatedBy(x: rect.minX * width / rect.width, y: rect.minY * height / rect.height)
return t
}
}
extension CGSize {
func aspectFit(_ size: CGSize) -> CGSize {
let widthRatio = self.width / size.width
let heightRatio = self.height / size.height
let ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio
let width = size.width * ratio
let height = size.height * ratio
return CGSize(width: width, height: height)
}
static func - (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height)
}
}
extension CGAffineTransform {
static func * (lhs: CGAffineTransform, rhs: CGAffineTransform) -> CGAffineTransform {
return lhs.concatenating(rhs)
}
}
| mit | 8c717ed9d6bb7976f162a55f03000b10 | 33.140496 | 131 | 0.679012 | 3.222309 | false | false | false | false |
abdallahnh/ANPopUpContainer | Example/ANPopUpContainer/CurrencyTableViewController.swift | 1 | 3288 | //
// CurrencyTableViewController.swift
// PopUpContainer_Example
//
// Created by Abdallah Nehme on 10/31/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class CurrencyTableViewController: UITableViewController {
var data: [String]!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
data = ["USD", "EURO", "JPY","CAD"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Configure the cell...
cell.textLabel?.text = data[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | cc700c9ab3bdb6549542d1df194539e1 | 31.544554 | 136 | 0.665957 | 5.276083 | false | false | false | false |
mmisesin/particle | Particle/APIError.swift | 1 | 1157 | //
// APIError.swift
// Particle
//
// Created by Artem Misesin on 11/1/17.
// Copyright © 2017 Artem Misesin. All rights reserved.
//
import Foundation
struct APIError: Error {
var domain: String
var code: Int
var userInfo: [AnyHashable: Any]
init(domain: String = "", code: Int = 0, userInfo dictionary: [AnyHashable: Any]) {
self.domain = domain
self.code = code
self.userInfo = dictionary
}
init(errorDescription: String) {
self.domain = ""
self.code = 0
self.userInfo = [NSLocalizedDescriptionKey: errorDescription]
}
}
extension APIError {
var errorDescription: String {
if let errDesc = self.userInfo[NSLocalizedDescriptionKey] as? String {
return errDesc
}
return Constants.unknownErrorDescription
}
}
extension Error {
var apiError: APIError {
if let error = self as? APIError {
return error
} else {
let castedError = self as NSError
return APIError(domain: castedError.domain, code: castedError.code, userInfo: castedError.userInfo)
}
}
}
| mit | 4ee7b4746e4928933ccfd03e5346fca4 | 23.595745 | 111 | 0.615917 | 4.446154 | false | false | false | false |
strike65/SwiftyStats | SwiftyStats/CommonSource/SpecialFunctions/Hypergeo/HypergeometricPFQ.swift | 1 | 82741 | /*
Copyright (2017-2019) strike65
GNU GPL 3+
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, version 3 of the License.
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import Accelerate
// naive implementation
extension SSSpecialFunctions {
internal static func h2f2<T: SSFloatingPoint & Codable>(a1: T, a2: T, b1: T, b2: T, z: T) -> T {
var sum1, s: T
let tol: T = T.ulpOfOne
let maxIT: T = 1000
var k: T = 0
sum1 = 0
s = 0
var p1: T = 0
var p2: T = 0
var temp1: T = 0
let lz: T = SSMath.log1(z)
var kz: T
while k < maxIT {
p1 = lpochhammer(x: a1, n: k) + lpochhammer(x: a2, n: k)
p2 = lpochhammer(x: b1, n: k) + lpochhammer(x: b2, n: k)
kz = k * lz
temp1 = p1 + kz - p2
temp1 = temp1 - SSMath.logFactorial(Helpers.integerValue(k))
s = SSMath.exp1(temp1)
if abs((sum1 - (s + sum1))) < tol {
break
}
sum1 = sum1 + SSMath.exp1(temp1)
k = k + 1
}
return sum1
}
/*
%% Original fortran documentation
% ACPAPFQ. A NUMERICAL EVALUATOR FOR THE GENERALIZED HYPERGEOMETRIC
%
% 1 SERIES. W.F. PERGER, A. BHALLA, M. NARDIN.
%
% REF. IN COMP. PHYS. COMMUN. 77 (1993) 249
%
% ****************************************************************
% * *
% * SOLUTION TO THE GENERALIZED HYPERGEOMETRIC FUNCTION *
% * *
% * by *
% * *
% * W. F. PERGER, *
% * *
% * MARK NARDIN and ATUL BHALLA *
% * *
% * *
% * Electrical Engineering Department *
% * Michigan Technological University *
% * 1400 Townsend Drive *
% * Houghton, MI 49931-1295 USA *
% * Copyright 1993 *
% * *
% * e-mail address: [email protected] *
% * *
% * Description : A numerical evaluator for the generalized *
% * hypergeometric function for complex arguments with large *
% * magnitudes using a direct summation of the Gauss series. *
% * The method used allows an accuracy of up to thirteen *
% * decimal places through the use of large integer arrays *
% * and a single final division. *
% * (original subroutines for the confluent hypergeometric *
% * written by Mark Nardin, 1989; modifications made to cal- *
% * culate the generalized hypergeometric function were *
% * written by W.F. Perger and A. Bhalla, June, 1990) *
% * *
% * The evaluation of the pFq series is accomplished by a func- *
% * ion call to PFQ, which is a double precision complex func- *
% * tion. The required input is: *
% * 1. Double precision complex arrays A and B. These are the *
% * arrays containing the parameters in the numerator and de-*
% * nominator, respectively. *
% * 2. Integers IP and IQ. These integers indicate the number *
% * of numerator and denominator terms, respectively (these *
% * are p and q in the pFq function). *
% * 3. Double precision complex argument Z. *
% * 4. Integer LNPFQ. This integer should be set to '1' if the *
% * result from PFQ is to be returned as the natural logaritm*
% * of the series, or '0' if not. The user can generally set*
% * LNPFQ = '0' and change it if required. *
% * 5. Integer IX. This integer should be set to '0' if the *
% * user desires the program PFQ to estimate the number of *
% * array terms (in A and B) to be used, or an integer *
% * greater than zero specifying the number of integer pos- *
% * itions to be used. This input parameter is escpecially *
% * useful as a means to check the results of a given run. *
% * Specificially, if the user obtains a result for a given *
% * set of parameters, then changes IX and re-runs the eval- *
% * uator, and if the number of array positions was insuffi- *
% * cient, then the two results will likely differ. The rec-*
% * commended would be to generally set IX = '0' and then set*
% * it to 100 or so for a second run. Note that the LENGTH *
% * parameter currently sets the upper limit on IX to 777, *
% * but that can easily be changed (it is a single PARAMETER *
% * statement) and the program recompiled. *
% * 6. Integer NSIGFIG. This integer specifies the requested *
% * number of significant figures in the final result. If *
% * the user attempts to request more than the number of bits*
% * in the mantissa allows, the program will abort with an *
% * appropriate error message. The recommended value is 10. *
% * *
% * Note: The variable NOUT is the file to which error mess- *
% * ages are written (default is 6). This can be *
% * changed in the FUNCTION PFQ to accomodate re- *
% * of output to another file *
% * *
% * Subprograms called: HYPER. *
% * *
% ****************************************************************
*/
internal static func hypergeometricPFQ<T: SSFloatingPoint>(a: Array<Complex<T>>, b: Array<Complex<T>>, z: Complex<T>, log: Bool = false) throws -> Complex<T> {
var sigfig: Int
switch z.re {
case is Double:
sigfig = 15
case is Float:
sigfig = 7
#if arch(x86_64)
case is Float80:
sigfig = 19
#endif
default:
sigfig = 15
}
var ans: Complex<T>
var zz: Complex<T> = z
let aa: Array<Complex<T>> = a
let bb: Array<Complex<T>> = b
do {
try ans = hyper(a: aa, b: bb, ip: aa.count, iq: bb.count, z: &zz, lnpfq: log ? 1 : 0, ix: 777, nsigfig: &sigfig)
if !ans.isNan {
return ans
}
}
catch {
throw error
}
return ans
}
}
/*
% ****************************************************************
% * *
% * FUNCTION HYPER *
% * *
% * *
% * Description : Function that sums the Gauss series. *
% * *
% * Subprograms called: ARMULT, ARYDIV, BITS, CMPADD, CMPMUL, *
% * IPREMAX. *
% * *
% ****************************************************************
*/
fileprivate func hyper<T: SSFloatingPoint>(a: Array<Complex<T>>, b: Array<Complex<T>>, ip: Int, iq: Int, z: inout Complex<T>, lnpfq: Int, ix: Int, nsigfig: inout Int) throws -> Complex<T> {
let length: Int = 777
var cr: Array<T> = Array<T>.init(repeating: 0, count: 10)
var ci: Array<T> = Array<T>.init(repeating: 0, count: 10)
var ar: Array<T> = Array<T>.init(repeating: 0, count: 10)
var ai: Array<T> = Array<T>.init(repeating: 0, count: 10)
var ar2: Array<T> = Array<T>.init(repeating: 0, count: 10)
var ai2: Array<T> = Array<T>.init(repeating: 0, count: 10)
var cr2: Array<T> = Array<T>.init(repeating: 0, count: 10)
var ci2: Array<T> = Array<T>.init(repeating: 0, count: 10)
var sumr: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var sumi: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var denomr: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var denomi: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var qr1: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var qi1: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var wk1: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var wk2: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var wk3: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var wk4: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var wk5: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var wk6: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var qr2: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var qi2: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var foo1: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var foo2: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var numr: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var numi: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var bar1: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var bar2: Array<T> = Array<T>.init(repeating: 0, count: length + 2)
var accy, cnt, bitss, creal, dum1, dum2, expon, mx1, mx2, ri10, rr10, sigfig, rmax, x, xi, xi2, xl, xr, xr2, log2: T
var cdum1, cdum2, final, oldtemp, temp, temp1, ans: Complex<T>
var goon1, i1, ibit,icount,ii10,ir10,ixcnt,l,lmax,nmach,rexp: Int
var e1, e2, e3: T
var ex1: T
var ex2: T
var ex3: T
var ex4: T
var ex5: T
accy = 0
cnt = 0
creal = 0
dum1 = 0
dum2 = 0
expon = 0
mx1 = 0
mx2 = 0
ri10 = 0
rr10 = 0
sigfig = 0
rmax = 0
x = 0
xi = 0
xi2 = 0
xl = 0
xr = 0
xr2 = 0
cdum1 = Complex<T>(0)
cdum2 = Complex<T>(0)
final = Complex<T>(T.nan, T.nan)
oldtemp = Complex<T>(0)
temp = Complex<T>(0)
temp1 = Complex<T>(0)
goon1 = 0
i1 = 0
ibit = 0
icount = 0
ii10 = 0
ir10 = 0
ixcnt = 0
l = 0
lmax = 0
nmach = 0
rexp = 0
bitss = bits()
log2 = SSMath.log101(2)
ibit = Helpers.integerValue(bitss)
let intibito2: T = Helpers.makeFP(ibit) / 2
let intibito4: T = Helpers.makeFP(ibit) / 4
let iintibito2: Int = Helpers.integerValue(intibito2)
let iintibito4: Int = Helpers.integerValue(intibito4)
let intibito2f: T = Helpers.makeFP(iintibito2)
let intibito4f: T = Helpers.makeFP(iintibito4)
rmax = SSMath.pow1(2, intibito2f)
sigfig = SSMath.pow1(2, intibito4f)
for I1: Int in stride(from: 1, to: ip, by: 1) {
i1 = I1
ar2[i1 - 1] = (a[i1 - 1] &** sigfig).re
ar[i1 - 1] = fix(ar2[i1 - 1])
ar2[i1 - 1] = round((ar2[i1 - 1] - ar[i1 - 1]) * rmax)
ai2[i1 - 1] = (a[i1 - 1] &** sigfig).im
ai[i1 - 1] = fix(ai2[i1 - 1])
ai2[i1 - 1] = round((ai2[i1 - 1] - ai[i1 - 1] * rmax))
}
for I1: Int in stride(from: 1, to: ip, by: 1) {
cr2[I1 - 1] = (b[I1 - 1] &** sigfig).re
cr[I1 - 1] = fix(cr2[i1 - 1])
cr2[I1 - 1] = round((cr2[I1 - 1] - cr[I1 - 1]) * rmax)
ci2[I1 - 1] = (b[I1 - 1] &** sigfig).im
ci[I1 - 1] = fix(ci2[i1 - 1])
ci2[I1 - 1] = round((ci2[I1 - 1] - ci[I1 - 1] * rmax))
}
xr2 = z.re * sigfig
xr = fix(xr2)
xr2 = round( (xr2 - xr) * rmax)
xi2 = z.im * sigfig
xi = fix(xi2)
xi2 = round((xi2 - xi) * rmax)
/*
%
% WARN THE USER THAT THE INPUT VALUE WAS SO CLOSE TO ZERO THAT IT
% WAS SET EQUAL TO ZERO.
%
*/
for i1 in stride(from: 1, to: ip, by: 1) {
if (!a[i1 - 1].re.isZero && ar[i1 - 1].isZero && ar2[i1 - 1].isZero) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Real part was set to zero (input vector a - at least one element was too close to zero)", log: .log_stat, type: .error)
}
#else
print("Real part was set to zero (input vector a - at least one element was too close to zero)")
#endif
}
if (!a[i1 - 1].isZero && ai[i1 - 1].isZero && ai2[i1 - 1].isZero) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Imaginary part was set to zero (input vector a - at least one element was too close to zero)", log: .log_stat, type: .error)
}
#else
print("Imaginary part was set to zero (input vector a - at least one element was too close to zero)")
#endif
}
}
for i1 in stride(from: 1, to: iq, by: 1) {
if (!b[i1 - 1].re.isZero && cr[i1 - 1].isZero && cr2[i1 - 1].isZero) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Real part was set to zero (input vector b - at least one element was too close to zero)", log: .log_stat, type: .error)
}
#else
print("Real part was set to zero (input vector b - at least one element was too close to zero)")
#endif
}
if (!b[i1 - 1].isZero && ci[i1 - 1].isZero && ci2[i1 - 1].isZero) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Imaginary part was set to zero (input vector b - at least one element was too close to zero)", log: .log_stat, type: .error)
}
#else
print("Imaginary part was set to zero (input vector b - at least one element was too close to zero)")
#endif
}
}
if !z.re.isZero && xr.isZero && xr2.isZero {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Real part was set to zero (input z - at least one element was too close to zero)", log: .log_stat, type: .error)
}
#else
print("Real part was set to zero (input z - at least one element was too close to zero)")
#endif
z = Complex<T>.init(re: 0, im: z.im)
}
if !z.im.isZero && xi.isZero && xi2.isZero {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Imaginary part was set to zero (input z - at least one element was too close to zero)", log: .log_stat, type: .error)
}
#else
print("Imaginary part was set to zero (input z - at least one element was too close to zero)")
#endif
z = Complex<T>.init(re: z.re, im: 0)
}
/*
%
%
% SCREENING OF NUMERATOR ARGUMENTS FOR NEGATIVE INTEGERS OR ZERO.
% ICOUNT WILL FORCE THE SERIES TO TERMINATE CORRECTLY.
%
*/
nmach = ifix(SSMath.log101(SSMath.pow1(2, fix(bitss))))
icount = -1
for i1 in 1...ip {
if ar2[i1 - 1].isZero && ar[i1 - 1].isZero && ai2[i1 - 1].isZero && ai[i1 - 1].isZero {
ans = Complex<T>.init(re: T.one, im: 0)
return ans
}
if ai[i1 - 1].isZero && ai2[i1 - 1].isZero && a[i1 - 1].re < 0 {
ex1 = a[i1 - 1].re - round(a[i1 - 1].re)
if abs(ex1) < SSMath.pow1(10, -Helpers.makeFP(nmach)) {
if (icount != -1) {
icount = ifix(min( Helpers.makeFP(icount), -round(a[i1 - 1].re)))
}
else {
icount = -ifix(round(a[i1 - 1].re))
}
}
}
}
/*
%
% SCREENING OF DENOMINATOR ARGUMENTS FOR ZEROES OR NEGATIVE INTEGERS
% .
%
*/
for i1 in 1...iq {
if ((cr[i1 - 1].isZero) && (cr2[i1 - 1].isZero) && (ci[i1 - 1].isZero) && (ci2[i1 - 1].isZero)) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Abort - denominator argument was equal to zero", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
if ((ci[i1 - 1].isZero) && (ci2[i1 - 1].isZero) && (b[i1 - 1].re < 0)) {
ex1 = (abs(b[i1 - 1].re) - round(b[i1 - 1].re))
ex2 = SSMath.pow1(10, Helpers.makeFP(-nmach))
if ((ex1 < ex2) && (icount >= ifix(-round(b[i1 - 1].re)) || icount == -1)) {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Abort - denominator argument was equal to zero", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
}
}
nmach = ifix(SSMath.log101(SSMath.pow1(2, Helpers.makeFP(ibit))))
nsigfig = min(nsigfig, nmach)
accy = SSMath.pow1(10, Helpers.makeFP(-nsigfig))
do {
l = try ipremax(a: a, b: b, ip: ip, iq: iq, z: z)
}
catch {
throw error
}
var cex1: Complex<T>
var cex2: Complex<T>
if (l != 1) {
/*
%
% First, estimate the exponent of the maximum term in the pFq series
% .
%*/
expon = 0
xl = Helpers.makeFP(l)
for i in 1...ip {
cex1 = a[i - 1] &++ xl
cex2 = cex1 &-- 1
expon = expon + factor(cex2).re - factor(a[i - 1] &-- 1).re
}
for i in 1...iq {
cex1 = b[i - 1] &++ xl
cex2 = cex1 &++ 1
expon = expon - factor(cex2).re + factor(b[i - 1] &-- 1).re
}
expon = (expon + xl) * SSMath.ComplexMath.log(z).re - factor(Complex<T>.init(re: xl, im: T.zero)).re
lmax = ifix(SSMath.log101(SSMath.exp1(1)) * expon)
l = lmax
/*
%
% Now, estimate the exponent of where the pFq series will terminate.
%
%
*/
temp1 = Complex<T>.init(re: 1, im: 0)
creal = 1
for i1 in 1...ip {
temp1 = temp1 &** Complex<T>(ar[i1 - 1],ai[i1 - 1]) &% sigfig
}
for i1 in 1...iq {
temp1 = temp1 &% (Complex<T>(cr[i1 - 1],ci[i1 - 1]) &% sigfig)
creal = creal * cr[i1 - 1]
}
temp1 = temp1 &** Complex<T>(xr,xi)
/*
%
% Triple it to make sure.
%
*/
l = 3 * l
/*
%
% Divide the number of significant figures necessary by the number
% of
% digits available per array position.
%
%
*/
e1 = Helpers.makeFP(l)
e2 = Helpers.makeFP(nsigfig)
e3 = Helpers.makeFP(nmach)
l = ifix(2 * e1 + e2 / e3) + 2
}
/*
%
% Make sure there are at least 5 array positions used.
%
*/
l = max(l, 5)
l = max(l, ix)
if l < 0 || l > length {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Abort - error in fn hyper: l must be < 777", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function)
}
if nsigfig > nmach {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Warning--the number of significant figures requested is greate than machine precision. Result is not as accurate as requested.", log: .log_stat, type: .error)
}
#else
print("Warning--the number of significant figures requested is greate than machine precision. Result is not as accurate as requested.")
#endif
}
sumr[-1 + aOffset] = 1
sumi[-1 + aOffset] = 1
numr[-1 + aOffset] = 1
numi[-1 + aOffset] = 1
denomr[-1 + aOffset] = 1
denomi[-1 + aOffset] = 1
for i in 0...l + 1 {
sumr[i + aOffset] = 0
sumi[i + aOffset] = 0
numr[i + aOffset] = 0
numi[i + aOffset] = 0
denomr[i + aOffset] = 0
denomi[i + aOffset] = 0
}
sumr[1 + aOffset] = 1
numr[1 + aOffset] = 1
denomr[1 + aOffset] = 1
cnt = sigfig
temp = Complex<T>(0,0)
oldtemp = temp
ixcnt = 0
e1 = Helpers.makeFP(ibit)
e2 = Helpers.makeFP(2)
rexp = ifix(e1 / e2)
x = Helpers.makeFP(rexp) * (sumr[l + 1 + aOffset] - 2)
rr10 = x * log2
ir10 = ifix(rr10)
rr10 = rr10 - Helpers.makeFP(ir10)
x = Helpers.makeFP(rexp) * (sumi[l + 1 + aOffset] - 2)
ri10 = x * log2
ii10 = ifix(ri10)
ri10 = ri10 - Helpers.makeFP(ii10)
ex1 = sumr[1 + aOffset] * rmax * rmax
ex2 = sumr[2 + aOffset] * rmax
ex3 = sumr[3 + aOffset]
ex4 = ex1 + ex2 + ex3
dum1 = abs(ex4) * SSMath.sign(sumr[-1 + aOffset])
ex1 = sumi[1 + aOffset] * rmax * rmax
ex2 = sumi[2 + aOffset] * rmax
ex3 = sumi[3 + aOffset]
ex4 = ex1 + ex2 + ex3
dum2 = ex4 * SSMath.sign(sumi[-1 + aOffset])
dum1 = dum1 * SSMath.pow1(10, rr10)
dum2 = dum2 * SSMath.pow1(10, ri10)
cdum1 = Complex<T>(dum1,dum2)
x = Helpers.makeFP(rexp) * (denomr[l + 1 + aOffset] - 2)
rr10 = x * log2
ir10 = ifix(rr10)
rr10 = rr10 - Helpers.makeFP(ir10)
x = Helpers.makeFP(rexp) * (denomi[l + 1 + aOffset] - 2)
ri10 = x * log2
ii10 = ifix(ri10)
ri10 = ri10 - Helpers.makeFP(ii10)
ex1 = denomr[1 + aOffset] * rmax * rmax
ex2 = denomr[2 + aOffset] * rmax
ex3 = ex1 + ex2 + denomr[3 + aOffset]
ex4 = abs(ex3)
ex5 = denomr[-1 + aOffset]
dum1 = ex4 * SSMath.sign(ex5)
ex1 = denomi[1 + aOffset] * rmax * rmax
ex2 = denomi[2 + aOffset] * rmax
ex3 = ex1 + ex2 + denomi[3 + aOffset]
dum2 = abs(ex3) * SSMath.sign(denomi[-1 + aOffset])
dum1 = dum1 * SSMath.pow1(10, rr10)
dum2 = dum2 * SSMath.pow1(10, ri10)
cdum2 = Complex<T>(dum1, dum2)
temp = cdum1 &% cdum2
goon1 = 1
while goon1 == 1 {
goon1 = 0
if (ip < 0) {
if (sumr[1 + aOffset] < T.half) {
mx1 = sumi[l + 1 + aOffset]
}
else if (sumi[1 + aOffset] < T.half) {
mx1 = sumr[l + 1 + aOffset]
}
else {
mx1 = max(sumr[l + 1 + aOffset],sumi[l + 1 + aOffset])
}
if (numr[1 + aOffset] < T.half) {
mx2 = numi[l + 1 + aOffset]
}
else if (numi[1 + aOffset] < T.half) {
mx2 = numr[l + 1 + aOffset]
}
else {
mx2 = max(numr[l + 1 + aOffset],numi[l + 1 + aOffset])
}
if (mx1 - mx2 > 2) {
if (creal >= 0) {
if ((temp1 &% cnt).abs <= 1) {
do {
try arydiv(ar: &sumr, ai: &sumi, br: &denomr, bi: &denomi, c: &final, l: l, lnpfq: lnpfq, rmax: rmax, ibit: ibit)
}
catch {
throw error
}
ans = final
return ans
}
}
}
}
else {
do {
try arydiv(ar: &sumr, ai: &sumi, br: &denomr, bi: &denomi, c: &temp, l: l, lnpfq: lnpfq, rmax: rmax, ibit: ibit)
}
catch {
throw error
}
// %
// % First, estimate the exponent of the maximum term in the pFq
// % series.
// %
expon = 0
xl = Helpers.makeFP(ixcnt)
for i in 1...ip {
cex1 = a[i - 1] &++ xl
cex2 = cex1 &-- 1
expon = expon + factor(cex2).re - factor(a[i - 1] &-- T.one).re
}
for i in 1...iq {
cex1 = b[i - 1] &++ xl
cex2 = cex1 &-- 1
expon = expon - factor(cex2).re + factor(b[i - 1] &-- T.one).re
}
expon = expon + xl * SSMath.ComplexMath.log(z).re - factor(Complex<T>(xl,0)).re
lmax = ifix(SSMath.log101(SSMath.exp1(T.one)) * expon)
if ((oldtemp &-- temp).abs < (temp &** accy).abs) {
do {
try arydiv(ar: &sumr, ai: &sumi, br: &denomr, bi: &denomi, c: &final, l: l, lnpfq: lnpfq, rmax: rmax, ibit: ibit)
}
catch {
throw error
}
ans = final
return ans
}
temp = oldtemp
}
if ixcnt != icount {
ixcnt = ixcnt + 1
for i1 in 1...iq {
// %
// % TAKE THE CURRENT SUM AND MULTIPLY BY THE DENOMINATOR OF THE NEXT
// %
// % TERM, FOR BOTH THE MOST SIGNIFICANT HALF (CR,CI) AND THE LEAST
// %
// % SIGNIFICANT HALF (CR2,CI2).
// %
// %
cmpmul(ar: &sumr, ai: &sumi, br: cr[i1 - 1], bi: ci[i1 - 1], cr: &qr1, ci: &qi1, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
cmpmul(ar: &sumr, ai: &sumi, br: cr2[i1 - 1], bi: ci2[i1 - 1], cr: &qr2, ci: &qi2, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
qr2[l + 1 + aOffset] = qr2[l + 1 + aOffset] - T.one
qi2[l + 1 + aOffset] = qi2[l + 1 + aOffset] - T.one
// %
// % STORE THIS TEMPORARILY IN THE SUM ARRAYS.
// %
// %
cmpadd(ar: &qr1, ai: &qi1, br: &qr2, bi: &qi2, cr: &sumr, ci: &sumi, wk1: &wk1, l: l, rmax: rmax)
}
// %
// % MULTIPLY BY THE FACTORIAL TERM.
// %
foo1 = sumr
foo2 = sumr
armult(a: &foo1, b: cnt, c: &foo2, z: &wk6, l: l, rmax: rmax)
sumr = foo2
foo1 = sumi
foo2 = sumi
armult(a: &foo1, b: cnt, c: &foo2, z: &wk6, l: l, rmax: rmax)
sumi = foo2
// %
// % MULTIPLY BY THE SCALING FACTOR, SIGFIG, TO KEEP THE SCALE CORRECT.
// %
for _ in 1...ip-iq {
foo1 = sumr
foo2 = sumr
armult(a: &foo1, b: sigfig, c: &foo2, z: &wk6, l: l, rmax: rmax)
sumr = foo2
foo1 = sumi
foo2 = sumi
armult(a: &foo1, b: sigfig, c: &foo2, z: &wk6, l: l, rmax: rmax)
sumi = foo2
}
for i1 in 1...iq {
// %
// % UPDATE THE DENOMINATOR.
// %
// %
cmpmul(ar: &denomr, ai: &denomi, br: cr[i1 - 1], bi: ci[i1 - 1], cr: &qr1, ci: &qi1, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
cmpmul(ar: &denomr, ai: &denomi, br: cr2[i1 - 1], bi: ci2[i1 - 1], cr: &qr2, ci: &qi2, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
qr2[l + 1 + aOffset] = qr2[l + 1 + aOffset] - T.one
qi2[l + 1 + aOffset] = qi2[l + 1 + aOffset] - T.one
cmpadd(ar: &qr1, ai: &qi1, br: &qr2, bi: &qi2, cr: &denomr, ci: &denomi, wk1: &wk1, l: l, rmax: rmax)
}
// %
// %
// % MULTIPLY BY THE FACTORIAL TERM.
// %
foo1 = denomr
foo2 = denomr
armult(a: &foo1, b: cnt, c: &foo2, z: &wk6, l: l, rmax: rmax)
denomr = foo2
foo2 = denomi
foo1 = denomi
armult(a: &foo1, b: cnt, c: &foo2, z: &wk6, l: l, rmax: rmax)
denomi = foo2
// %
// % MULTIPLY BY THE SCALING FACTOR, SIGFIG, TO KEEP THE SCALE CORRECT.
// %
for _ in 1...ip-iq {
foo1 = denomr
foo2 = denomr
armult(a: &foo1, b: sigfig, c: &foo2, z: &wk6, l: l, rmax: rmax)
denomr = foo2
foo1 = denomi
foo2 = denomi
armult(a: &foo1, b: sigfig, c: &foo2, z: &wk6, l: l, rmax: rmax)
denomi = foo2
}
// %
// % FORM THE NEXT NUMERATOR TERM BY MULTIPLYING THE CURRENT
// % NUMERATOR TERM (AN ARRAY) WITH THE A ARGUMENT (A SCALAR).
// %
for i1 in 1...ip {
cmpmul(ar: &numr, ai: &numi, br: ar[i1 - 1], bi: ai[i1 - 1], cr: &qr1, ci: &qi1, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
cmpmul(ar: &numr, ai: &numi, br: ar2[i1 - 1], bi: ai2[i1 - 1], cr: &qr2, ci: &qi2, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
qr2[l + 1 + aOffset] = qr2[l + 1 + aOffset] - T.one
qi2[l + 1 + aOffset] = qi2[l + 1 + aOffset] - T.one
cmpadd(ar: &qr1, ai: &qi1, br: &qr2, bi: &qi2, cr: &numr, ci: &numi, wk1: &wk1, l: l, rmax: rmax)
}
// %
// % FINISH THE NEW NUMERATOR TERM BY MULTIPLYING BY THE Z ARGUMENT.
// %
cmpmul(ar: &numr, ai: &numi, br: xr, bi: xi, cr: &qr1, ci: &qi1, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
cmpmul(ar: &numr, ai: &numi, br: xr2, bi: xi2, cr: &qr2, ci: &qi2, wk1: &wk1, wk2: &wk2, cr2: &wk3, d1: &wk4, d2: &wk5, wk6: &wk6, l: l, rmax: rmax)
qr2[l + 1 + aOffset] = qr2[l + 1 + aOffset] - T.one
qi2[l + 1 + aOffset] = qi2[l + 1 + aOffset] - T.one
cmpadd(ar: &qr1, ai: &qi1, br: &qr2, bi: &qi2, cr: &numr, ci: &numi, wk1: &wk1, l: l, rmax: rmax)
// %
// % MULTIPLY BY THE SCALING FACTOR, SIGFIG, TO KEEP THE SCALE CORRECT.
// %
for _ in 1...iq-ip {
foo1 = numr
foo2 = numr
armult(a: &foo1, b: sigfig, c: &foo2, z: &wk6, l: l, rmax: rmax)
numr = foo2
foo1 = numi
foo2 = numi
armult(a: &foo1, b: sigfig, c: &foo2, z: &wk6, l: l, rmax: rmax)
numi = foo2
}
// %
// % FINALLY, ADD THE NEW NUMERATOR TERM WITH THE CURRENT RUNNING
// % SUM OF THE NUMERATOR AND STORE THE NEW RUNNING SUM IN SUMR, SUMI.
// %
foo1 = sumr
foo2 = sumr
bar1 = sumi
bar2 = sumi
cmpadd(ar: &foo1, ai: &bar1, br: &numr, bi: &numi, cr: &foo2, ci: &bar2, wk1: &wk1, l: l, rmax: rmax)
sumi = bar2
sumr = foo2
// %
// % BECAUSE SIGFIG REPRESENTS "ONE" ON THE NEW SCALE, ADD SIGFIG
// % TO THE CURRENT COUNT AND, CONSEQUENTLY, TO THE IP ARGUMENTS
// % IN THE NUMERATOR AND THE IQ ARGUMENTS IN THE DENOMINATOR.
// %
cnt = cnt + sigfig
for i1 in 1...ip {
ar[i1 - 1] = ar[i1 - 1] + sigfig
}
for i1 in 1...iq {
cr[i1 - 1] = cr[i1 - 1] + sigfig
}
goon1 = 1
}
}
do {
try arydiv(ar: &sumr, ai: &sumi, br: &denomr, bi: &denomi, c: &final, l: l, lnpfq: lnpfq, rmax: rmax, ibit: ibit)
ans = final
}
catch {
throw error
}
return final
}
fileprivate func fix<T: SSFloatingPoint>(_ x: T) -> T {
let i: Int = Helpers.integerValue(x)
let f: T = Helpers.makeFP(i)
return f
}
fileprivate func ifix<T: SSFloatingPoint>(_ x: T) -> Int {
let i: Int = Helpers.integerValue(x)
return i
}
fileprivate func bits<T: SSFloatingPoint>() -> T {
var bit, bit2: T
var count: T
bit = 1
count = 1
count = count + 1
bit2 = bit * 2
bit = bit2 + 1
while !(bit - bit2).isZero {
count = count + 1
bit2 = bit * 2
bit = bit2 + 1
}
bit = count - 3
return bit
}
// FORTRAN ARRAYS START WITH -1
fileprivate let aOffset = 1
/*
% ****************************************************************
% * *
% * SUBROUTINE ARADD *
% * *
% * *
% * Description : Accepts two arrays of numbers and returns *
% * the sum of the array. Each array is holding the value *
% * of one number in the series. The parameter L is the *
% * size of the array representing the number and RMAX is *
% * the actual number of digits needed to give the numbers *
% * the desired accuracy. *
% * *
% * Subprograms called: none *
% * *
% ****************************************************************
*/
fileprivate func aradd<T: SSFloatingPoint>(a: inout Array<T>, b: inout Array<T>, c: inout Array<T>, z: inout Array<T>, l: Int, rmax: T) {
let one: T = T.one
let zero: T = T.zero
let half: T = T.half
var ediff, I,i: Int
var goon300: Int = 1
var goon190: Int = 1
I = 0
ediff = 0
for i in stride(from: 0, through: l + 1, by: 1) {
z[i + aOffset] = zero
}
ediff = Helpers.integerValue(round(a[l + 1 + aOffset] - b[l + 1 + aOffset]))
if (abs(a[1 + aOffset]) < half || ediff <= -l) {
for i in -1...l + 1 {
c[i + aOffset] = b[i + aOffset]
I = i
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = zero
}
return;
}
else {
if (abs(b[1 + aOffset]) < half || ediff >= l) {
for i in -1...l + 1 {
c[i + aOffset] = a[i + 2]
I = i
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = zero
}
return
}
else {
z[-1 + aOffset] = a[-1 + aOffset]
goon300 = 1
goon190 = 1
if (abs(a[-1 + aOffset] - b[-1 + aOffset]) >= half) {
goon300 = 0
if (ediff > 0) {
z[l + 1 + aOffset] = a[l + 1 + aOffset]
}
else if (ediff < 0) {
z[l + 1 + aOffset] = b[l + 1 + aOffset]
z[-1 + aOffset] = b[-1 + aOffset]
goon190 = 0
}
else {
for i in 1...l {
if (a[i + aOffset] > b[i + aOffset]) {
z[l+1 + aOffset] = a[l + 1 + aOffset]
break
}
if (a[i + aOffset] < b[i + aOffset]) {
z[l + 1 + aOffset] = b[l + 1 + aOffset]
z[-1 + aOffset] = b[-1 + aOffset]
goon190 = 0
}
I = i
}
}
}
else if ediff > 0 {
z[l + 1 + aOffset] = a[l + 1 + aOffset]
for i in stride(from: l, through: 1 + ediff, by: -1) {
z[i + aOffset] = a[i + aOffset] + b[i - ediff + aOffset] + z[i + aOffset]
if (z[i + aOffset] >= rmax) {
z[i + aOffset] = z[i + aOffset] - rmax
z[i - 1 + aOffset] = one
}
I = i
}
for i in stride(from: ediff, through: 1, by: -1) {
z[i + aOffset] = a[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] >= rmax) {
z[i + aOffset] = z[i + aOffset] - rmax
z[i - 1 + aOffset] = one
}
I = i
}
if (z[0 + aOffset] > half) {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = z[i - 1 + aOffset]
I = i
}
z[l + 1 + aOffset] = z[l + 1 + aOffset] + 1
z[0 + aOffset] = zero
}
}
else if ediff < 0 {
z[l + 1 + aOffset] = b[l + 1 + aOffset]
for i in stride(from: l, through: 1 - ediff, by: -1) {
z[i + aOffset] = a[i + ediff + aOffset] + b[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] >= rmax) {
z[i + aOffset] = z[i + aOffset] - rmax
z[i - 1 + aOffset] = one
}
I = i
}
for i in stride(from: 0 - ediff, through: 1, by: -1) {
z[i + aOffset] = b[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] >= rmax) {
z[i + aOffset] = z[i + aOffset] - rmax
z[i-1 + aOffset] = one
}
I = i
}
if (z[0 + aOffset] > half) {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = z[i - 1 + aOffset]
I = i
}
z[l + 1 + aOffset] = z[l + 1 + aOffset] + one
z[0 + aOffset] = 0
}
}
else {
z[l + 1 + aOffset] = a[l + 1 + aOffset]
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = a[i + aOffset] + b[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] >= rmax) {
z[i + aOffset] = z[i + aOffset] - rmax
z[i - 1 + aOffset] = one
}
I = i
}
if (z[0 + aOffset] > half) {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = z[i - 1 + aOffset]
I = i
}
z[l + 1 + aOffset] = z[l + 1 + aOffset] + one
z[0 + aOffset] = zero
}
}
if goon300 == 1 {
i = I // %here is the line that had a +1 taken from it.
while (z[i + aOffset] < half && i < l + 1) {
i = i + 1
}
if (i == l + 1) {
z[-1 + aOffset] = one
z[l + 1 + aOffset] = 0
for i in -1...l + 1 {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
return
}
for j in 1...l + 1 - i {
z[j + aOffset] = z[j + i - 1 + aOffset]
}
/// TODO: ???
for j in stride(from: l + 2 - 1, through: l, by: -1) {
z[j + aOffset] = 0
}
z[l + 1 + aOffset] = z[l + 1 + aOffset] - Helpers.makeFP(i) + 1
for i in stride(from: -1, through: l + 1, by: 1) {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
return
}
if goon190 == 1{
if ediff > 0 {
for i in stride(from: l, through: 1 + ediff, by: -1) {
z[i + aOffset] = a[i + aOffset] - b[i - ediff + aOffset] + z[i + aOffset]
if (z[i + aOffset] < 0) {
z[i + aOffset] = z[i + aOffset] + rmax
z[i - 1 + aOffset] = -one
}
}
for i in stride(from: ediff, through: 1, by: -1) {
z[i + aOffset] = a[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] < 0) {
z[i + aOffset] = z[i + aOffset] + rmax
z[i - 1 + aOffset] = -one
}
}
}
else {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = a[i + aOffset] - b[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] < 0) {
z[i + aOffset] = z[i + aOffset] + rmax
z[i - 1 + aOffset] = -one
}
}
}
if (z[1 + aOffset] > half) {
for i in -1...l + 1 {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
return
}
i = 1
i = i + 1
while (z[i + aOffset] < half && i < l + 1) {
i = i + 1
}
if (i == l + 1) {
z[-1 + aOffset] = one
z[l + 1 + aOffset] = 0
for i in -1...l + 1 {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
return
}
}
}
if ediff < 0 {
for i in stride(from: l, through: 1 - ediff, by: -1) {
z[i + aOffset] = b[i + 2] - a[i + ediff + aOffset] + z[i + aOffset]
if (z[i + aOffset] < 0) {
z[i + aOffset] = z[i + aOffset] + rmax
z[i - 1 + aOffset] = -one
}
}
for i in stride(from: 0 - ediff, through: 1, by: -1) {
z[i + aOffset] = b[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] < 0) {
z[i + aOffset] = z[i + aOffset] + rmax
z[i - 1 + aOffset] = -one
}
}
} else {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = b[i + aOffset] - a[i + aOffset] + z[i + aOffset]
if (z[i + aOffset] < 0) {
z[i + aOffset] = z[i + aOffset] + rmax
z[i - 1 + aOffset] = -one
}
}
}
}
if (z[1 + aOffset] > half) {
for i in -1...l + 1 {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
return
}
i = 1
i = i + 1
while (z[i + aOffset] < half && i < l + 1 ) {
i = i + 1
}
if (i == l + 1) {
z[-1 + aOffset] = one
z[l + 1 + aOffset] = 0
for i in -1...l+1 {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
return
}
for j in 1...l + 1 - i {
z[j + aOffset] = z[j + i - 1 + aOffset]
}
for j in stride(from: l + 2 - i, through: l, by: -1) {
z[j + aOffset] = 0
}
z[l + 1 + aOffset] = z[l + 1 + aOffset] - Helpers.makeFP(i) + 1
for i in -1...l + 1 {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
}
/*
% ****************************************************************
% * *
% * SUBROUTINE ARSUB *
% * *
% * *
% * Description : Accepts two arrays and subtracts each element *
% * in the second array from the element in the first array *
% * and returns the solution. The parameters L and RMAX are *
% * the size of the array and the number of digits needed for *
% * the accuracy, respectively. *
% * *
% * Subprograms called: ARADD *
% * *
% ****************************************************************
*/
fileprivate func arsub<T: SSFloatingPoint>(a: inout Array<T>, b: inout Array<T>, c: inout Array<T>, wk1: inout Array<T>, wk2: inout Array<T>, l: Int, rmax: T) {
let one: T = T.one
for i in -1...l + 1 {
wk2[i + aOffset] = b[i + aOffset]
}
wk2[-1 + aOffset] = -one * wk2[-1 + aOffset]
aradd(a: &a, b: &wk2, c: &c, z: &wk1, l: l, rmax: rmax)
}
/*
%
% ****************************************************************
% * *
% * SUBROUTINE ARMULT *
% * *
% * *
% * Description : Accepts two arrays and returns the product. *
% * L and RMAX are the size of the arrays and the number of *
% * digits needed to represent the numbers with the required *
% * accuracy. *
% * *
% * Subprograms called: none *
% * *
% ****************************************************************
*/
fileprivate func armult<T: SSFloatingPoint>(a: inout Array<T>, b: T, c: inout Array<T>, z: inout Array<T>, l: Int, rmax: T) {
let eps: T = T.ulpOfOne
let one: T = T.one
let half: T = T.half
var b2: T = 0
var carry: T = 0
z[-1 + aOffset] = SSMath.sign(b) * a[-1 + aOffset]
b2 = abs(b)
z[l + 1 + aOffset] = a[l + 1 + aOffset]
for i in 0...l {
z[i + aOffset] = 0
}
if (b2 <= eps || a[1 + aOffset] <= eps) {
z[-1 + aOffset] = one
z[l + 1 + aOffset] = 0
}
else {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = a[i + aOffset] * b2 + z[i + aOffset]
if (z[i + aOffset] >= rmax) {
carry = Helpers.integerPart(z[i + aOffset] / rmax)
z[i + aOffset] = z[i + aOffset] - carry * rmax
z[i - 1 + aOffset] = carry
}
}
if (z[0 + aOffset] >= half) {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = z[i - 1 + aOffset]
}
z[l + 1 + aOffset] = z[l + 1 + aOffset] + one
if (z[1 + aOffset] >= rmax) {
for i in stride(from: l, through: 1, by: -1) {
z[i + aOffset] = z[i - 1 + aOffset]
}
carry = Helpers.integerPart(z[1 + aOffset] / rmax)
z[2 + aOffset] = z[2 + aOffset] - carry * rmax
z[1 + aOffset] = carry
z[l + 1 + aOffset] = z[l + 1 + aOffset] + one
}
z[0 + aOffset] = 0
}
}
for i in -1...l + 1 {
c[i + aOffset] = z[i + aOffset]
}
if (c[1 + aOffset] < half) {
c[-1 + aOffset] = one
c[l + 1 + aOffset] = 0
}
}
/*
% ****************************************************************
% * *
% * SUBROUTINE CMPADD *
% * *
% * *
% * Description : Takes two arrays representing one real and *
% * one imaginary part, and adds two arrays representing *
% * another complex number and returns two array holding the *
% * complex sum. *
% * (CR,CI) = (AR+BR, AI+BI) *
% * *
% * Subprograms called: ARADD *
% * *
% ****************************************************************
*/
fileprivate func cmpadd<T: SSFloatingPoint>(ar: inout Array<T>, ai: inout Array<T>, br: inout Array<T>, bi: inout Array<T>, cr: inout Array<T>, ci: inout Array<T>, wk1: inout Array<T>, l: Int, rmax: T) {
aradd(a: &ar, b: &br, c: &cr, z: &wk1, l: l, rmax: rmax)
aradd(a: &ai, b: &bi, c: &ci, z: &wk1, l: l, rmax: rmax)
}
/*
! ****************************************************************
! * *
! * SUBROUTINE CMPSUB *
! * *
! * *
! * Description : Takes two arrays representing one real and *
! * one imaginary part, and subtracts two arrays representing *
! * another complex number and returns two array holding the *
! * complex sum. *
! * (CR,CI) = (AR+BR, AI+BI) *
! * *
! * Subprograms called: ARADD *
! * *
! ****************************************************************
*/
fileprivate func cmpsub<T: SSFloatingPoint>(ar: inout Array<T>, ai: inout Array<T>, br: inout Array<T>, bi: inout Array<T>, cr: inout Array<T>, ci: inout Array<T>, wk1: inout Array<T>, wk2: inout Array<T>, l: Int, rmax: T) {
arsub(a: &ar, b: &br, c: &cr, wk1: &wk1, wk2: &wk2, l: l, rmax: rmax)
arsub(a: &ai, b: &bi, c: &ci, wk1: &wk1, wk2: &wk2, l: l, rmax: rmax)
}
/*
% ****************************************************************
% * *
% * SUBROUTINE CMPMUL *
% * *
% * *
% * Description : Takes two arrays representing one real and *
% * one imaginary part, and multiplies it with two arrays *
% * representing another complex number and returns the *
% * complex product. *
% * *
% * Subprograms called: ARMULT, ARSUB, ARADD *
% * *
% ****************************************************************
*/
fileprivate func cmpmul<T: SSFloatingPoint>(ar: inout Array<T>,ai: inout Array<T>,br: T,bi: T,cr: inout Array<T>,ci: inout Array<T>,wk1: inout Array<T>,wk2: inout Array<T>,cr2: inout Array<T>,d1: inout Array<T>,d2: inout Array<T>,wk6: inout Array<T>,l: Int,rmax: T) {
armult(a: &ar, b: br, c: &d1, z: &wk6, l: l, rmax: rmax)
armult(a: &ai, b: bi, c: &d2, z: &wk6, l: l, rmax: rmax)
arsub(a: &d1, b: &d2, c: &cr2, wk1: &wk1, wk2: &wk2, l: l, rmax: rmax)
armult(a: &ar, b: bi, c: &d1, z: &wk6, l: l, rmax: rmax)
armult(a: &ai, b: br, c: &d2, z: &wk6, l: l, rmax: rmax)
aradd(a: &d1, b: &d2, c: &ci, z: &wk1, l: l, rmax: rmax)
for i in -1...l + 1 {
cr[i + aOffset] = cr2[i + aOffset]
}
}
/*
% ****************************************************************
% * *
% * SUBROUTINE ARYDIV *
% * *
% * *
% * Description : Returns the double precision complex number *
% * resulting from the division of four arrays, representing *
% * two complex numbers. The number returned will be in one *
% * of two different forms: either standard scientific or as *
% * the log (base 10) of the number. *
% * *
% * Subprograms called: CONV21, CONV12, EADD, ECPDIV, EMULT. *
% * *
% ****************************************************************
*/
fileprivate func arydiv<T: SSFloatingPoint>(ar: inout Array<T>,ai: inout Array<T>,br: inout Array<T>,bi: inout Array<T>,c: inout Complex<T>,l: Int,lnpfq: Int,rmax: T,ibit: Int) throws {
var cdum: Complex<T> = Complex<T>.init(re: 0, im: 0)
var c: Complex<T> = Complex<T>.init(re: 0, im: 0)
var dum1 , dum2 , e1 , e2 ,e3 , n1 , n2 , n3 , phi , ri10 , rr10 , tenmax , x ,x1 , x2: T
var ii10 , ir10, rexp: Int
var be: Array<Array<T>>
var ae: Array<Array<T>> /* = Array<Array<T>>.init(repeating: Array<T>.init(repeating: 0, count: 2), count: 2) */
var ce: Array<Array<T>> = Array<Array<T>>.init(repeating: Array<T>.init(repeating: 0, count: 2), count: 2)
var ex1: T
var ex2: T
var ex3: T
rexp = ibit / 2
x = Helpers.makeFP(rexp) * (ai[l + aOffset + 1] - 2)
rr10 = x * SSMath.log1(2) / SSMath.log101(10)
ir10 = Helpers.integerValue(rr10)
rr10 = rr10 - Helpers.makeFP(ir10)
x = Helpers.makeFP(rexp) * (ai[l + 1 + aOffset] - 2)
ri10 = x * SSMath.log101(2) / SSMath.log101(10)
ii10 = Helpers.integerValue(ri10)
ri10 = ri10 - Helpers.makeFP(ii10)
ex1 = ar[1 + aOffset] * rmax * rmax
ex2 = ex1 + (ar[2 + aOffset] * rmax)
ex3 = ex2 + ar[3 + aOffset]
dum1 = abs(ex3) * SSMath.sign(ar[-1 + aOffset])
ex1 = ai[1 + aOffset] * rmax * rmax
ex2 = ex1 + ai[2 + aOffset] * rmax
ex3 = ex2 + ai[3 + aOffset]
dum2 = abs(ex3) * SSMath.sign(ai[-1 + aOffset])
dum1 = dum1 * SSMath.pow1(10, rr10)
dum2 = dum2 * SSMath.pow1(10, ri10)
cdum.re = dum1
cdum.im = dum2
ae = conv12(cn: cdum)
ae[0][1] = ae[0][1] + Helpers.makeFP(ir10)
ae[1][1] = ae[1][1] + Helpers.makeFP(ii10)
x = Helpers.makeFP(rexp) * (br[l + 1 + aOffset] - 2)
rr10 = x * SSMath.log101(2) / SSMath.log101(10)
ir10 = Helpers.integerValue(rr10)
rr10 = rr10 - Helpers.makeFP(ir10)
x = Helpers.makeFP(rexp) * (bi[l + 1 + aOffset] - 2)
ri10 = x * SSMath.log101(2) / SSMath.log101(10)
ii10 = Helpers.integerValue(ri10)
ri10 = ri10 - Helpers.makeFP(ii10)
ex1 = br[1 + aOffset] * rmax * rmax
ex2 = ex1 + br[2 + aOffset] * rmax
ex3 = ex2 + br[3 + aOffset]
dum1 = abs(ex3) * SSMath.sign(br[-1 + aOffset])
ex1 = bi[1 + aOffset] * rmax * rmax
ex2 = ex1 + bi[2 + aOffset] * rmax
ex3 = ex2 + bi[3 + aOffset]
dum2 = abs(ex3) * SSMath.sign(bi[-1 + aOffset])
dum1 = dum1 * SSMath.pow1(10, rr10)
dum2 = dum2 * SSMath.pow1(10, ri10)
be = conv12(cn: cdum)
be[0][1] = be[0][1] + Helpers.makeFP(ir10)
be[1][1] = be[1][1] + Helpers.makeFP(ii10)
ecpdiv(&ae, &be, &ce)
tenmax = Helpers.makeFP(T.greatestFiniteMagnitude.exponent - 2) * T.ln2 / T.ln10
if lnpfq == 0 {
do {
c = try conv21(cae: ce)
}
catch {
throw error
}
}
else {
n1 = 0
e1 = 0
n2 = 0
e2 = 0
n3 = 0
e3 = 0
emult(ce[0][0], ce[0][1], ce[0][0], ce[0][1], &n1, &e1)
emult(ce[1][0], ce[1][1], ce[1][0], ce[1][1], &n2, &e2)
eadd(n1, e1, n2, e2, &n3, &e3)
n1 = ce[0][0]
e1 = ce[0][1] - ce[1][1]
x2 = ce[1][0]
if e1 > tenmax {
x1 = tenmax
}
else if (e1 < -tenmax) {
x1 = 0
}
else {
x1 = n1 * SSMath.pow1(10, e1)
}
if !x2.isZero {
phi = SSMath.atan21(x2, x1)
}
else {
phi = T.zero
}
c = Complex<T>.init(re: 0, im: 0)
c.re = T.half * (SSMath.log1(n3) + e3 * T.ln10)
c.im = phi
}
}
/*
% ****************************************************************
% * *
% * SUBROUTINE CONV12 *
% * *
% * *
% * Description : Converts a number from complex notation to a *
% * form of a 2x2 real array. *
% * *
% * Subprograms called: none *
% * *
% ****************************************************************
*/
fileprivate func conv12<T: SSFloatingPoint>(cn: Complex<T>) -> Array<Array<T>> {
var cae: Array<Array<T>> = Array<Array<T>>.init(repeating: Array<T>.init(repeating: 0, count: 2), count: 2)
cae[0][0] = cn.re
cae[0][1] = T.zero
while true {
if abs(cae[0][0]) < 10 {
while true {
if ((abs(cae[0][0]) >= T.one) || (cae[0][0].isZero)) {
cae[1][0] = cn.im
cae[1][1] = T.zero
while true {
if (abs(cae[1][0]) < 10) {
while ((abs(cae[1][0]) < T.one) && !cae[1][0].isZero) {
cae[1][0] = cae[1][0] * 10
cae[1][1] = cae[1][1] - T.one
}
break;
}
else {
cae[1][0] = cae[1][0] / 10
cae[1][1] = cae[1][1] + T.one
}
}
break;
}
else {
cae[0][0] = cae[0][0] * 10
cae[0][1] = cae[0][1] - T.one
}
}
break;
}
else {
cae[0][0] = cae[0][0] / 10
cae[0][1] = cae[0][1] + T.one
}
}
return cae
}
/*
% ****************************************************************
% * *
% * SUBROUTINE CONV21 *
% * *
% * *
% * Description : Converts a number represented in a 2x2 real *
% * array to the form of a complex number. *
% * *
% * Subprograms called: none *
% * *
% ****************************************************************
*/
fileprivate func conv21<T: SSFloatingPoint>(cae: Array<Array<T>>) throws -> Complex<T> {
var cn: Complex<T> = Complex<T>.init(re: 0, im: 0)
cn.re = 0
cn.im = 0
let tenmax:T = Helpers.makeFP(T.greatestFiniteMagnitude.exponent - 2) * T.ln2 / T.ln10
if cae[0][1] > tenmax || cae[1][1] > tenmax {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("value of exponent required for summation: pFq", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .maxExponentExceeded, file: #file, line: #line, function: #function)
}
else if cae[1][1] < -tenmax {
cn.re = cae[0][0] * SSMath.pow1(10, cae[0][1])
cn.im = 0
}
else {
cn.re = cae[0][0] * SSMath.pow1(10, cae[0][1])
cn.im = cae[1][0] * SSMath.pow1(10, cae[1][1])
}
return cn
}
/*
% ****************************************************************
% * *
% * SUBROUTINE ECPDIV *
% * *
% * *
% * Description : Divides two numbers and returns the solution. *
% * All numbers are represented by a 2x2 array. *
% * *
% * Subprograms called: EADD, ECPMUL, EDIV, EMULT *
% * *
% ****************************************************************
*/
fileprivate func ecpdiv<T: SSFloatingPoint>(_ a: inout Array<Array<T>>, _ b: inout Array<Array<T>>, _ c: inout Array<Array<T>>) {
var b2: Array<Array<T>> = Array<Array<T>>.init(repeating: Array<T>.init(repeating: 0, count: 2), count: 2)
var c2: Array<Array<T>> = Array<Array<T>>.init(repeating: Array<T>.init(repeating: 0, count: 2), count: 2)
var e1: T = 0
var e2: T = 0
var e3: T = 0
var n1: T = 0
var n2:T = 0
var n3: T = 0
b2[0][0] = b[0][0]
b2[0][1] = b[0][1]
b2[1][0] = -T.one * b[1][0]
b2[1][1] = b[1][1]
ecpmul(&a, &b2, &c2)
emult(b[0][0], b[0][1], b[0][0], b[0][1], &n1, &e1)
emult(b[1][0], b[1][1], b[1][0], b[1][1], &n2, &e2)
eadd(n1, e1, n2, e2, &n3, &e3)
ediv(c2[0][0], c2[0][1], n3, e3, &n1, &e1)
ediv(c2[1][0], c2[1][1], n3, e3, &n2, &e2)
c[0][0] = n1
c[0][1] = e1
c[1][0] = n2
c[1][1] = e2
}
/*
% ****************************************************************
% * *
% * SUBROUTINE EMULT *
% * *
% * *
% * Description : Takes one base and exponent and multiplies it *
% * by another numbers base and exponent to give the product *
% * in the form of base and exponent. *
% * *
% * Subprograms called: none *
% * *
% ****************************************************************
*/
fileprivate func emult<T: SSFloatingPoint>(_ n1: T, _ e1: T, _ n2: T, _ e2: T, _ nf: inout T, _ ef: inout T) {
nf = n1 * n2
ef = e1 + e2
if abs(nf) >= 10 {
nf = nf / 10
ef = ef + T.one
}
}
/*
% ****************************************************************
% * *
% * SUBROUTINE EDIV *
% * *
% * *
% * Description : returns the solution in the form of base and *
% * exponent of the division of two exponential numbers. *
% * *
% * Subprograms called: none *
% * *
% ****************************************************************
*/
fileprivate func ediv<T: SSFloatingPoint>(_ n1: T, _ e1: T, _ n2: T, _ e2: T, _ nf: inout T, _ ef: inout T) {
nf = n1 / n2
ef = e1 - e2
if abs(nf) < T.one && !nf.isZero {
nf = nf * 10
ef = ef - T.one
}
}
/*
% ****************************************************************
% * *
% * SUBROUTINE ECPMUL *
% * *
% * *
% * Description : Multiplies two numbers which are each *
% * represented in the form of a two by two array and returns *
% * the solution in the same form. *
% * *
% * Subprograms called: EMULT, ESUB, EADD *
% * *
% ****************************************************************
*/
fileprivate func ecpmul<T: SSFloatingPoint>(_ a: inout Array<Array<T>>, _ b: inout Array<Array<T>>, _ c: inout Array<Array<T>>) {
var c2: Array<Array<T>> = Array<Array<T>>.init(repeating: Array<T>.init(repeating: 0, count: 2), count: 2)
var e1: T = 0
var e2: T = 0
var n1: T = 0
var n2:T = 0
var n3: T = 0
var e3: T = 0
emult(a[0][0], a[0][1], b[0][0], b[0][1], &n1, &e1)
emult(a[1][0], a[1][1], b[1][0], b[1][1], &n2, &e2)
esub(n1, e1, n2, e2, &n3, &e3)
c2[0][0] = n3
c2[0][1] = e3
emult(a[0][0], a[0][1], b[1][0], b[1][1], &n1, &e1)
emult(a[1][0], a[1][1], b[0][0], b[0][0], &n2, &e2)
eadd(n1, e1, n2, e2, &n3, &e3)
c[1][0] = n3
c[1][1] = e3
c[0][0] = c2[0][0]
c[0][1] = c2[0][1]
}
/*
% ****************************************************************
% * *
% * SUBROUTINE ESUB *
% * *
% * *
% * Description : Returns the solution to the subtraction of *
% * two numbers in the form of base and exponent. *
% * *
% * Subprograms called: EADD *
% * *
% ****************************************************************
*/
fileprivate func esub<T: SSFloatingPoint>(_ n1: T, _ e1: T, _ n2: T, _ e2: T, _ nf: inout T, _ ef: inout T) {
let dummy: T = -T.one * n2
eadd(n1, e1, dummy, e2, &nf, &ef)
}
/*
% ****************************************************************
% * *
% * SUBROUTINE EADD *
% * *
% * *
% * Description : Returns the sum of two numbers in the form *
% * of a base and an exponent. *
% * *
% * Subprograms called: none *
% * *
% ****************************************************************
*/
fileprivate func eadd<T: SSFloatingPoint>(_ n1: T, _ e1: T, _ n2: T, _ e2: T, _ nf: inout T, _ ef: inout T) {
let ediff: T = e1 - e2
if (ediff > 36) {
nf = n1
ef = e1
}
else if (ediff < -36) {
nf = n2
ef = e2
}
else {
nf = n1 * SSMath.pow1( Helpers.makeFP(10), ediff) + n2
ef = e2
while true {
if (abs(nf) < 10) {
while ((abs(nf) < T.one) && (!nf.isZero)) {
nf = nf * 10
ef = ef - T.one
}
break;
}
else {
nf = nf / 10
ef = ef + T.one
}
}
}
}
/*
% ****************************************************************
% * *
% * FUNCTION IPREMAX *
% * *
% * *
% * Description : Predicts the maximum term in the pFq series *
% * via a simple scanning of arguments. *
% * *
% * Subprograms called: none. *
% * *
% ****************************************************************
*/
fileprivate func ipremax<T: SSFloatingPoint>(a: Array<Complex<T>>, b: Array<Complex<T>>, ip: Int, iq: Int, z: Complex<T>) throws -> Int {
var expon, xl, xmax, xterm: T
var cex1: Complex<T>
var cex2: Complex<T>
var cex3: Complex<T>
var ex1: T
var ex2: T
expon = 0
xl = 0
xmax = 0
xterm = 0
var ans: Int = 0
for j in stride(from: 1, through: 100000, by: 1) {
expon = T.zero
xl = Helpers.makeFP(j)
for i in stride(from: 1, through: ip, by: 1) {
cex1 = a[i - 1] &++ xl
cex2 = cex1 &-- T.one
cex3 = a[i - 1] &-- T.one
expon = expon + (factor(cex2)).re - factor(cex3).re
}
for i in stride(from: 1, to: iq, by: 1) {
cex1 = b[i - 1] &++ xl
cex2 = cex1 &-- T.one
cex3 = b[i - 1] &-- T.one
expon = expon - factor(cex1).re + factor(cex2).re
}
ex1 = xl * SSMath.ComplexMath.log(z).re
ex2 = expon + ex1
expon = ex2 - factor(Complex<T>(xl)).re
xmax = SSMath.log101(SSMath.exp1(T.one)) * expon
if ((xmax < xterm) && (j > 2)) {
ans = j
break
}
xterm = max(xmax, xterm)
}
if ans == 0 {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Max exponent not found", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function)
}
else {
return ans
}
}
/*
% ****************************************************************
% * *
% * FUNCTION FACTOR *
% * *
% * *
% * Description : This function is the log of the factorial. *
% * *
% * Subprograms called: none. *
% * *
% ****************************************************************
%
*/
fileprivate func factor<T: SSFloatingPoint>(_ z: Complex<T>) -> Complex<T> {
var pi: T = 0
var f: Complex<T>
if (((z.re == T.one) && (z.im.isZero)) || z.abs.isZero) {
f = Complex<T>.init(re: T.zero, im: T.zero)
return f
}
else {
pi = T.pi
var e1: T
var e3, e4: Complex<T>
e1 = (T.half * SSMath.log1(2 * pi))
e3 = (z &++ T.half)
e4 = (1 &% (12 &** z))
f = e1 &++ e3 &** SSMath.ComplexMath.log(z) &-- z &++ e4;
e3 = (1 &% (30 &** z &** z))
e4 = (2 &% (7 &** z &** z))
f = f &** (1 &-- e3 &** (1 &-- e4))
return f
}
}
/*
% ****************************************************************
% * *
% * FUNCTION CGAMMA *
% * *
% * *
% * Description : Calculates the complex gamma function. Based *
% * on a program written by F.A. Parpia published in Computer*
% * Physics Communications as the `GRASP2' program (public *
% * domain). *
% * *
% * *
% * Subprograms called: none. *
% * *
% *****************************************************************/
fileprivate func cgamma<T: SSFloatingPoint>(_ arg: Complex<T>, lnpfq: Int) throws -> Complex<T> {
var argi: T = 0
var argr: T = 0
var argui: T = 0
var argui2: T = 0
var argum: T = 0
var argur: T = 0
var argur2: T = 0
var clngi: T = 0
var clngr: T = 0
var diff: T = 0
var dnum: T = 0
var expmax: T = 0
var fac: T = 0
var facneg: T = 0
var hlntpi: T = 0
var obasq: T = 0
var obasqi: T = 0
var obasqr: T = 0
var ovlfac: T = 0
var ovlfi: T = 0
var ovlfr: T = 0
var pi: T = 0
var precis: T = 0
var tenmax: T = 0
var tenth: T = 0
var termi: T = 0
var termr: T = 0
var twoi: T = 0
var zfaci: T = 0
var zfacr: T = 0
var ex1: T
var ex2: T
var ex3: T
var first : Bool = true
var negarg : Bool = true
var fn: Array<T> = [1,-1, 1,-1, 5, -691, 7, -3617, 43867, -174611, 854513, -236364091, 8553103, -23749461029, 8615841276005, -7709321041217, 2577687858367, -26315271553053477373,2929993913841559,-261082718496449122051, 1520097643918070802691,27833269579301024235023]
let fd: Array<T> = [6,30,42,30,66,2730,6,510,789,330,138,2730, 6, 870,14322,510,6,1919190,6,13530,1806,960]
var ans: Complex<T> = Complex<T>.init(re: 0, im: 0)
hlntpi = Helpers.makeFP(1)
tenth = Helpers.makeFP(0.1)
argr = arg.re
argi = arg.im
if first {
pi = 4 * SSMath.atan1(T.one)
}
tenmax = Helpers.makeFP(T.greatestFiniteMagnitude.exponent - 1) * T.ln2 / T.ln10
dnum = SSMath.pow1(tenth, tenmax)
expmax = -SSMath.log1(dnum)
precis = T.one
precis = precis / 2
dnum = precis + T.one
while dnum > T.one {
precis = precis / 2
dnum = precis + T.one
}
precis = SSMath.pow1(2, precis)
hlntpi = T.half * SSMath.log1(2 * pi)
for i in stride(from: 1, through: fd.count, by: 1) {
fn[i] = fn[i - 1] / fd[i - 1]
twoi = 2 * Helpers.makeFP(i)
fn[i - 1] = fn[i - 1] / (twoi * (twoi - T.one))
}
first = false
if argi.isZero {
if argr <= 0 {
diff = abs(round(argr) - argr)
if diff <= 2 * precis {
#if os(macOS) || os(iOS)
if #available(macOS 10.12, iOS 13, *) {
os_log("Argument to close to a pols, mo imaginary part", log: .log_stat, type: .error)
}
#endif
throw SSSwiftyStatsError.init(type: .singularity, file: #file, line: #line, function: #function)
}
else {
if lnpfq == 1 {
ans.re = SSMath.lgamma1(argr)
}
else {
ans.re = SSMath.tgamma1(argr)
}
argum = pi / (-argr * SSMath.sin1(pi * argr))
if (argum < 0) {
argum = -argum
clngi = pi
}
else {
clngi = 0
}
facneg = SSMath.log1(argum)
argur = -argr
negarg = true
}
}
else {
clngi = 0
argur = argr
negarg = false
}
ovlfac = T.one
while argur < 10 {
ovlfac = ovlfac * argur;
argur = argur + T.one
}
ex1 = (argur - T.half)
ex2 = ex1 * SSMath.log1(argur)
ex3 = ex2 - argur
clngr = ex3 + hlntpi
fac = argur
obasq = T.one / (argur * argur)
for i in stride(from: 1, through: fn.count, by: 1) {
fac = fac * obasq
clngr = clngr + fn[i - 1] * fac
}
clngr = clngr - SSMath.log1(ovlfac)
if negarg {
clngr = facneg - clngr
}
}
else {
argur = argr
argui = argi
argui2 = argui * argui
ovlfr = T.one
ovlfi = T.zero
ex1 = argur * argur
argum = sqrt(ex1 + argui2)
while (argum < 10) {
termr = ovlfr * argur - ovlfi * argui
termi = ovlfr * argui + ovlfi * argur
ovlfr = termr
ovlfi = termi
argur = argur + T.one
argum = sqrt(argur * argur + argui2)
}
argur2 = argur * argur
termr = T.half * SSMath.log1(argur2 + argui2)
termi = SSMath.atan21(argui, argur)
ex1 = (argur - T.half) * termr
ex2 = argui * termi
ex3 = argur + hlntpi
clngr = ex1 - ex2 - ex3
ex1 = (argur - T.half) * termi
ex2 = argui * termr
clngi = ex1 + ex2 - argui
fac = SSMath.pow1(argur2 + argui2, -2)
obasqr = (argur2 - argui2) * fac
obasqi = -2 * argur * argui * fac
zfacr = argur
zfaci = argui
for i in stride(from: 1, through: fn.count, by: 1) {
termr = zfacr * obasqr - zfaci * obasqi
termi = zfacr * obasqi + zfaci * obasqr
fac = fn[i - 1]
clngr = clngr + termr * fac
clngi = clngi + termi * fac
zfacr = termr
zfaci = termi
}
ex1 = ovlfr * ovlfr
ex2 = ovlfi * ovlfi
ex3 = ex1 + ex2
clngr = clngr - T.half * SSMath.log1(ex3)
clngi = clngi - SSMath.atan21(ovlfi, ovlfr)
if lnpfq == 1 {
ans.re = clngr
ans.im = clngi
return ans
}
else {
if ((clngr <= expmax) && (clngr >= -expmax)) {
fac = SSMath.exp1(clngr)
}
else {
ans = Complex<T>.nan
}
ans.re = fac * SSMath.cos1(clngi)
ans.im = fac * SSMath.sin1(clngi)
}
}
return ans
}
| gpl-3.0 | b8924dc227995910df5bd8d3ddf52320 | 40.557509 | 270 | 0.38293 | 3.699741 | false | false | false | false |
silenteh/HKDFKit | HKDFKit/NSData+HexString.swift | 1 | 980 | //
// NSData+HexString.swift
// HKDFKit
//
// Created by silenteh on 07/02/16.
// Copyright © 2016 silenteh. All rights reserved.
//
import Foundation
extension String {
public func dataFromHexString() -> NSData {
var bytes = [UInt8]()
for i in 0..<(self.characters.count/2) {
let stringBytes = self.substringWithRange(Range(start:self.startIndex.advancedBy(2*i), end:self.startIndex.advancedBy(2*i+2)))
let byte = strtol((stringBytes as NSString).UTF8String, nil, 16)
bytes.append(UInt8(byte))
}
return NSData(bytes:bytes, length:bytes.count)
}
}
extension NSData {
func toHexString() -> String {
var hexString: String = ""
let dataBytes = UnsafePointer<CUnsignedChar>(self.bytes)
for (var i: Int=0; i<self.length; ++i) {
hexString += String(format: "%02x", dataBytes[i])
}
return hexString
}
}
| gpl-3.0 | 61de079b9863f0aceceac24b0b862c86 | 24.763158 | 138 | 0.588355 | 3.869565 | false | false | false | false |
asm-products/giraff-ios | Fun/DesignableTextField.swift | 1 | 1779 | enum TextFieldValidation {
case Valid, Invalid, Unknown
}
@IBDesignable class DesignableTextField: UITextField {
@IBOutlet var nextTextField: UITextField?
@IBInspectable var leftPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, leftPadding, 0))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
}
}
@IBInspectable var rightPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, 0, rightPadding))
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var validColor: UIColor = UIColor(red:0.25, green:0.68, blue:0.35, alpha:1)
@IBInspectable var invalidColor: UIColor = UIColor(red:0.73, green:0.24, blue:0.17, alpha:1)
@IBInspectable var defaultColor: UIColor = UIColor(red:0.59, green:0.65, blue:0.71, alpha:1)
var validated: TextFieldValidation = .Unknown {
didSet {
switch (validated) {
case .Valid:
self.borderColor = validColor
case .Invalid:
self.borderColor = invalidColor
case .Unknown:
self.borderColor = defaultColor
}
}
}
} | agpl-3.0 | fae9d0af1ddcddd38a0ec000e1ba9ca2 | 26.8125 | 96 | 0.568859 | 4.997191 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/ChangePassword/Controller/ChangePasswordViewController.swift | 1 | 8836 | import KsApi
import Library
import Prelude
import UIKit
final class ChangePasswordViewController: UIViewController, MessageBannerViewControllerPresenting {
@IBOutlet fileprivate var changePasswordLabel: UILabel!
@IBOutlet fileprivate var confirmNewPasswordLabel: UILabel!
@IBOutlet fileprivate var confirmNewPasswordTextField: UITextField!
@IBOutlet fileprivate var currentPasswordLabel: UILabel!
@IBOutlet fileprivate var currentPasswordTextField: UITextField!
@IBOutlet fileprivate var validationErrorMessageLabel: UILabel!
@IBOutlet fileprivate var newPasswordLabel: UILabel!
@IBOutlet fileprivate var newPasswordTextField: UITextField!
@IBOutlet fileprivate var scrollView: UIScrollView!
@IBOutlet fileprivate var stackView: UIStackView!
private var saveButtonView: LoadingBarButtonItemView!
internal var messageBannerViewController: MessageBannerViewController?
private let viewModel: ChangePasswordViewModelType = ChangePasswordViewModel()
internal static func instantiate() -> ChangePasswordViewController {
return Storyboard.Settings.instantiate(ChangePasswordViewController.self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.messageBannerViewController = self.configureMessageBannerViewController(on: self)
self.saveButtonView = LoadingBarButtonItemView.instantiate()
self.saveButtonView.setTitle(title: Strings.Save())
self.saveButtonView.addTarget(self, action: #selector(self.saveButtonTapped(_:)))
let navigationBarButton = UIBarButtonItem(customView: self.saveButtonView)
self.navigationItem.setRightBarButton(navigationBarButton, animated: false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.viewModel.inputs.viewDidAppear()
}
override func bindStyles() {
super.bindStyles()
_ = self.scrollView
|> \.alwaysBounceVertical .~ true
|> \.backgroundColor .~ .ksr_support_100
_ = self.stackView
|> \.layoutMargins .~ .init(topBottom: Styles.grid(1), leftRight: Styles.grid(2))
_ = self
|> settingsViewControllerStyle
|> UIViewController.lens.title %~ { _ in
Strings.Change_password()
}
_ = [self.currentPasswordLabel, self.newPasswordLabel, self.confirmNewPasswordLabel]
||> \.isAccessibilityElement .~ false
_ = self.changePasswordLabel
|> settingsDescriptionLabelStyle
|> UILabel.lens.text %~ { _ in
Strings.Well_ask_you_to_sign_back_into_the_Kickstarter_app_once_youve_changed_your_password()
}
_ = self.confirmNewPasswordLabel
|> settingsTitleLabelStyle
|> UILabel.lens.text %~ { _ in Strings.Confirm_password() }
_ = self.confirmNewPasswordTextField
|> settingsNewPasswordFormFieldAutoFillStyle
|> \.accessibilityLabel .~ self.confirmNewPasswordLabel.text
|> UITextField.lens.returnKeyType .~ .done
|> \.attributedPlaceholder %~ { _ in
settingsAttributedPlaceholder(Strings.login_placeholder_password())
}
_ = self.currentPasswordLabel
|> settingsTitleLabelStyle
|> UILabel.lens.text %~ { _ in Strings.Current_password() }
_ = self.currentPasswordTextField
|> settingsPasswordFormFieldAutoFillStyle
|> \.accessibilityLabel .~ self.currentPasswordLabel.text
|> \.attributedPlaceholder %~ { _ in
settingsAttributedPlaceholder(Strings.login_placeholder_password())
}
_ = self.validationErrorMessageLabel
|> settingsDescriptionLabelStyle
_ = self.newPasswordLabel
|> settingsTitleLabelStyle
|> UILabel.lens.text %~ { _ in Strings.New_password() }
_ = self.newPasswordTextField
|> settingsNewPasswordFormFieldAutoFillStyle
|> \.accessibilityLabel .~ self.newPasswordLabel.text
|> \.attributedPlaceholder %~ { _ in
settingsAttributedPlaceholder(Strings.login_placeholder_password())
}
}
override func bindViewModel() {
super.bindViewModel()
self.validationErrorMessageLabel.rac.hidden = self.viewModel.outputs.validationErrorLabelIsHidden
self.validationErrorMessageLabel.rac.text = self.viewModel.outputs.validationErrorLabelMessage
self.viewModel.outputs.activityIndicatorShouldShow
.observeForUI()
.observeValues { [weak self] shouldShow in
if shouldShow {
self?.saveButtonView.startAnimating()
} else {
self?.saveButtonView.stopAnimating()
}
}
self.viewModel.outputs.saveButtonIsEnabled
.observeForUI()
.observeValues { [weak self] isEnabled in
self?.saveButtonView.setIsEnabled(isEnabled: isEnabled)
}
self.viewModel.outputs.currentPasswordBecomeFirstResponder
.observeForControllerAction()
.observeValues { [weak self] in
self?.currentPasswordTextField.becomeFirstResponder()
}
self.viewModel.outputs.newPasswordBecomeFirstResponder
.observeForControllerAction()
.observeValues { [weak self] in
self?.newPasswordTextField.becomeFirstResponder()
}
self.viewModel.outputs.confirmNewPasswordBecomeFirstResponder
.observeForControllerAction()
.observeValues { [weak self] in
self?.confirmNewPasswordTextField.becomeFirstResponder()
}
self.viewModel.outputs.dismissKeyboard
.observeForControllerAction()
.observeValues { [weak self] in
self?.dismissKeyboard()
}
self.viewModel.outputs.changePasswordFailure
.observeForControllerAction()
.observeValues { [weak self] errorMessage in
self?.messageBannerViewController?.showBanner(with: .error, message: errorMessage)
}
self.viewModel.outputs.changePasswordSuccess
.observeForControllerAction()
.observeValues { [weak self] in
self?.logoutAndDismiss()
}
self.viewModel.outputs.accessibilityFocusValidationErrorLabel
.observeForUI()
.observeValues { [weak self] _ in
UIAccessibility.post(notification: .layoutChanged, argument: self?.validationErrorMessageLabel)
}
Keyboard.change
.observeForUI()
.observeValues { [weak self] change in
self?.scrollView.handleKeyboardVisibilityDidChange(change)
}
}
// MARK: - Functions
private func logoutAndDismiss() {
AppEnvironment.logout()
PushNotificationDialog.resetAllContexts()
NotificationCenter.default.post(.init(name: .ksr_sessionEnded))
self.dismiss(animated: true, completion: nil)
}
private func dismissKeyboard() {
[self.newPasswordTextField, self.confirmNewPasswordTextField, self.currentPasswordTextField]
.forEach { $0?.resignFirstResponder() }
}
// MARK: - Actions
@IBAction func currentPasswordTextDidChange(_ sender: UITextField) {
guard let text = sender.text else {
return
}
self.viewModel.inputs.currentPasswordFieldTextChanged(text: text)
}
@IBAction func currentPasswordDidEndEditing(_ sender: UITextField) {
guard let currentPassword = sender.text else {
return
}
self.viewModel.inputs.currentPasswordFieldTextChanged(text: currentPassword)
}
@IBAction func currentPasswordDidReturn(_ sender: UITextField) {
guard let currentPassword = sender.text else {
return
}
self.viewModel.inputs.currentPasswordFieldDidReturn(currentPassword: currentPassword)
}
@IBAction func newPasswordTextDidChange(_ sender: UITextField) {
guard let text = sender.text else {
return
}
self.viewModel.inputs.newPasswordFieldTextChanged(text: text)
}
@IBAction func newPasswordDidEndEditing(_ sender: UITextField) {
guard let newPassword = sender.text else {
return
}
self.viewModel.inputs.newPasswordFieldTextChanged(text: newPassword)
}
@IBAction func newPasswordDidReturn(_ sender: UITextField) {
guard let newPassword = sender.text else {
return
}
self.viewModel.inputs.newPasswordFieldDidReturn(newPassword: newPassword)
}
@IBAction func confirmNewPasswordTextDidChange(_ sender: UITextField) {
guard let text = sender.text else {
return
}
self.viewModel.inputs.newPasswordConfirmationFieldTextChanged(text: text)
}
@IBAction func confirmNewPasswordDidEndEditing(_ sender: UITextField) {
guard let newPasswordConfirmed = sender.text else {
return
}
self.viewModel.inputs
.newPasswordConfirmationFieldTextChanged(text: newPasswordConfirmed)
}
@IBAction func confirmNewPasswordDidReturn(_ sender: UITextField) {
guard let newPasswordConfirmed = sender.text else {
return
}
self.viewModel.inputs
.newPasswordConfirmationFieldDidReturn(newPasswordConfirmed: newPasswordConfirmed)
}
@IBAction func saveButtonTapped(_: Any) {
self.viewModel.inputs.saveButtonTapped()
}
}
| apache-2.0 | bf485cf6cdc8eafd01959d83c8255e56 | 31.130909 | 103 | 0.725102 | 5.284689 | false | false | false | false |
daisysomus/swift-algorithm-club | Union-Find/UnionFind.playground/Sources/UnionFindQuickUnion.swift | 1 | 1355 | import Foundation
/// Quick-Union algorithm may take ~MN steps
/// to process M union commands on N objects
public struct UnionFindQuickUnion<T: Hashable> {
private var index = [T: Int]()
private var parent = [Int]()
private var size = [Int]()
public init() {}
public mutating func addSetWith(_ element: T) {
index[element] = parent.count
parent.append(parent.count)
size.append(1)
}
private mutating func setByIndex(_ index: Int) -> Int {
if parent[index] == index {
return index
} else {
parent[index] = setByIndex(parent[index])
return parent[index]
}
}
public mutating func setOf(_ element: T) -> Int? {
if let indexOfElement = index[element] {
return setByIndex(indexOfElement)
} else {
return nil
}
}
public mutating func unionSetsContaining(_ firstElement: T, and secondElement: T) {
if let firstSet = setOf(firstElement), let secondSet = setOf(secondElement) {
if firstSet != secondSet {
parent[firstSet] = secondSet
size[secondSet] += size[firstSet]
}
}
}
public mutating func inSameSet(_ firstElement: T, and secondElement: T) -> Bool {
if let firstSet = setOf(firstElement), let secondSet = setOf(secondElement) {
return firstSet == secondSet
} else {
return false
}
}
}
| mit | d8b67ea135bc5c69f3b34253db7ec381 | 25.568627 | 85 | 0.6369 | 4.208075 | false | false | false | false |
drinkapoint/DrinkPoint-iOS | DrinkPoint/Pods/FacebookShare/Sources/Share/Dialogs/MessageDialog/MessageDialog.swift | 1 | 3846 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import FBSDKShareKit
/// A dialog for sharing content through Messenger.
public final class MessageDialog<Content: ContentProtocol> {
private let sdkSharer: FBSDKMessageDialog
private let sdkShareDelegate: SDKSharingDelegateBridge<Content>
/**
Create a `MessageDialog` with a given content.
- parameter content: The content to share.
*/
public init(content: Content) {
sdkSharer = FBSDKMessageDialog()
sdkShareDelegate = SDKSharingDelegateBridge<Content>()
sdkShareDelegate.setupAsDelegateFor(sdkSharer)
sdkSharer.shareContent = ContentBridger.bridgeToObjC(content)
}
}
extension MessageDialog: ContentSharingProtocol {
/// The content that is being shared.
public var content: Content {
get {
guard let swiftContent: Content = ContentBridger.bridgeToSwift(sdkSharer.shareContent) else {
fatalError("Content of our private share dialog has changed type. Something horrible has happened.")
}
return swiftContent
}
}
/// The completion handler to be invoked upon the share performing.
public var completion: (ContentSharerResult<Content> -> Void)? {
get {
return sdkShareDelegate.completion
}
set {
sdkShareDelegate.completion = newValue
}
}
/// Whether or not this sharer fails on invalid data.
public var failsOnInvalidData: Bool {
get {
return sdkSharer.shouldFailOnDataError
}
set {
sdkSharer.shouldFailOnDataError = newValue
}
}
/**
Validates the content on the receiver.
- throws: If The content could not be validated.
*/
public func validate() throws {
try sdkSharer.validate()
}
}
extension MessageDialog: ContentSharingDialogProtocol {
/**
Shows the dialog.
- throws: If the dialog cannot be presented.
*/
public func show() throws {
var error: ErrorType?
let completionHandler = sdkShareDelegate.completion
sdkShareDelegate.completion = {
if case .Failed(let resultError) = $0 {
error = resultError
}
}
sdkSharer.show()
sdkShareDelegate.completion = completionHandler
if let error = error {
throw error
}
}
}
extension MessageDialog {
/**
Convenience method to show a Message Share Dialog with content and a completion handler.
- parameter content: The content to share.
- parameter completion: The completion handler to invoke.
- returns: The dialog that has been presented.
- throws: If the dialog fails to validate.
*/
public static func show(content: Content, completion: (ContentSharerResult<Content> -> Void)? = nil) throws -> Self {
let dialog = self.init(content: content)
dialog.completion = completion
try dialog.show()
return dialog
}
}
| mit | 040fe3790841efc20f08c70cfc359ba5 | 30.52459 | 119 | 0.719969 | 4.724816 | false | false | false | false |
zdrzdr/DIYPresentTransitionAnimation-Swift- | iOS 8自定义动画转场上手指南/ViewController.swift | 1 | 2776 | //
// ViewController.swift
// iOS 8自定义动画转场上手指南
//
// Created by 张德荣 on 15/8/2.
// Copyright (c) 2015年 JsonZhang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lblMessage:UILabel!
@IBAction func showThirdViewController(sender: AnyObject)
{
self.performSegueWithIdentifier("idSecondSegue", sender: self)
}
@IBAction func returnFromSegueActions(sender:UIStoryboardSegue){
if sender.identifier == "idFirstSegueUnwind" {
let originalColor = self.view.backgroundColor
self.view.backgroundColor = UIColor.redColor()
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.view.backgroundColor = originalColor
})
}
else
{
self.lblMessage.text = "Welcome back!"
}
}
override func viewDidLoad() {
super.viewDidLoad()
var swipeGesuteRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "showSecondViewController")
swipeGesuteRecognizer.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(swipeGesuteRecognizer)
}
func showSecondViewController() {
self.performSegueWithIdentifier("idFirstSegue", sender: self)
}
override func segueForUnwindingToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String?) -> UIStoryboardSegue {
if let id = identifier {
if id == "idFirstSegueUnwind" {
let unwindSegue = FirstCustomSegueUnwind(identifier: id, source: fromViewController, destination: toViewController, performHandler: { () -> Void in
})
return unwindSegue
}
else if id == "idSecondSegueUnwind" {
let unwindSegue = SecondCustomSegueUnwind(identifier: id, source: fromViewController, destination: toViewController, performHandler: { () -> Void in
})
return unwindSegue
}
}
return super.segueForUnwindingToViewController(toViewController, fromViewController: fromViewController, identifier: identifier)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "idFirstSegue" {
let secondViewController = segue.destinationViewController as! SecondViewController
secondViewController.message = "Hello from the 1st View Controller"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 101cc01075914e8503c5beba44f37c5f | 35.613333 | 169 | 0.664967 | 5.492 | false | false | false | false |
ibm-wearables-sdk-for-mobile/ios | RecordApp/RecordApp/ConnectViewController.swift | 2 | 3951 | /*
* © Copyright 2015 IBM Corp.
*
* Licensed under the Mobile Edge iOS Framework License (the "License");
* you may not use this file except in compliance with the License. You may find
* a copy of the license in the license.txt file in this package.
*
* 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 IBMMobileEdge
class ConnectViewController: UIViewController, ConnectionStatusDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var statusLable: UILabel!
@IBOutlet weak var picker: UIPickerView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var connectButton: UIButton!
let controller = AppDelegate.controller
var pickerData = [DeviceConnector]()
var selectedDeviceIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
controller.delegate = self
spinner.stopAnimating()
statusLable.hidden = true
setUpConnectors()
}
//set up the list of avalible connectors
func setUpConnectors(){
for connector in AppDelegate.applicationConnectors{
pickerData.append(connector)
}
}
@IBAction func onConnectButtonClicked(sender: AnyObject) {
if (pickerData.count > 0){
performConnection()
}
else{
Utils.showMsgDialog(self, withMessage: "You have not defined any connectors. Please refer to the wiki page (at GitHub.com) for detailed instructions");
}
}
func performConnection(){
connectButton.enabled = false
spinner.startAnimating()
statusLable.hidden = false
statusLable.text = "Connecting to \(pickerData[selectedDeviceIndex].deviceName)..."
//connect to the selected device
controller.connect(pickerData[selectedDeviceIndex])
}
func connectionStatusChanged(deviceName: String, withStatus status: ConnectionStatus) {
spinner.stopAnimating()
statusLable.hidden = true
switch status{
case .Connected:
self.performSegueWithIdentifier("moveToMain", sender: self)
case .Disconnected:
Utils.showMsgDialog(self, withMessage:"Device Dissconected")
connectButton.enabled = true
case .BluetoothUnavailable:
Utils.showMsgDialog(self, withMessage:"Bluetooth Unavailable")
connectButton.enabled = true
case .DeviceUnavailable:
Utils.showMsgDialog(self, withMessage:"Device Unavailable")
connectButton.enabled = true
}
}
// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row].deviceName
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedDeviceIndex = row
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let attributedString = NSAttributedString(string: pickerData[row].deviceName, attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()])
return attributedString
}
}
| epl-1.0 | 367177e9204df144d8dd12457ef7c034 | 33.051724 | 163 | 0.665316 | 5.539972 | false | false | false | false |
SteveRohrlack/CitySimCore | src/Actors/ElectricityActor.swift | 1 | 5588 | //
// ElectricityActor.swift
// CitySimCore
//
// Created by Steve Rohrlack on 30.05.16.
// Copyright © 2016 Steve Rohrlack. All rights reserved.
//
import Foundation
import GameplayKit
/**
The ElectricityActor
*/
public struct ElectricityActor: Acting, EventSubscribing {
typealias StageType = City
/// actor stage
/// simulation's main data container
weak var stage: ActorStageable?
/**
initializer
- parameter stage: City object work work with
*/
init(stage: City) {
self.stage = stage
stage.map.subscribe(subscriber: self, to: .AddTile)
stage.map.subscribe(subscriber: self, to: .RemoveTile)
}
/**
Eventhandler for CityMapEvents
- parameter event: the event type
- parameter payload: the event data
*/
public func recieveEvent(event event: EventNaming, payload: Any) throws {
guard let stage = stage as? StageType, let event = event as? CityMapEvent else {
return
}
/// a tile may be a consumer and a producer at the same time
/// consumer is added or removed
if let consumer = payload as? RessourceConsuming {
update(consumer: consumer, event: event)
}
/// producer is added or removed
if let producer = payload as? RessourceProducing {
update(producer: producer, event: event)
}
/// update consumers if RessourceCarrier is added or removed
if let _ = payload as? RessourceCarrying {
stage.ressources.electricityNeedsRecalculation = true
}
}
/**
the ElectricityActor updates electricity consumers state
- parameter tick: the current simulation tick
*/
func act(tick tick: Int) {
guard let stage = stage as? StageType where stage.ressources.electricityNeedsRecalculation else {
return
}
updateConsumers()
}
private func update(consumer consumer: RessourceConsuming, event: CityMapEvent) {
guard let stage = stage as? StageType,
let ressource = consumer.ressources.get(content: .Electricity(nil)),
let value = ressource.value() else {
return
}
if case .AddTile = event {
/// if the new demand is bigger than the current supply,
/// recalculation is needed
/// otherwise, all consumers will be supplied with
/// electricity, after adding this new one
stage.ressources.electricityDemand += value
guard stage.ressources.electricityDemand > stage.ressources.electricitySupply else {
return
}
stage.ressources.electricityNeedsRecalculation = true
/// newly added tile needs to get status .NotPowered if electricity demand is higher than supply
var updatedConsumer = consumer
updatedConsumer.conditions.add(content: .NotPowered)
guard let tile = updatedConsumer as? TileLayer.ValueType else {
return
}
do {
try stage.map.tileLayer.add(tile: tile)
} catch {
return
}
}
if case .RemoveTile = event {
/// if the previous demand is already bigger than the supply,
/// recalculation is needed
/// otherwise, all consumers have already been supplied with
/// electricity, and will still be if a consumer is removed
if stage.ressources.electricityDemand > stage.ressources.electricitySupply {
stage.ressources.electricityNeedsRecalculation = true
}
stage.ressources.electricityDemand -= value
}
}
private func update(producer producer: RessourceProducing, event: CityMapEvent) {
guard let stage = stage as? StageType,
case .Electricity(let ressourceValue) = producer.ressource,
let value = ressourceValue else {
return
}
if case .AddTile = event {
/// if the previous supply is smaller than the current demand,
/// recalculation is needed
/// otherwise, all consumers are already supplied with electricity
/// and will still be after adding a new producer
if stage.ressources.electricitySupply < stage.ressources.electricityDemand {
stage.ressources.electricityNeedsRecalculation = true
}
stage.ressources.electricitySupply += value
}
if case .RemoveTile = event {
/// if the new supply is smaller than the current demand,
/// recalculation is needed
/// otherwise, all consumers are still being supplied with
/// electricity, and will still be if the producer is removed
stage.ressources.electricitySupply -= value
if stage.ressources.electricitySupply < stage.ressources.electricityDemand {
stage.ressources.electricityNeedsRecalculation = true
}
}
}
/**
updates electricity consumers based on current electricity supply and demand
*/
private func updateConsumers() {
/*defer {
/// reset recalculation flag
stage?.ressources.electricityNeedsRecalculation = false
}*/
}
}
| mit | aa709fce05fc97029cbefb555279a40b | 33.276074 | 108 | 0.593521 | 5.63774 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/cards/TKUIHomeCard+Configuration.swift | 1 | 2905 | //
// TKUIHomeCard+Configuration.swift
// TripKit
//
// Created by Kuan Lun Huang on 2/12/19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
import RxSwift
import RxCocoa
import TripKit
public extension TKUIHomeCard {
enum SelectionMode {
/// Home selection will always be passed to the home map manager, for that to handle it.
case selectOnMap
/// Execute the provided callback on tap; the component will only be set if selected via
/// the card itself and not something on the map. The closure returns a boolean indicating
/// whether other annotations should be hidden when the selection is made.
case callback((TKAutocompletionSelection, TKUIHomeComponentViewModel?) -> Bool)
/// Default handling shows timetable for stops and routing results for others
case `default`
}
enum VoiceOverMode {
case searchBar
case routeButton
}
struct Configuration {
// We don't want this to be initialised.
private init() {}
static let empty = Configuration()
/// Set this to indicate if permission to access location services should be
/// requested when the card is loaded. When setting to `true`, the map
/// is zoomed to a user's current location and begins displaying nearby
/// stops and locations.
///
/// The default value is `true`
public var requestLocationServicesOnLoad: Bool = true
/// Set this to place actionable items on the map view. Items are arranged
/// vertically.
public var topMapToolbarItems: [UIView]?
/// Set this to add a list of autocompletion providers to use.
///
/// The default providers, if none is provided, are Apple and SkedGo geocoders.
public var autocompletionDataProviders: [TKAutocompleting]?
/// Set this to specify what view model classes can be used by the home card
/// to build its content
public var componentViewModelClasses: [TKUIHomeComponentViewModel.Type] = []
/// Set this to `true` if your components aren't customizable and they should always be ordered
/// as defined in ``componentViewModelClasses``.
public var ignoreComponentCustomization: Bool = false
/// Set this to customise what should happen if map content or an autocompletion
/// result is tapped (or whenever one of your component view models calls `.handleSelection`)
public var selectionMode: SelectionMode = .default
/// Set where the initial VoiceOver focus should be. Defaults to `.searchBar`
public var voiceOverStartMode: TKUIHomeCard.VoiceOverMode = .searchBar
/// Determines if a `TKUIRoutingQueryInputCard` starts with a focus on the destination field,
/// if activated through the direction button in the home card.
public var directionButtonStartsQueryInputInDestinationMode: Bool = true
}
}
| apache-2.0 | 81d9095ecd214de20a558a2c25e1f5ee | 34.851852 | 99 | 0.711088 | 4.981132 | false | false | false | false |
apple/swift-argument-parser | Tools/generate-manual/DSL/SinglePageDescription.swift | 1 | 1397 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import ArgumentParserToolInfo
struct SinglePageDescription: MDocComponent {
var command: CommandInfoV0
var body: MDocComponent {
Section(title: "description") {
core
}
}
@MDocBuilder
var core: MDocComponent {
if let discussion = command.discussion {
discussion
}
List {
for argument in command.arguments ?? [] {
MDocMacro.ListItem(title: argument.manualPageDescription)
if let abstract = argument.abstract {
abstract
}
if argument.abstract != nil, argument.discussion != nil {
MDocMacro.ParagraphBreak()
}
if let discussion = argument.discussion {
discussion
}
}
for subcommand in command.subcommands ?? [] {
MDocMacro.ListItem(title: MDocMacro.Emphasis(arguments: [subcommand.commandName]))
SinglePageDescription(command: subcommand).core
}
}
}
}
| apache-2.0 | bf87faa8f4632a296cc33a1a5c227bdd | 25.358491 | 90 | 0.586972 | 5.08 | false | false | false | false |
superman-coder/pakr | pakr/pakr/UserInterface/ListParking/SearchController.swift | 1 | 8440 | //
// Created by Huynh Quang Thao on 4/5/16.
// Copyright (c) 2016 Pakr. All rights reserved.
//
import Foundation
import UIKit
import MBProgressHUD
class SearchController: UIViewController {
@IBOutlet weak var emptyView: UIView!
// Inside status view (empty view)
@IBOutlet weak var statusImageView: UIImageView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var parkingTableView: UITableView!
@IBOutlet weak var tableBottomToSuperViewConstraint: NSLayoutConstraint!
var parkSearchResult: [Topic]! = []
var searchTriggerTimer:NSTimer?
internal var addressService = WebServiceFactory.getAddressService()
let searchBar = UISearchBar()
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
initSearchBar()
showWelcomeInStatusView()
}
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SearchController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SearchController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func initTableView() {
parkingTableView.registerNib(UINib(nibName: "ParkingResultCell", bundle: nil), forCellReuseIdentifier: "ParkingResultCell")
parkingTableView.rowHeight = UITableViewAutomaticDimension
parkingTableView.estimatedRowHeight = 10
parkingTableView.delegate = self
parkingTableView.dataSource = self
}
func initSearchBar() {
searchBar.delegate = self
self.navigationItem.titleView = searchBar
searchBar.tintColor = UIColor.primaryColor()
searchBar.autocorrectionType = .No
searchBar.placeholder = "Type an address..."
}
func reloadData() {
MBProgressHUD.hideHUDForView(self.view, animated: true)
searchBar.resignFirstResponder()
parkingTableView.reloadData()
}
func keyboardWillShow(notification:NSNotification) {
let userInfo = notification.userInfo! as NSDictionary
let keyboardSizeValue = userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue
let keyboardSize = keyboardSizeValue.CGRectValue().size
let animDurationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
let animCurveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
self.view.layoutIfNeeded()
UIView.animateWithDuration(animDurationValue.doubleValue,
delay: 0,
options: UIViewAnimationOptions(rawValue: UInt(animCurveValue.integerValue << 16)),
animations: {
self.tableBottomToSuperViewConstraint.constant = keyboardSize.height
self.view.layoutIfNeeded()
},
completion: nil
)
}
func keyboardWillHide(notification:NSNotification) {
let userInfo = notification.userInfo! as NSDictionary
let animDurationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
let animCurveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
self.view.layoutIfNeeded()
UIView.animateWithDuration(animDurationValue.doubleValue,
delay: 0,
options: UIViewAnimationOptions(rawValue: UInt(animCurveValue.integerValue << 16)),
animations: {
self.tableBottomToSuperViewConstraint.constant = 0
self.view.layoutIfNeeded()
},
completion: nil
)
}
@IBAction func onTapView(sender: AnyObject) {
self.view.endEditing(false)
}
}
extension SearchController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ParkingResultCell") as! ParkingResultCell
cell.configWithTopic(parkSearchResult[indexPath.row])
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parkSearchResult.count
}
func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let footer = view as! UITableViewHeaderFooterView
footer.backgroundView?.backgroundColor = UIColor.clearColor()
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 8
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let topic = self.parkSearchResult[indexPath.row];
let detailVc = DetailParkingController(nibName: "DetailParkingController", bundle: nil)
detailVc.topic = topic
self.navigationController?.pushViewController(detailVc, animated: true)
}
}
extension SearchController: UISearchBarDelegate {
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
return true
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.characters.count == 0 {
handleSearchResult(nil, error: nil)
return
}
searchTriggerTimer?.invalidate()
searchTriggerTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(SearchController.requestSearchPlaces(_:)), userInfo: searchText, repeats: false)
}
func requestSearchPlaces(sender:NSTimer) {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
let searchText = sender.userInfo as! String
addressService.getNearByParkingByAddressName(searchText, radius: 800, success: { topics in
self.handleSearchResult(topics, error: nil)
}) { error in
self.handleSearchResult(nil, error: error)
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar){
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
self.searchBar(searchBar, textDidChange: "")
searchBar.setShowsCancelButton(false, animated: true)
}
func handleSearchResult(topics:[Topic]?, error:NSError?) {
if let error = error {
showStatusErrorInStatusView(error)
}
self.parkSearchResult.removeAll()
if let topics = topics {
self.parkSearchResult.appendContentsOf(topics)
}
if self.parkSearchResult.count > 0 {
parkingTableView.hidden = false
emptyView.hidden = true
} else {
showNoDataStatusInStatusView()
parkingTableView.hidden = true
emptyView.hidden = false
}
reloadData()
}
func showStatusErrorInStatusView(error:NSError) {
statusImageView.image = UIImage(named: "angry")
statusLabel.text = "Oops, something went wrong!"
}
func showWelcomeInStatusView() {
statusImageView.image = UIImage(named: "troll")
statusLabel.text = "Let's search for parking lots"
}
func showNoDataStatusInStatusView() {
statusImageView.image = UIImage(named: "troll")
statusLabel.text = "No data there"
}
}
| apache-2.0 | 3f241b007c3c3734704eff12dc114fa0 | 37.894009 | 185 | 0.656991 | 5.977337 | false | false | false | false |
pantuspavel/PPAssetsActionController | PPAssetsActionController/Classes/PPAssetsActionController.swift | 1 | 16713 | import UIKit
import MobileCoreServices
/**
Assets Picker Delegate methods.
*/
public protocol PPAssetsActionControllerDelegate: class {
/**
Called when a user dismisses a picker by tapping cancel or background.
Implementation is optional.
- Parameter picker: Picker Controller that was dismissed.
*/
func assetsPickerDidCancel(_ picker: PPAssetsActionController)
/**
Called when a user takes an image.
Assets Picker is not dismissed automatically when the delegate method is called.
Implementation is optional.
- Parameters:
- picker: Current picker controller.
- image: Picture that was taken with system Image Picker Controller.
*/
func assetsPicker(_ picker: PPAssetsActionController, didSnapImage image: UIImage)
/**
Called when a user takes a video.
Assets Picker is not dismissed automatically when the delegate method is called.
Implementation is optional.
- Parameters:
- picker: Current picker controller.
- videoURL: URL of video that was taken with system Image Picker Controller.
*/
func assetsPicker(_ picker: PPAssetsActionController, didSnapVideo videoURL: URL)
/**
Called when a user selects previews and presses send button.
Assets Picker is not dismissed automatically when the delegate method is called.
Implementation is optional.
- Parameters:
- picker: Current picker controller.
- assets: Assets that were selected with Preview Picker.
*/
func assetsPicker(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider])
}
/**
Default implementation for delegate methods to make them optional.
*/
extension PPAssetsActionControllerDelegate {
func assetsPickerDidCancel(_ picker: PPAssetsActionController) {}
func assetsPicker(_ picker: PPAssetsActionController, didSnapImage image: UIImage) {}
func assetsPicker(_ picker: PPAssetsActionController, didSnapVideo videoURL: URL) {}
func assetsPicker(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider]) {}
}
/**
Custom implementation of action sheet controller with assets preview.
It is highly customizable (check out PPAssetsPickerConfig) and easy to use.
*/
public class PPAssetsActionController: UIViewController {
public weak var delegate: PPAssetsActionControllerDelegate?
fileprivate var foldedPositionConstraint: NSLayoutConstraint!
fileprivate var shownPositionConstraint: NSLayoutConstraint!
fileprivate var optionsController: PPOptionsViewController!
fileprivate var assetsController: PPAssetsCollectionController!
fileprivate let assetsContainer = UIView()
fileprivate var config = PPAssetsActionConfig()
public init(with options: [PPOption], aConfig: PPAssetsActionConfig? = nil) {
super.init(nibName: nil, bundle: nil)
transitioningDelegate = self
modalPresentationStyle = .custom
if let aConfig = aConfig {
config = aConfig
}
optionsController = PPOptionsViewController(aConfig: config)
optionsController.options = options
optionsController.delegate = self
assetsController = PPAssetsCollectionController(aConfig: config)
assetsController.delegate = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = "assets-action-view"
view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleBackgroundTap(recognizer:)))
tapRecognizer.delegate = self
view.addGestureRecognizer(tapRecognizer)
assetsContainer.backgroundColor = UIColor.white
assetsContainer.translatesAutoresizingMaskIntoConstraints = false
assetsContainer.layer.cornerRadius = 5.0
view.addSubview(assetsContainer)
let bottomCornersFiller = UIView()
bottomCornersFiller.backgroundColor = assetsContainer.backgroundColor
bottomCornersFiller.translatesAutoresizingMaskIntoConstraints = false
assetsContainer.addSubview(bottomCornersFiller)
let assetsSeparator = UIView()
assetsSeparator.translatesAutoresizingMaskIntoConstraints = false
assetsSeparator.backgroundColor = optionsController.tableView!.separatorColor
bottomCornersFiller.addSubview(assetsSeparator)
assetsController.willMove(toParentViewController: self)
addChildViewController(assetsController)
assetsController.didMove(toParentViewController: self)
assetsContainer.addSubview(assetsController.collectionView!)
optionsController.willMove(toParentViewController: self)
addChildViewController(optionsController)
optionsController.didMove(toParentViewController: self)
view.addSubview(optionsController.tableView)
let views: [String : Any] = ["options": optionsController.tableView!,
"assets": assetsController.collectionView!,
"assetsContainer": assetsContainer,
"filler": bottomCornersFiller,
"assetsSeparator": assetsSeparator]
let si: CGFloat
if #available(iOS 9.0, *) {
si = 8.0
} else if #available(iOS 8.0, *) {
si = 15.0
} else {
si = 0.0
}
let metrics = ["M": config.inset,
"ACM": 6.0,
"MLW": 1 / UIScreen.main.scale,
"SI": si]
foldedPositionConstraint = NSLayoutConstraint(item: assetsContainer,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
shownPositionConstraint = NSLayoutConstraint(item: optionsController.tableView,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
view.addConstraint(NSLayoutConstraint(item: assetsContainer,
attribute: .bottom,
relatedBy: .equal,
toItem: optionsController.tableView,
attribute: .top,
multiplier: 1.0,
constant: 0.0))
shownPositionConstraint.isActive = false
view.addConstraint(foldedPositionConstraint)
assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-ACM-[assets]-ACM-|",
options: [],
metrics: metrics,
views: views))
assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-ACM-[assets]-ACM-|",
options: [],
metrics: metrics,
views: views))
assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[filler]|",
options: [],
metrics: metrics,
views: views))
assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[filler(ACM)]|",
options: [],
metrics: metrics,
views: views))
bottomCornersFiller.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-SI-[assetsSeparator]-SI-|",
options: [],
metrics: metrics,
views: views))
bottomCornersFiller.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[assetsSeparator(MLW)]|",
options: [],
metrics: metrics,
views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-M-[assetsContainer]-M-|",
options: [],
metrics: metrics,
views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-M-[options]-M-|",
options: [],
metrics: metrics,
views: views))
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if(foldedPositionConstraint.isActive) {
view.backgroundColor = config.backgroundColor
foldedPositionConstraint.isActive = false
shownPositionConstraint.isActive = true
assetsContainer.layer.cornerRadius = 5.0
view.layoutIfNeeded()
}
}
}
// MARK: PPOptionsViewControllerDelegate
extension PPAssetsActionController: PPOptionsViewControllerDelegate {
func optionsViewControllerShouldBeDismissed(_ controller: PPOptionsViewController) {
dismiss(animated: true) {
self.delegate?.assetsPickerDidCancel(self)
}
}
func optionsViewControllerDidRequestTopOption(_ controller: PPOptionsViewController) {
let selectedMedia = assetsController.selectedMedia()
if selectedMedia.count > 0 {
delegate?.assetsPicker(self, didFinishPicking: selectedMedia)
} else {
openImagePicker()
}
}
}
// MARK: PPAssetsViewControllerDelegate
extension PPAssetsActionController: PPAssetsViewControllerDelegate {
func assetsViewController(_ controller: PPAssetsCollectionController, didChange itemsCount: Int) {
optionsController.set(sendItemsCount: itemsCount)
}
func assetsViewControllerDidRequestCameraController(_ controller: PPAssetsCollectionController) {
openImagePicker()
}
}
// MARK: UIGestureRecognizerDelegate
/**
Handle tap on a background view to dismiss the picker view controller.
*/
extension PPAssetsActionController: UIGestureRecognizerDelegate {
@objc fileprivate func handleBackgroundTap(recognizer: UITapGestureRecognizer) {
if recognizer.state == .ended {
dismiss(animated: true) {
self.delegate?.assetsPickerDidCancel(self)
}
}
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard let view = touch.view else {
return false
}
if view.isDescendant(of: assetsContainer) ||
view.isDescendant(of: optionsController.view) {
return false
}
return true
}
}
// MARK: UIViewControllerTransitioningDelegate
extension PPAssetsActionController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
// MARK: UIViewControllerAnimatedTransitioning
extension PPAssetsActionController: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return config.animationDuration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let resultingColor: UIColor
let animationOptions: UIViewAnimationOptions
if shownPositionConstraint.isActive {
shownPositionConstraint.isActive = false
foldedPositionConstraint.isActive = true
resultingColor = UIColor.clear
animationOptions = .curveEaseOut
} else {
let views: [String: Any] = ["view": view]
resultingColor = config.backgroundColor
animationOptions = .curveEaseIn
containerView.addSubview(view)
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|",
options: [],
metrics: nil,
views: views))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|",
options: [],
metrics: nil,
views: views))
containerView.setNeedsLayout()
containerView.layoutIfNeeded()
foldedPositionConstraint.isActive = false
shownPositionConstraint.isActive = true
}
UIView.animate(withDuration: config.animationDuration,
delay: 0.0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 1.0,
options: animationOptions,
animations:
{
containerView.layoutIfNeeded()
self.view.backgroundColor = resultingColor
}) { result in
transitionContext.completeTransition(result)
}
}
}
// MARK: UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PPAssetsActionController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func openImagePicker() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String]
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
let videoURL = info[UIImagePickerControllerMediaURL] as? URL
dismiss(animated: true) {
if let image = image {
self.delegate?.assetsPicker(self, didSnapImage: image)
} else if let videoURL = videoURL {
self.delegate?.assetsPicker(self, didSnapVideo: videoURL)
}
}
}
}
| mit | 3366a2ec8388ed62083f89b353a30885 | 43.449468 | 177 | 0.568839 | 7.206986 | false | false | false | false |
davidvuong/ddfa-app | ios/Pods/GooglePlacePicker/Example/GooglePlacePickerDemos/ViewControllers/PlaceDetail/PlaceDetailViewController.swift | 4 | 6550 | /*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import GoogleMaps
import GooglePlaces
/// A view controller which displays details about a specified |GMSPlace|.
class PlaceDetailViewController: BaseContainerViewController {
private let place: GMSPlace
@IBOutlet private weak var photoView: UIImageView!
@IBOutlet private weak var mapView: GMSMapView!
@IBOutlet var tableBackgroundView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var statusBarShadow: ShadowLineView!
@IBOutlet weak var navigationBar: UIView!
@IBOutlet weak var headerHeightExtension: UIView!
@IBOutlet weak var headerHeightExtensionConstraint: NSLayoutConstraint!
@IBOutlet weak var photoWidthConstraint: NSLayoutConstraint!
private lazy var placesClient = { GMSPlacesClient.shared() } ()
private static let photoSize = CGSize(width: 450, height: 300)
private var tableDataSource: PlaceDetailTableViewDataSource!
init(place: GMSPlace) {
self.place = place
super.init(nibName: String(describing: type(of: self)), bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Configure the table
tableDataSource =
PlaceDetailTableViewDataSource(place: place,
extensionConstraint: headerHeightExtensionConstraint,
tableView: tableView)
tableView.backgroundView = tableBackgroundView
tableView.dataSource = tableDataSource
tableView.delegate = tableDataSource
// Configure the UI elements
lookupPhoto()
configureMap()
configureBars()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateNavigationBarState(actualTraitCollection)
updateStatusBarState(actualTraitCollection)
}
override func willTransition(to newCollection: UITraitCollection,
with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
updateNavigationBarState(newCollection)
updateStatusBarState(newCollection)
}
override func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
updateStatusBarState(actualTraitCollection)
}
private func lookupPhoto() {
// Lookup the photos associated with this place.
placesClient.lookUpPhotos(forPlaceID: place.placeID) { (metadata, error) in
// Handle the result if it was successful.
if let metadata = metadata {
// Check to see if any photos were found.
if !metadata.results.isEmpty {
// If there were load the first one.
self.loadPhoto(metadata.results[0])
} else {
NSLog("No photos were found")
}
} else if let error = error {
NSLog("An error occured while looking up the photos: \(error)")
} else {
fatalError("An unexpected error occured")
}
}
}
private func loadPhoto(_ photo: GMSPlacePhotoMetadata) {
// Load the specified photo.
placesClient.loadPlacePhoto(photo, constrainedTo: PlaceDetailViewController.photoSize,
scale: view.window?.screen.scale ?? 1) { (image, error) in
// Handle the result if it was successful.
if let image = image {
self.photoView.image = image
self.photoWidthConstraint.isActive = false
} else if let error = error {
NSLog("An error occured while loading the first photo: \(error)")
} else {
fatalError("An unexpected error occured")
}
}
}
private func configureMap() {
// Place a marker on the map and center it on the desired coordinates.
let marker = GMSMarker(position: place.coordinate)
marker.map = mapView
mapView.camera = GMSCameraPosition(target: place.coordinate, zoom: 15, bearing: 0,
viewingAngle: 0)
mapView.isUserInteractionEnabled = false
}
private func configureBars() {
// Configure the drop-shadow we display under the status bar.
statusBarShadow.enableShadow = true
statusBarShadow.shadowOpacity = 1
statusBarShadow.shadowSize = 80
// Add a constraint to the top of the navigation bar so that it respects the top layout guide.
NSLayoutConstraint(item: navigationBar, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom, multiplier: 1,
constant: 0).isActive = true
// Set the color of the hight extension view.
headerHeightExtension.backgroundColor = Colors.blue2
}
private func updateNavigationBarState(_ traitCollection: UITraitCollection) {
// Hide the navigation bar if we have enough space to be split-screen.
let isNavigationBarHidden = traitCollection.horizontalSizeClass == .regular
navigationBar.isHidden = isNavigationBarHidden
tableDataSource.offsetNavigationTitle = !isNavigationBarHidden
tableDataSource.updateNavigationTextOffset()
}
private func updateStatusBarState(_ traitCollection: UITraitCollection) {
// Hide the shadow if we are not right against the status bar.
let hasMargin = insetViewController?.hasMargin ?? false
statusBarShadow.isHidden = hasMargin
// Transition to a compact navigation bar layout if the status bar is hidden.
tableDataSource.compactHeader = traitCollection.verticalSizeClass == .compact
}
@IBAction func backButtonTapped() {
splitPaneViewController?.popViewController()
}
}
| mit | 039bedbeb0386c14a733c7436bbf75e5 | 38.457831 | 101 | 0.678321 | 5.382087 | false | false | false | false |
Ricky-Choi/AppcidCocoaUtil | AppcidCocoaUtil/StringExtension.swift | 1 | 1236 | //
// StringExtension.swift
//
//
// Created by Jaeyoung Choi on 2015. 10. 20..
// Copyright © 2015년 Appcid. All rights reserved.
//
import Foundation
extension String {
public func trim() -> String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
public func length() -> Int {
var count = 0
enumerateSubstrings(in: startIndex ..< endIndex, options: .byComposedCharacterSequences) { _ in
count = count + 1
}
return count
}
public func filter(predicate: (Character) -> Bool) -> String {
var res = String()
for c in self.characters {
if (predicate(c)) {
res.append(c)
}
}
return res
}
public func trimInside() -> String {
let trimString = self.trim()
return trimString.filter { return $0 != Character(" ") }
}
public func uppercasedFirstCharacterOnly() -> String {
guard length() > 1 else {
return uppercased()
}
let secondIndex = index(after: startIndex)
return substring(to: secondIndex).uppercased() + substring(from: secondIndex)
}
}
| mit | 19a37637551a834472ca9671834b91fd | 23.66 | 103 | 0.549067 | 4.77907 | false | false | false | false |
Isuru-Nanayakkara/Broadband-Usage-Meter-OSX | Broadband Usage Meter/Broadband Usage Meter/SLTAPI.swift | 1 | 4167 | //
// SLTAPI.swift
// SLT Usage Meter
//
// Created by Isuru Nanayakkara on 10/23/15.
// Copyright © 2015 BitInvent. All rights reserved.
//
import Foundation
class SLTAPI {
private let session = NSURLSession.sharedSession()
private let baseURL = "https://www.internetvas.slt.lk/SLTVasPortal-war/"
func login(userID userID: String, password: String, completion: (error: NSError?) -> ()) {
let url = NSURL(string: baseURL + "login/j_security_check/j_security_check")!
let params = ["j_username": userID, "j_password": password]
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.encodeParameters(params)
session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
print("Something's fucky! - \(httpResponse)")
completion(error: error)
} else {
let html = String(data: data!, encoding: NSUTF8StringEncoding)!
if html.containsString("Invalid Credentials") {
let errorDescription = "Invalid Credentails"
let recoverySuggestion = "Please enter the correct portal Username and Password"
let loginError = NSError(domain: "SLT-Usage-Error", code: 0, userInfo: [NSLocalizedDescriptionKey: errorDescription, NSLocalizedRecoverySuggestionErrorKey: recoverySuggestion])
completion(error: loginError)
} else {
completion(error: nil)
}
}
}
}).resume()
}
func fetchUsage(completion: (usage: Usage?, error: NSError?) -> ()) {
let url = NSURL(string: baseURL + "application/GetProfile")!
let request = NSURLRequest(URL: url)
session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let error = error {
completion(usage: nil, error: error)
} else {
if let usage = Usage(jsonData: data!) {
completion(usage: usage, error: nil)
} else {
let errorDescription = "Error Fetching Data"
let recoverySuggestion = ""
let fetchDataError = NSError(domain: "SLT-Usage-Error", code: 1, userInfo: [NSLocalizedDescriptionKey: errorDescription, NSLocalizedRecoverySuggestionErrorKey: recoverySuggestion])
completion(usage: nil, error: fetchDataError)
}
}
}).resume()
}
}
// see: http://stackoverflow.com/a/31031859/1077789
extension NSMutableURLRequest {
/// Percent escape
///
/// Percent escape in conformance with W3C HTML spec:
///
/// See http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
///
/// - parameter string: The string to be percent escaped.
/// - returns: Returns percent-escaped string.
private func percentEscapeString(string: String) -> String {
let characterSet = NSCharacterSet.alphanumericCharacterSet().mutableCopy() as! NSMutableCharacterSet
characterSet.addCharactersInString("-._* ")
return string
.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!
.stringByReplacingOccurrencesOfString(" ", withString: "+", options: [], range: nil)
}
/// Encode the parameters for `application/x-www-form-urlencoded` request
///
/// - parameter parameters: A dictionary of string values to be encoded in POST request
func encodeParameters(parameters: [String : String]) {
HTTPMethod = "POST"
let parameterArray = parameters.map { (key, value) -> String in
return "\(key)=\(self.percentEscapeString(value))"
}
HTTPBody = parameterArray.joinWithSeparator("&").dataUsingEncoding(NSUTF8StringEncoding)
}
} | mit | e01c36ee5910a6cac298dd34a2f23627 | 42.40625 | 200 | 0.604657 | 5.155941 | false | false | false | false |
zzBelieve/Hello_Swift | Hello Swift/Hello Swift/ZZCargruop.swift | 1 | 1139 | //
// ZZCargruop.swift
// Hello Swift
//
// Created by ZZBelieve on 15/8/24.
// Copyright (c) 2015年 galaxy-link. All rights reserved.
//
import UIKit
class ZZCargruop: NSObject {
var title: String = ""
var cars: NSArray = NSArray()
init(dictionary: NSDictionary){
super.init()
self .setValue(dictionary["title"], forKey: "title")
self.cars = ZZCar.carWithArray(dictionary["cars"] as! NSArray)
}
class func groupWithDic(dictionary: NSDictionary)->ZZCargruop{
return ZZCargruop(dictionary: dictionary)
}
class func carsGroup()->NSMutableArray{
let path: NSString = NSBundle.mainBundle().pathForResource("cars_total.plist", ofType: nil)!
let array: NSArray = NSArray (contentsOfFile: path as String)!
var tempArray: NSMutableArray = NSMutableArray()
for object in array{
tempArray.addObject(ZZCargruop.groupWithDic(object as!NSDictionary))
}
return tempArray
}
}
| mit | 6ce3eb099742a153e85e5fbec6492ac8 | 20.055556 | 100 | 0.574318 | 4.659836 | false | false | false | false |
lyimin/EyepetizerApp | EyepetizerApp/EyepetizerApp/Views/CollectionView/EYECollectionView.swift | 1 | 1136 | //
// EYECollectionView.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/21.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
class EYECollectionLayout: UICollectionViewFlowLayout {
override init () {
super.init()
let itemHeight = 200*UIConstant.SCREEN_WIDTH/UIConstant.IPHONE5_WIDTH
itemSize = CGSize(width: UIConstant.SCREEN_WIDTH, height: itemHeight)
sectionInset = UIEdgeInsetsZero
minimumInteritemSpacing = 0
minimumLineSpacing = 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class EYECollectionView: UICollectionView {
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
backgroundColor = UIColor.whiteColor()
// 注册cell
registerClass(EYEChoiceCell.self, forCellWithReuseIdentifier: EYEChoiceCell.reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 3d3c5a7cd2329fbc04e5cdd8ecb02c41 | 27.794872 | 100 | 0.695459 | 4.861472 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigo/Settings/Help/Help06ViewController.swift | 1 | 2977 | //
// Help06ViewController.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 31/12/2020.
// Copyright © 2020 Piwigo.org. All rights reserved.
//
import UIKit
import piwigoKit
class Help06ViewController: UIViewController {
@IBOutlet weak var legend: UILabel!
@IBOutlet weak var imageView: UIImageView!
private let helpID: UInt16 = 0b00000000_00100000
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Initialise mutable attributed string
let legendAttributedString = NSMutableAttributedString(string: "")
// Title
let titleString = "\(NSLocalizedString("help06_header", comment: "Upload Management"))\n"
let titleAttributedString = NSMutableAttributedString(string: titleString)
titleAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontBold() : UIFont.piwigoFontSemiBold(), range: NSRange(location: 0, length: titleString.count))
legendAttributedString.append(titleAttributedString)
// Text
let textString = NSLocalizedString("help06_text", comment: "How to manage upload requests")
let textAttributedString = NSMutableAttributedString(string: textString)
textAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontNormal() : UIFont.piwigoFontSmall(), range: NSRange(location: 0, length: textString.count))
legendAttributedString.append(textAttributedString)
// Set legend
legend.attributedText = legendAttributedString
// Set image view
guard let imageUrl = Bundle.main.url(forResource: "help06", withExtension: "png") else {
fatalError("!!! Could not find help06 image !!!")
}
imageView.layoutIfNeeded() // Ensure imageView is in its final size.
let size = imageView.bounds.size
let scale = imageView.traitCollection.displayScale
imageView.image = ImageUtilities.downsample(imageAt: imageUrl, to: size, scale: scale)
// Remember that this view was watched
AppVars.shared.didWatchHelpViews = AppVars.shared.didWatchHelpViews | helpID
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set colors, fonts, etc.
applyColorPalette()
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Legend color
legend.textColor = .piwigoColorText()
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
}
| mit | 886d8180bf4a1a2c9a39316386a71f2e | 38.144737 | 198 | 0.673277 | 5.228471 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/Harvest/BillingStatsFetcher.swift | 2 | 2926 | //
// BillingStatsFetcher.swift
// GrandCentralBoard
//
// Created by Karol Kozub on 2016-04-14.
// Copyright © 2016 Oktawian Chojnacki. All rights reserved.
//
import Foundation
import GCBCore
import GCBUtilities
final class BillingStatsFetcher {
private let dates: [NSDate]
private let account: String
private let accessToken: AccessToken
private let downloader: NetworkRequestManager
init(account: String, accessToken: AccessToken, downloader: NetworkRequestManager, dates: [NSDate]) {
self.dates = dates
self.account = account
self.accessToken = accessToken
self.downloader = downloader
}
func fetchBillingStats(completion: (Result<[DailyBillingStats]>) -> Void) {
fetchProjectList { result in
switch result {
case .Success(let projectIDs):
self.fetchBillingStats(projectIDs, dates: self.dates, fetchedStats: [], completion: completion)
case .Failure(let error):
completion(.Failure(error))
}
}
}
private func fetchProjectList(completion: (Result<[BillingProjectID]>) -> Void) {
let projectListFetcher = BillingProjectListFetcher(account: account, accessToken: accessToken, downloader: downloader)
projectListFetcher.fetchProjectList(completion)
}
private func fetchBillingStats(projectIDs: [BillingProjectID], dates: [NSDate], fetchedStats: [DailyBillingStats],
completion: (Result<[DailyBillingStats]>) -> Void) {
if dates.count == 0 {
return completion(.Success(fetchedStats))
}
var remainingDates = dates
let date = dates.first!
remainingDates.removeFirst()
let dailyFetcher = DailyBillingStatsFetcher(projectIDs: projectIDs, date: date, account: account,
accessToken: accessToken, downloader: downloader)
dailyFetcher.fetchDailyBillingStats { result in
switch result {
case .Success(let dailyStats):
var fetchedStats = fetchedStats
fetchedStats.append(dailyStats)
self.fetchBillingStats(projectIDs, dates: remainingDates, fetchedStats: fetchedStats, completion: completion)
case .Failure(let error):
completion(.Failure(error))
}
}
}
}
extension NSDate {
static func arrayOfPreviousDays(numberOfDays: Int) -> [NSDate] {
return (1...numberOfDays).map({ index in
return NSDate().dateDaysAgo(index)
})
}
func dateDaysAgo(daysAgo: Int) -> NSDate {
return dateWithDayOffset(-daysAgo)
}
func dateWithDayOffset(numberOfDays: Int) -> NSDate {
let timeInterval = NSTimeInterval(numberOfDays * 24 * 3600)
return self.dateByAddingTimeInterval(timeInterval)
}
}
| gpl-3.0 | 9947f225f9a63fb40a8c2706e9b825b4 | 31.5 | 126 | 0.639316 | 5.113636 | false | false | false | false |
Tinker-S/SpriteKitDemoBySwift | SpriteKitDemoBySwift/GameScene.swift | 1 | 7861 | //
// GameScene.swift
// SpriteKitDemoBySwift
//
// Created by Ting Sun on 7/29/14.
// Copyright (c) 2014 Tinker S. All rights reserved.
//
import SpriteKit
import AVFoundation
class GameScene: SKScene, SKPhysicsContactDelegate {
var lastSpawnTimeInterval: CFTimeInterval = 0.0
var lastUpdateTimeInterval: CFTimeInterval = 0.0
var player: SKSpriteNode!
var backgroundMusicPlayer: AVAudioPlayer!
// win if hit more than 20 monsters
var monsterDestroyed = 0
// lose if more than 5 monsters escaped
var monsterEscaped = 0
let projectileCategory: UInt32 = 1 << 0
let monsterCategory: UInt32 = 1 << 1
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
init(size: CGSize) {
super.init(size: size)
}
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!"
myLabel.fontSize = 65
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.backgroundColor = SKColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0)
player = SKSpriteNode(imageNamed: "player");
player.position = CGPoint(x: 100, y: 100)
self.addChild(myLabel)
self.addChild(player)
self.physicsWorld.gravity = CGVector(0, 0)
self.physicsWorld.contactDelegate = self
self.backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: NSBundle.mainBundle().URLForResource("background-music-aac", withExtension: "caf"), error: nil)
self.backgroundMusicPlayer.numberOfLoops = 1
self.backgroundMusicPlayer.prepareToPlay()
self.backgroundMusicPlayer.play()
}
func addMonster() {
let monster = SKSpriteNode(imageNamed: "monster")
let minY = monster.size.height / 2
let maxY = self.frame.size.height - monster.size.height / 2
let rangeY = maxY - minY
let actualY: Double = Double(arc4random() % UInt32(rangeY)) + minY
monster.position = CGPoint(x: self.frame.size.width / 2 + monster.size.width / 2, y: actualY)
addChild(monster)
let minDuration = 2.0
let maxDuration = 4.0
let rangeDuration = maxDuration - minDuration
let actualDuration = Double(arc4random() % UInt32(rangeDuration)) + minDuration
let actionMove: SKAction = SKAction.moveTo(CGPoint(x: -monster.size.width / 2, y: actualY), duration: actualDuration)
//let actionMoveDone: SKAction = SKAction.removeFromParent()
let actionMoveDone = SKAction.runBlock({
self.monsterEscaped++
if self.monsterEscaped > 5 {
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let gameOverScene = GameOverScene(size: self.size, won: false)
self.view.presentScene(gameOverScene, transition: reveal)
}
})
monster.runAction(SKAction.sequence([actionMove, actionMoveDone]))
//为怪物sprite 创建物理外形。在这里,这个外形被定义成和怪物sprite大小一致的矩形,与怪物自身大致相匹配
monster.physicsBody = SKPhysicsBody(rectangleOfSize: monster.size)
//将怪物物理外形的dynamic(动态)属性置为YES。这表示怪物的移动不会被物理引擎所控制。你可以在这里不受影响而继续使用之前的代码(指之前怪物的移动action)
monster.physicsBody.dynamic = true
//把怪物物理外形的种类掩码设为刚刚定义的 monsterCategory
monster.physicsBody.categoryBitMask = monsterCategory
//当发生碰撞时,当前怪物对象会通知它contactTestBitMask 这个属性所代表的category。这里应该把子弹的种类掩码projectileCategory赋给它
monster.physicsBody.contactTestBitMask = projectileCategory
//collisionBitMask 这个属性表示哪些种类的对象与当前怪物对象相碰撞时物理引擎要让其有所反应(比如回弹效果)。你并不想让怪物和子弹彼此之间发生回弹,设置这个属性为0吧。当然这在其他游戏里是可能的
monster.physicsBody.collisionBitMask = 0
}
func updateWithTimeSinceLastUpdate(timeSinceLast: CFTimeInterval) -> Void {
self.lastSpawnTimeInterval += timeSinceLast
if self.lastSpawnTimeInterval > 1 {
self.lastSpawnTimeInterval = 0
self.addMonster()
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch: AnyObject! = touches.anyObject()
let location = touch.locationInNode(self)
// 初始化子弹位置
let projectTile = SKSpriteNode(imageNamed: "projectile")
projectTile.position = player.position
// 计算子弹移动的偏移量
let offset = CGPoint(x: location.x - projectTile.position.x, y: location.y - projectTile.position.y)
if offset.x <= 0 {
return
}
addChild(projectTile)
let length = sqrt(offset.x * offset.x + offset.y * offset.y)
let direction = CGPoint(x: offset.x / length, y: offset.y / length)
let shootAmount = CGPoint(x: direction.x * 1000, y: direction.y * 1000)
let realDest = CGPoint(x: shootAmount.x + projectTile.position.x, y: shootAmount.y + projectTile.position.y)
let velocity = 480.0 / 1.0
let realMoveDuration = self.frame.size.width / velocity
let actionMove = SKAction.moveTo(realDest, duration: realMoveDuration)
let actionMoveDone = SKAction.removeFromParent()
projectTile.runAction(SKAction.sequence([actionMove, actionMoveDone]))
projectTile.physicsBody = SKPhysicsBody(rectangleOfSize: projectTile.size)
projectTile.physicsBody.dynamic = true
projectTile.physicsBody.categoryBitMask = projectileCategory
projectTile.physicsBody.contactTestBitMask = monsterCategory
projectTile.physicsBody.collisionBitMask = 0
projectTile.physicsBody.usesPreciseCollisionDetection = true
self.runAction(SKAction.playSoundFileNamed("pew-pew-lei.caf", waitForCompletion: false))
}
override func update(currentTime: CFTimeInterval) {
var timeSinceLast = currentTime - lastUpdateTimeInterval
lastUpdateTimeInterval = currentTime
if timeSinceLast > 1 {
timeSinceLast = 1.0 / 60.0
lastUpdateTimeInterval = currentTime
}
updateWithTimeSinceLastUpdate(timeSinceLast)
}
func didCollideWithMonster(projectile: SKNode, monster: SKNode) {
projectile.removeFromParent()
monster.removeFromParent()
self.monsterDestroyed++
if self.monsterDestroyed > 20 {
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let gameOverScene = GameOverScene(size: self.size, won: true)
self.view.presentScene(gameOverScene, transition: reveal)
}
}
func didBeginContact(contact: SKPhysicsContact!) {
var firstBody: SKPhysicsBody!
var secondBody: SKPhysicsBody!
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
secondBody = contact.bodyA
firstBody = contact.bodyB
}
if (firstBody.categoryBitMask & projectileCategory != 0) && (secondBody.categoryBitMask & monsterCategory != 0) {
didCollideWithMonster(firstBody.node, monster: secondBody.node)
}
}
}
| apache-2.0 | bc8c95dbbd39247adb17509a99b2dc94 | 38.562162 | 161 | 0.655417 | 4.49294 | false | false | false | false |
yanif/circator | MetabolicCompassWatchExtension/ExerciseStartTimeController.swift | 1 | 4552 | //
// ExerciseStartTimeController.swift
// MetabolicCompass
//
// Created by twoolf on 6/25/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import WatchKit
import Foundation
import HealthKit
import SwiftDate
class ExerciseStartTimeController: WKInterfaceController {
@IBOutlet var exerciseStartTimePicker: WKInterfacePicker!
@IBOutlet var exerciseStartTimeButton: WKInterfaceButton!
var exerciseClose = 0
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
exerciseStartTimeButton.setTitle("End \(exerciseTypebyButton.exerciseType) ")
var tempItems: [WKPickerItem] = []
for i in 0...48 {
let item = WKPickerItem()
item.contentImage = WKImage(imageName: "Time\(i)")
tempItems.append(item)
}
exerciseStartTimePicker.setItems(tempItems)
exerciseStartTimePicker.setSelectedItemIndex((exerciseTimeStruc.exerciseBegin)+2)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
func showButton() {
let buttonColor = UIColor(red: 0.50, green: 0.0, blue: 0.13, alpha: 0.5)
exerciseStartTimeButton.setBackgroundColor(buttonColor)
exerciseStartTimeButton.setTitle("Saved")
// setting up conversion of saved value from 'end of exercise' in 1st screen
let thisRegion = DateRegion()
let calendar = NSCalendar.currentCalendar()
var beginDate = NSDate.today(inRegion: thisRegion)
let beginComponents = calendar.components([.Year, .Month, .Day, .Hour, .Minute], fromDate: beginDate)
var timeConvertBegin:Int = 0
var timeAddHalfHourBegin:Int = 0
// note: imageset (0-47) is keyed into 24-hour schedule
// so 0=midnight, 2=1AM, 4=2AM, etc
if exerciseTimeStruc.exerciseBegin % 2 == 0 {
_=0
timeConvertBegin = ( (exerciseTimeStruc.exerciseBegin)/2 )
} else {
timeConvertBegin = ( (exerciseTimeStruc.exerciseBegin-1)/2 )
timeAddHalfHourBegin=30
}
beginComponents.hour = timeConvertBegin
beginComponents.minute = timeAddHalfHourBegin
beginDate = calendar.dateFromComponents(beginComponents)!
var closeDate = NSDate.today(inRegion: thisRegion)
var timeConvertClose:Int = 0
var timeAddHalfHourClose:Int = 0
if exerciseClose % 2 == 0 {
_=0
timeConvertClose = ( (exerciseClose)/2)
} else {
_=30
timeConvertClose = ( (exerciseClose-1)/2 )
timeAddHalfHourClose=30
}
let closeComponents = calendar.components([.Year, .Month, .Day, .Hour, .Minute], fromDate: closeDate)
closeComponents.hour = timeConvertClose
closeComponents.minute = timeAddHalfHourClose
closeDate = calendar.dateFromComponents(closeComponents)!
if closeDate < beginDate {
closeComponents.day = closeComponents.day-1
closeDate = calendar.dateFromComponents(closeComponents)!
}
let exerciseDurationHours = beginComponents.hour - closeComponents.hour
let exerciseDurationMinutes = beginComponents.minute - closeComponents.minute
let exerciseDurationTime = exerciseDurationHours*60+exerciseDurationMinutes
let workout = HKWorkout(activityType:
.Running,
startDate: beginDate,
endDate: closeDate,
duration: Double(exerciseDurationTime)*60,
totalEnergyBurned: HKQuantity(unit:HKUnit.calorieUnit(), doubleValue:0.0),
totalDistance: HKQuantity(unit:HKUnit.meterUnit(), doubleValue:0.0),
device: HKDevice.localDevice(),
metadata: [mealTypebyButton.mealType:"source"])
let healthKitStore:HKHealthStore = HKHealthStore()
healthKitStore.saveObject(workout) { success, error in
}
}
@IBAction func onExerciseStartPicker(value: Int) {
exerciseClose = value
}
@IBAction func onExerciseStartSaveButton() {
showButton()
dispatch_after(3,
dispatch_get_main_queue()){
self.popToRootController()
}
}
}
| apache-2.0 | b6f1b9a92cb931a73eb77c00b135f27d | 36.303279 | 109 | 0.618545 | 5.14819 | false | false | false | false |
huonw/swift | stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift | 6 | 9949 | //===--- Subprocess.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 SwiftPrivate
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku)
import Glibc
#endif
#if !os(Windows)
// posix_spawn is not available on Windows.
// posix_spawn is not available on Android.
// posix_spawn is not available on Haiku.
#if !os(Android) && !os(Haiku)
// posix_spawn isn't available in the public watchOS SDK, we sneak by the
// unavailable attribute declaration here of the APIs that we need.
// FIXME: Come up with a better way to deal with APIs that are pointers on some
// platforms but not others.
#if os(Linux)
typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t
#else
typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t?
#endif
@_silgen_name("_stdlib_posix_spawn_file_actions_init")
internal func _stdlib_posix_spawn_file_actions_init(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_destroy")
internal func _stdlib_posix_spawn_file_actions_destroy(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_addclose")
internal func _stdlib_posix_spawn_file_actions_addclose(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>,
_ filedes: CInt) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_adddup2")
internal func _stdlib_posix_spawn_file_actions_adddup2(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>,
_ filedes: CInt,
_ newfiledes: CInt) -> CInt
@_silgen_name("_stdlib_posix_spawn")
internal func _stdlib_posix_spawn(
_ pid: UnsafeMutablePointer<pid_t>?,
_ file: UnsafePointer<Int8>,
_ file_actions: UnsafePointer<_stdlib_posix_spawn_file_actions_t>?,
_ attrp: UnsafePointer<posix_spawnattr_t>?,
_ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>,
_ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt
#endif
/// Calls POSIX `pipe()`.
func posixPipe() -> (readFD: CInt, writeFD: CInt) {
var fds: [CInt] = [ -1, -1 ]
if pipe(&fds) != 0 {
preconditionFailure("pipe() failed")
}
return (fds[0], fds[1])
}
/// Start the same executable as a child process, redirecting its stdout and
/// stderr.
public func spawnChild(_ args: [String])
-> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) {
// The stdout, stdin, and stderr from the child process will be redirected
// to these pipes.
let childStdout = posixPipe()
let childStdin = posixPipe()
let childStderr = posixPipe()
#if os(Android) || os(Haiku)
// posix_spawn isn't available on Android. Instead, we fork and exec.
// To correctly communicate the exit status of the child process to this
// (parent) process, we'll use this pipe.
let childToParentPipe = posixPipe()
let pid = fork()
precondition(pid >= 0, "fork() failed")
if pid == 0 {
// pid of 0 means we are now in the child process.
// Capture the output before executing the program.
dup2(childStdout.writeFD, STDOUT_FILENO)
dup2(childStdin.readFD, STDIN_FILENO)
dup2(childStderr.writeFD, STDERR_FILENO)
// Set the "close on exec" flag on the parent write pipe. This will
// close the pipe if the execve() below successfully executes a child
// process.
let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC)
let closeErrno = errno
precondition(
closeResult == 0,
"Could not set the close behavior of the child-to-parent pipe; " +
"errno: \(closeErrno)")
// Start the executable. If execve() does not encounter an error, the
// code after this block will never be executed, and the parent write pipe
// will be closed.
withArrayOfCStrings([CommandLine.arguments[0]] + args) {
execve(CommandLine.arguments[0], $0, environ)
}
// If execve() encountered an error, we write the errno encountered to the
// parent write pipe.
let errnoSize = MemoryLayout.size(ofValue: errno)
var execveErrno = errno
let writtenBytes = withUnsafePointer(to: &execveErrno) {
write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize)
}
let writeErrno = errno
if writtenBytes > 0 && writtenBytes < errnoSize {
// We were able to write some of our error, but not all of it.
// FIXME: Retry in this case.
preconditionFailure("Unable to write entire error to child-to-parent " +
"pipe.")
} else if writtenBytes == 0 {
preconditionFailure("Unable to write error to child-to-parent pipe.")
} else if writtenBytes < 0 {
preconditionFailure("An error occurred when writing error to " +
"child-to-parent pipe; errno: \(writeErrno)")
}
// Close the pipe when we're done writing the error.
close(childToParentPipe.writeFD)
}
#else
var fileActions = _make_posix_spawn_file_actions_t()
if _stdlib_posix_spawn_file_actions_init(&fileActions) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_init() failed")
}
// Close the write end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStdin.writeFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdin.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStdin.readFD, STDIN_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStdout.readFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdout.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStderr.readFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stderr.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStderr.writeFD, STDERR_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
var pid: pid_t = -1
var childArgs = args
childArgs.insert(CommandLine.arguments[0], at: 0)
let interpreter = getenv("SWIFT_INTERPRETER")
if interpreter != nil {
if let invocation = String(validatingUTF8: interpreter!) {
childArgs.insert(invocation, at: 0)
}
}
let spawnResult = withArrayOfCStrings(childArgs) {
_stdlib_posix_spawn(
&pid, childArgs[0], &fileActions, nil, $0, environ)
}
if spawnResult != 0 {
print(String(cString: strerror(spawnResult)))
preconditionFailure("_stdlib_posix_spawn() failed")
}
if _stdlib_posix_spawn_file_actions_destroy(&fileActions) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_destroy() failed")
}
#endif
// Close the read end of the pipe on the parent side.
if close(childStdin.readFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStdout.writeFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStderr.writeFD) != 0 {
preconditionFailure("close() failed")
}
return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD)
}
#if !os(Android) && !os(Haiku)
#if os(Linux)
internal func _make_posix_spawn_file_actions_t()
-> _stdlib_posix_spawn_file_actions_t {
return posix_spawn_file_actions_t()
}
#else
internal func _make_posix_spawn_file_actions_t()
-> _stdlib_posix_spawn_file_actions_t {
return nil
}
#endif
#endif
internal func _signalToString(_ signal: Int) -> String {
switch CInt(signal) {
case SIGILL: return "SIGILL"
case SIGTRAP: return "SIGTRAP"
case SIGABRT: return "SIGABRT"
case SIGFPE: return "SIGFPE"
case SIGBUS: return "SIGBUS"
case SIGSEGV: return "SIGSEGV"
case SIGSYS: return "SIGSYS"
default: return "SIG???? (\(signal))"
}
}
public enum ProcessTerminationStatus : CustomStringConvertible {
case exit(Int)
case signal(Int)
public var description: String {
switch self {
case .exit(let status):
return "Exit(\(status))"
case .signal(let signal):
return "Signal(\(_signalToString(signal)))"
}
}
}
public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
var status: CInt = 0
#if os(Cygwin)
withUnsafeMutablePointer(to: &status) {
statusPtr in
let statusPtrWrapper = __wait_status_ptr_t(__int_ptr: statusPtr)
while waitpid(pid, statusPtrWrapper, 0) < 0 {
if errno != EINTR {
preconditionFailure("waitpid() failed")
}
}
}
#else
while waitpid(pid, &status, 0) < 0 {
if errno != EINTR {
preconditionFailure("waitpid() failed")
}
}
#endif
if WIFEXITED(status) {
return .exit(Int(WEXITSTATUS(status)))
}
if WIFSIGNALED(status) {
return .signal(Int(WTERMSIG(status)))
}
preconditionFailure("did not understand what happened to child process")
}
// !os(Windows)
#endif
| apache-2.0 | 2c1d618d40a81bb4fdc96d6c53e0b947 | 32.498316 | 85 | 0.680872 | 3.784329 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/View/NormalCell.swift | 1 | 2900 | //
// NormalCell.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/23.
// Copyright © 2016年 CoderST. All rights reserved.
// 普通cell
import UIKit
class NormalCell: UICollectionViewCell {
fileprivate lazy var iconImageView : UIImageView = {
let iconImageView = UIImageView()
iconImageView.contentMode = .scaleAspectFill
return iconImageView
}()
fileprivate lazy var trackTitleLabel : UILabel = {
let trackTitleLabel = UILabel()
trackTitleLabel.font = UIFont.systemFont(ofSize: 12)
trackTitleLabel.numberOfLines = 2
return trackTitleLabel
}()
fileprivate lazy var findImageView : UIImageView = {
let findImageView = UIImageView()
findImageView.contentMode = .scaleAspectFill
return findImageView
}()
fileprivate lazy var titleLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = UIColor.gray
titleLabel.font = UIFont.systemFont(ofSize: 12)
return titleLabel
}()
var hotRecommendsSubItem : HotSubModel?{
didSet{
iconImageView.sd_setImage( with: URL(string: hotRecommendsSubItem?.albumCoverUrl290 ?? ""), placeholderImage: UIImage(named: "placeholder_image"))
trackTitleLabel.text = hotRecommendsSubItem?.trackTitle
titleLabel.text = hotRecommendsSubItem?.title
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(iconImageView)
contentView.addSubview(trackTitleLabel)
contentView.addSubview(findImageView)
contentView.addSubview(titleLabel)
findImageView.image = UIImage(named: "find_specialicon")
trackTitleLabel.preferredMaxLayoutWidth = contentView.bounds.width - 5
iconImageView.snp.makeConstraints { (make) in
make.left.top.right.equalTo(contentView)
make.height.equalTo(contentView.snp.width)
}
trackTitleLabel.snp.makeConstraints { (make) in
make.left.equalTo(contentView)
// make.right.equalTo(contentView)
make.top.equalTo(iconImageView.snp.bottom)
}
findImageView.snp.makeConstraints { (make) in
make.left.equalTo(contentView).offset(5)
make.bottom.equalTo(contentView.snp.bottom).offset(-7)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(findImageView.snp.right).offset(5)
make.right.equalTo(contentView.snp.right).offset(-5)
make.bottom.equalTo(contentView.snp.bottom).offset(-5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | fb0c32d3b12560ec97a5c53519619c74 | 29.776596 | 158 | 0.622191 | 5.222022 | false | false | false | false |
itjhDev/HttpSwift2.0 | HttpSwift2.0/ViewController.swift | 1 | 4205 | //
// ViewController.swift
// HttpSwift2.0
//
// Created by SongLijun on 15/7/31.
// Copyright © 2015年 SongLijun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//天气的url
let url = "http://www.weather.com.cn/adat/sk/1121190408.html"
/*
返回结果
{
"weatherinfo":
{"city":"太仓","cityid":"101190408","temp":"13","WD":"西北风","WS":"3级","SD":"93%","WSE":"3","time":"10:20","isRadar":"0","Radar":"","njd":"暂无实况","qy":"1005"
}
}
*/
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*测试GET请求*/
@IBAction func getRequest(sender: UIButton) {
HttpSwift.request("get", url: url) { (data, response, error) -> Void in
//使用guard判断
guard error != nil else{
print(data)
return
}
}
}
/*测试POST请求*/
@IBAction func postRequest(sender: UIButton) {
HttpSwift.request("POST", url: url, params: ["post": "value"]) { (data, response, error) -> Void in
//使用guard判断
guard error != nil else{
print(data)
return
}
}
//let url = "http://pitayaswift.sinaapp.com/pitaya.php"
HttpSwift.post(url, callback: { (data, response, error) -> Void in
//使用guard判断
guard error != nil else{
print(data)
print("POST不带参数 请求成功")
return
}
})
HttpSwift.post(url, params: ["post": "POST Network"], callback: { (data, response, error) -> Void in
let string = data
//使用guard判断
guard error != nil else{
print(data)
print("POST 2 请求成功 \(string)")
return
}
})
HttpSwift.get(url, callback: { (data, response, error) -> Void in
let string = data
//使用guard判断
guard error != nil else{
print(data)
print("GET不带参数 请求成功 \(string)")
return
}
})
HttpSwift.get(url, params: ["get": "POST Network"], callback: { (data, response, error) -> Void in
let string = data
//使用guard判断
guard error != nil else{
print(data)
print("GET带参数 请求成功 \(string)")
return
}
})
//
// HttpSwift.put(url, params: ["put": "POST Network"]) { (data, response, error) -> Void in
// let string = data
//
// //使用guard判断
// guard error != nil else{
// print(data)
// print("PUT带参数 请求成功 \(string)")
// return
// }
// }
//
// HttpSwift.put(vc) { (data, response, error) -> Void in
// //使用guard判断
// guard error != nil else{
// print(data)
// print("PUT带参数 请求成功 \(data)")
// return
// }
//
// }
// HttpSwift.delete(url, params: ["id":122]) { (data, response, error) -> Void in
// guard error != nil else{
// print(data)
// print("DELETE带参数 请求成功\(data)")
// return
// }
//
// }
//
// HttpSwift.request("GET", url: url, params: ["get": "Request Network"]) { (data, response, error) -> Void in
// let string = data
// print("Request 请求成功 \(string)")
// }
}
}
| mit | b3ebbf2d2d75985fb54eb26224b29d0d | 25.56 | 156 | 0.440763 | 4.421754 | false | false | false | false |
drumnkyle/music-notation-swift | Sources/Key.swift | 1 | 829 | //
// Key.swift
// MusicNotationCore
//
// Created by Kyle Sherman on 7/11/15.
// Copyright © 2015 Kyle Sherman. All rights reserved.
//
public struct Key {
fileprivate let type: KeyType
fileprivate let noteLetter: NoteLetter
fileprivate let accidental: Accidental
public init(noteLetter: NoteLetter, accidental: Accidental = .natural, type: KeyType = .major) {
self.noteLetter = noteLetter
self.accidental = accidental
self.type = type
}
}
extension Key: CustomDebugStringConvertible {
public var debugDescription: String {
"\(noteLetter)\(accidental.debugDescription) \(type)"
}
}
extension Key: Equatable {
public static func == (lhs: Key, rhs: Key) -> Bool {
if lhs.type == rhs.type,
lhs.noteLetter == rhs.noteLetter,
lhs.accidental == rhs.accidental {
return true
}
return false
}
}
| mit | c687e654469397d896f2e91b1d3c0a23 | 22 | 97 | 0.708937 | 3.6 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Seller/views/SLVUserFollowSectionView.swift | 1 | 2528 | //
// SLVUserFollowSectionView.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 2..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLVUserFollowSectionView: UICollectionReusableView {
@IBOutlet weak var sellerImageView: UIImageView!
@IBOutlet weak var sellerNameLabel: UILabel!
@IBOutlet weak var mannerLabel: UILabel!
@IBOutlet weak var followerCountLabel: UILabel!
@IBOutlet weak var sellingItemsCountLabel: UILabel!
@IBOutlet weak var soldItemsCountLabel: UILabel!
@IBOutlet weak var sellerImageButton: UIButton!
@IBOutlet weak var sellerNameButton: UIButton!
@IBOutlet weak var mannerButton: UIButton! //매너지수(하트)
@IBOutlet weak var followerButton: UIButton! //팔로워
@IBOutlet weak var salesButton: UIButton! //판매중
@IBOutlet weak var soldButton: UIButton! //거래완료
@IBOutlet weak var followButton: UIButton!
var followerInfo: SLVSellerFollower?
override public func awakeFromNib() {
super.awakeFromNib()
}
func setupData(follower: SLVSellerFollower) {
self.followerInfo = follower
if let user = self.followerInfo {
let name = user.nickname ?? ""
let thumb = user.avatar ?? ""
let manners = user.mannerPoint ?? 0
let followers = user.followersCount ?? 0
let sales = user.onSaleCount ?? 0
let dones = user.completeSaleCount ?? 0
self.sellerNameLabel?.text = name
if thumb != "" {
let dnModel = SLVDnImageModel.shared
let url = URL(string: "\(dnAvatar)\(thumb)")
if let url = url {
dnModel.setupImageView(view: self.sellerImageView, from: url)
}
}
self.mannerLabel.text = "\(manners)"
self.followerCountLabel.text = "\(followers)"
self.sellingItemsCountLabel.text = "\(sales)"
self.soldItemsCountLabel.text = "\(dones)"
}
}
//MARK: Event
@IBAction func touchSellerItem(_ sender: Any) {
//UserPage 이동
}
@IBAction func touchReviewsItem(_ sender: Any) {
//구매후기 이동
}
@IBAction func touchFollowItem(_ sender: Any) {
//UserPage 팔로워 이동
}
//TODO: FOLLOW 처리할 것
@IBAction func touchFollow(_ sender: Any) {
}
}
| mit | 4d5af14e6d6aec3d95f0a0626e4768ef | 29.6625 | 81 | 0.594374 | 4.388193 | false | false | false | false |
xiaoxionglaoshi/DNSwiftProject | DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/DictionaryExtension.swift | 1 | 1365 | //
// DictionaryExtension.swift
// DNSwiftProject
//
// Created by mainone on 16/12/22.
// Copyright © 2016年 wjn. All rights reserved.
//
import Foundation
public extension Dictionary {
// 字典中指定key是否存在
func has(key: Key) -> Bool {
return index(forKey: key) != nil
}
// dictionary 转 data
public func jsonData(prettify: Bool = false) -> Data? {
guard JSONSerialization.isValidJSONObject(self) else {
return nil
}
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: options)
return jsonData
} catch {
return nil
}
}
// dictionary 转 json.
public func jsonString(prettify: Bool = false) -> String? {
guard JSONSerialization.isValidJSONObject(self) else {
return nil
}
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: options)
return String(data: jsonData, encoding: .utf8)
} catch {
return nil
}
}
}
| apache-2.0 | 448c6ceb870aee7db9c86b9d3cffeb4a | 29.454545 | 126 | 0.614179 | 4.802867 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/misc/utils/StringBuilder.swift | 3 | 1673 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
//
// StringBuilder.swift
// antlr.swift
//
// Created by janyou on 15/9/4.
//
import Foundation
public class StringBuilder {
private var stringValue: String
public init(string: String = "") {
self.stringValue = string
}
public func toString() -> String {
return stringValue
}
public var length: Int {
return stringValue.length
}
@discardableResult
public func append(_ string: String) -> StringBuilder {
stringValue += string
return self
}
@discardableResult
public func append<T:CustomStringConvertible>(_ value: T) -> StringBuilder {
stringValue += value.description
return self
}
@discardableResult
public func appendLine(_ string: String) -> StringBuilder {
stringValue += string + "\n"
return self
}
@discardableResult
public func appendLine<T:CustomStringConvertible>(_ value: T) -> StringBuilder {
stringValue += value.description + "\n"
return self
}
@discardableResult
public func clear() -> StringBuilder {
stringValue = ""
return self
}
}
public func +=(lhs: StringBuilder, rhs: String) {
lhs.append(rhs)
}
public func +=<T:CustomStringConvertible>(lhs: StringBuilder, rhs: T) {
lhs.append(rhs.description)
}
public func +(lhs: StringBuilder, rhs: StringBuilder) -> StringBuilder {
return StringBuilder(string: lhs.toString() + rhs.toString())
}
| mit | e63309f64fc3eab0c6ee82a5b8e91661 | 23.970149 | 84 | 0.64734 | 4.497312 | false | false | false | false |
1amageek/Toolbar | Example/ChatViewController.swift | 1 | 6657 | //
// ChatViewController.swift
// Toolbar
//
// Created by 1amageek on 2017/04/24.
// Copyright © 2017年 Stamp Inc. All rights reserved.
//
import UIKit
//import Toolbar
class ChatViewController: UIViewController, UITextViewDelegate {
let toolbar: Toolbar = Toolbar()
var textView: UITextView?
var item0: ToolbarItem?
var item1: ToolbarItem?
lazy var camera: ToolbarItem = {
let item: ToolbarItem = ToolbarItem(image: #imageLiteral(resourceName: "camera"), target: nil, action: nil)
return item
}()
lazy var microphone: ToolbarItem = {
let item: ToolbarItem = ToolbarItem(image: #imageLiteral(resourceName: "microphone"), target: nil, action: nil)
return item
}()
lazy var picture: ToolbarItem = {
let item: ToolbarItem = ToolbarItem(image: #imageLiteral(resourceName: "picture"), target: nil, action: nil)
return item
}()
lazy var menu: ToolbarItem = {
let item: ToolbarItem = ToolbarItem(image: #imageLiteral(resourceName: "Add"), target: self, action: #selector(toggleMenu))
return item
}()
var toolbarBottomConstraint: NSLayoutConstraint?
override func loadView() {
super.loadView()
self.view.addSubview(toolbar)
if #available(iOS 11.0, *) {
self.toolbarBottomConstraint = self.view.bottomAnchor.constraint(equalTo: self.toolbar.bottomAnchor, constant: 0)
} else {
// Fallback on earlier versions
}
self.toolbarBottomConstraint?.isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
self.toolbar.maximumHeight = 100
let view: UITextView = UITextView(frame: .zero)
view.delegate = self
view.font = UIFont.systemFont(ofSize: 14)
self.textView = view
self.item0 = ToolbarItem(customView: view)
self.item1 = ToolbarItem(title: "Send", target: self, action: #selector(send))
self.toolbar.setItems([self.menu, self.camera, self.picture, self.microphone, self.item0!, self.item1!], animated: false)
let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hide))
self.view.addGestureRecognizer(gestureRecognizer)
self.item1?.isEnabled = false
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "SafeArea", style: .plain, target: self, action: #selector(setSafeArea))
}
var bottomSafeArea: CGFloat = 0 {
didSet {
if #available(iOS 11.0, *) {
self.additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: self.bottomSafeArea, right: 0)
} else {
// Fallback on earlier versions
}
self.view.setNeedsLayout()
}
}
@objc func setSafeArea() {
if #available(iOS 11.0, *) {
self.bottomSafeArea = self.additionalSafeAreaInsets.bottom == 0 ? 100 : 0
} else {
// Fallback on earlier versions
}
}
var isMenuHidden: Bool = false {
didSet {
if oldValue == isMenuHidden {
return
}
self.toolbar.layoutIfNeeded()
// self.camera.setHidden(isMenuHidden, animated: true)
// self.microphone.setHidden(isMenuHidden, animated: true)
// self.picture.setHidden(isMenuHidden, animated: true)
UIView.animate(withDuration: 0.3) {
self.camera.isHidden = self.isMenuHidden
self.microphone.isHidden = self.isMenuHidden
self.picture.isHidden = self.isMenuHidden
self.toolbar.layoutIfNeeded()
}
}
}
@objc func toggleMenu() {
self.isMenuHidden = !self.isMenuHidden
}
@objc func hide() {
self.textView?.resignFirstResponder()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
@objc final func keyboardWillShow(notification: Notification) {
moveToolbar(up: true, notification: notification)
}
@objc final func keyboardWillHide(notification: Notification) {
moveToolbar(up: false, notification: notification)
}
final func moveToolbar(up: Bool, notification: Notification) {
guard let userInfo = notification.userInfo else {
return
}
self.view.layoutIfNeeded()
let animationDuration: TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let keyboardHeight = up ? (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height : 0
// Animation
self.toolbarBottomConstraint?.constant = keyboardHeight
UIView.animate(withDuration: animationDuration, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
self.isMenuHidden = up
}
@objc func send() {
self.textView?.text = nil
if let constraint: NSLayoutConstraint = self.constraint {
self.textView?.removeConstraint(constraint)
}
self.toolbar.setNeedsLayout()
}
func textViewDidBeginEditing(_ textView: UITextView) {
self.isMenuHidden = true
}
func textViewDidChange(_ textView: UITextView) {
self.item1?.isEnabled = !textView.text.isEmpty
let size: CGSize = textView.sizeThatFits(textView.bounds.size)
if let constraint: NSLayoutConstraint = self.constraint {
textView.removeConstraint(constraint)
}
self.constraint = textView.heightAnchor.constraint(equalToConstant: size.height)
self.constraint?.priority = UILayoutPriority.defaultHigh
self.constraint?.isActive = true
}
var constraint: NSLayoutConstraint?
// MARK: -
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
self.toolbar.setNeedsUpdateConstraints()
}
}
| mit | 75cb74e7073a161d35a0707c9866ab49 | 35.163043 | 175 | 0.64217 | 5.126348 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios | Example/SuperAwesomeExampleTests/Common/Components/EncoderTests.swift | 1 | 890 | //
// EncoderTests.swift
// Tests
//
// Created by Gunhan Sancar on 22/04/2020.
//
import XCTest
import Nimble
@testable import SuperAwesome
class EncoderTests: XCTestCase {
func testEncoding() throws {
// Given
let encoder = CustomEncoder()
let given1 = "https://s3-eu-west-1.amazonaws.com/sb-ads-video-transcoded/x7XkGy43vim5P1OpldlOUuxk2cuKsDSn.mp4"
let given2 = ""
let given3: String? = nil
let given4 = "Gunhan Sancar"
let expected =
"https%3A%2F%2Fs3-eu-west-1.amazonaws.com%2Fsb-ads-video-transcoded%2Fx7XkGy43vim5P1OpldlOUuxk2cuKsDSn.mp4"
// Then
expect(encoder.encodeUri(given1)).to(equal(expected))
expect(encoder.encodeUri(given2)).to(equal(""))
expect(encoder.encodeUri(given3)).to(equal(""))
expect(encoder.encodeUri(given4)).to(equal("Gunhan%20Sancar"))
}
}
| lgpl-3.0 | d52fc1e81218944aead4fcef0f916783 | 29.689655 | 118 | 0.658427 | 3.090278 | false | true | false | false |
zero2launch/z2l-ios-social-network | InstagramClone/CommentTableViewCell.swift | 1 | 2334 | //
// CommentTableViewCell.swift
// InstagramClone
//
// Created by The Zero2Launch Team on 1/1/17.
// Copyright © 2017 The Zero2Launch Team. All rights reserved.
//
import UIKit
import KILabel
protocol CommentTableViewCellDelegate {
func goToProfileUserVC(userId: String)
}
class CommentTableViewCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var commentLabel: KILabel!
var delegate: CommentTableViewCellDelegate?
var comment: Comment? {
didSet {
updateView()
}
}
var user: User? {
didSet {
setupUserInfo()
}
}
func updateView() {
commentLabel.text = comment?.commentText
commentLabel.userHandleLinkTapHandler = {
label, handle, rang in
var mention = handle
mention = String(mention.characters.dropFirst())
Api.User.observeUserByUsername(username: mention.lowercased(), completion: { (user) in
self.delegate?.goToProfileUserVC(userId: user.id!)
})
}
}
func setupUserInfo() {
nameLabel.text = user?.username
if let photoUrlString = user?.profileImageUrl {
let photoUrl = URL(string: photoUrlString)
profileImageView.sd_setImage(with: photoUrl, placeholderImage: UIImage(named: "placeholderImg"))
}
}
override func awakeFromNib() {
super.awakeFromNib()
nameLabel.text = ""
commentLabel.text = ""
let tapGestureForNameLabel = UITapGestureRecognizer(target: self, action: #selector(self.nameLabel_TouchUpInside))
nameLabel.addGestureRecognizer(tapGestureForNameLabel)
nameLabel.isUserInteractionEnabled = true
}
func nameLabel_TouchUpInside() {
if let id = user?.id {
delegate?.goToProfileUserVC(userId: id)
}
}
override func prepareForReuse() {
super.prepareForReuse()
profileImageView.image = UIImage(named: "placeholderImg")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 490a401278a832d5d0e870e695f69e16 | 27.802469 | 122 | 0.627947 | 5.049784 | false | false | false | false |
fgulan/letter-ml | project/LetterML/Frameworks/framework/Source/FramebufferCache.swift | 7 | 2442 | #if os(Linux)
#if GLES
import COpenGLES.gles2
#else
import COpenGL
#endif
#else
#if GLES
import OpenGLES
#else
import OpenGL.GL3
#endif
#endif
// TODO: Add mechanism to purge framebuffers on low memory
public class FramebufferCache {
var framebufferCache = [Int64:[Framebuffer]]()
let context:OpenGLContext
init(context:OpenGLContext) {
self.context = context
}
public func requestFramebufferWithProperties(orientation:ImageOrientation, size:GLSize, textureOnly:Bool = false, minFilter:Int32 = GL_LINEAR, magFilter:Int32 = GL_LINEAR, wrapS:Int32 = GL_CLAMP_TO_EDGE, wrapT:Int32 = GL_CLAMP_TO_EDGE, internalFormat:Int32 = GL_RGBA, format:Int32 = GL_BGRA, type:Int32 = GL_UNSIGNED_BYTE, stencil:Bool = false) -> Framebuffer {
let hash = hashForFramebufferWithProperties(orientation:orientation, size:size, textureOnly:textureOnly, minFilter:minFilter, magFilter:magFilter, wrapS:wrapS, wrapT:wrapT, internalFormat:internalFormat, format:format, type:type, stencil:stencil)
let framebuffer:Framebuffer
if ((framebufferCache[hash]?.count ?? -1) > 0) {
// print("Restoring previous framebuffer")
framebuffer = framebufferCache[hash]!.removeLast()
framebuffer.orientation = orientation
} else {
do {
debugPrint("Generating new framebuffer at size: \(size)")
framebuffer = try Framebuffer(context:context, orientation:orientation, size:size, textureOnly:textureOnly, minFilter:minFilter, magFilter:magFilter, wrapS:wrapS, wrapT:wrapT, internalFormat:internalFormat, format:format, type:type, stencil:stencil)
framebuffer.cache = self
} catch {
fatalError("Could not create a framebuffer of the size (\(size.width), \(size.height)), error: \(error)")
}
}
return framebuffer
}
public func purgeAllUnassignedFramebuffers() {
framebufferCache.removeAll()
}
func returnToCache(_ framebuffer:Framebuffer) {
// print("Returning to cache: \(framebuffer)")
context.runOperationSynchronously{
if (self.framebufferCache[framebuffer.hash] != nil) {
self.framebufferCache[framebuffer.hash]!.append(framebuffer)
} else {
self.framebufferCache[framebuffer.hash] = [framebuffer]
}
}
}
}
| mit | 9f7497eac44815cf91833c772b6b0b19 | 39.7 | 365 | 0.662981 | 4.488971 | false | false | false | false |
auth0/Lock.swift | LockTests/Presenters/PasswordlessPresenterSpec.swift | 1 | 25271 | // PasswordlessPresenterSpec.swift
//
// Copyright (c) 2017 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 Quick
import Nimble
import Auth0
@testable import Lock
private let phone = "01234567891"
private let countryData = CountryCode(isoCode: "UK", phoneCode: "+44", localizedName: "United Kingdom")
class PasswordlessPresenterSpec: QuickSpec {
override func spec() {
let authentication = Auth0.authentication(clientId: clientId, domain: domain)
var messagePresenter: MockMessagePresenter!
var options: OptionBuildable!
var user: User!
var passwordlessActivity: MockPasswordlessActivity!
var interactor: PasswordlessInteractor!
var presenter: PasswordlessPresenter!
var connection: PasswordlessConnection!
var navigator: MockNavigator!
var dispatcher: Dispatcher!
var view: PasswordlessView!
context("email") {
beforeEach {
navigator = MockNavigator()
connection = PasswordlessConnection(name: "custom-email", strategy: "email")
messagePresenter = MockMessagePresenter()
options = LockOptions()
options.passwordlessMethod = .code
user = User()
passwordlessActivity = MockPasswordlessActivity()
dispatcher = ObserverStore()
interactor = PasswordlessInteractor(connection: connection, authentication: authentication, dispatcher: dispatcher, user: user, options: options, passwordlessActivity: passwordlessActivity)
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
describe("request screen") {
it("should show request screen") {
expect(presenter.screen) == PasswordlessScreen.request
}
it("should expect email input in form") {
let form = view.form as! SingleInputView
expect(form.type) == InputField.InputType.email
}
it("should expect no secondary button") {
expect(view.secondaryButton).to(beNil())
}
describe("input") {
it("should update email") {
let input = mockInput(.email, value: email)
view.form?.onValueChange(input)
expect(interactor.identifier) == email
expect(interactor.validIdentifier) == true
}
it("should show field error if email is invalid") {
let input = mockInput(.email, value: "invalid_email")
view.form?.onValueChange(input)
expect(input.valid) == false
}
}
describe("request code") {
var interactor: MockPasswordlessInteractor!
beforeEach {
interactor = MockPasswordlessInteractor()
interactor.onLogin = { return nil }
interactor.onRequest = { return nil }
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should trigger action on return of field") {
let input = mockInput(.email, value: email)
input.returnKey = .done
interactor.onRequest = { return nil }
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beNil())
}
it("should not trigger action with nil button") {
let input = mockInput(.email, value: email)
input.returnKey = .done
interactor.onRequest = { return nil }
view.primaryButton = nil
view.form?.onReturn(input)
expect(messagePresenter.message).toEventually(beNil())
expect(messagePresenter.error).toEventually(beNil())
}
it("should trigger action on primary button press") {
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beNil())
}
it("should route to code screen upon success") {
view.primaryButton!.onPress(view.primaryButton!)
expect(navigator.route).toEventually(equal(Route.passwordless(screen: .code, connection: connection)))
}
it("should show error on failure") {
interactor.onRequest = { return .codeNotSent }
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventuallyNot(beNil())
}
}
describe("request link") {
var interactor: MockPasswordlessInteractor!
beforeEach {
options.passwordlessMethod = .magicLink
interactor = MockPasswordlessInteractor()
interactor.onLogin = { return nil }
interactor.onRequest = { return nil }
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should trigger action on return of field") {
let input = mockInput(.email, value: email)
input.returnKey = .done
interactor.onRequest = { return nil }
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beNil())
}
it("should trigger action on primary button press") {
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beNil())
}
it("should route to link sent screen upon success") {
view.primaryButton!.onPress(view.primaryButton!)
expect(navigator.route).toEventually(equal(Route.passwordless(screen: .linkSent, connection: connection)))
}
it("should show error on failure") {
interactor.onRequest = { return .codeNotSent }
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventuallyNot(beNil())
}
}
}
describe("code auth screen") {
let screen = PasswordlessScreen.code
beforeEach {
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should show code screen") {
expect(presenter.screen) == PasswordlessScreen.code
}
it("should expect code input in form") {
let form = view.form as! SingleInputView
expect(form.type) == InputField.InputType.oneTimePassword
}
it("should expect title on secondary button") {
expect(view.secondaryButton!.title).to(contain("Did not get the code"))
}
describe("input") {
it("should update code") {
let input = mockInput(.oneTimePassword, value: "123456")
view.form?.onValueChange(input)
expect(presenter.interactor.code) == "123456"
expect(presenter.interactor.validCode) == true
}
it("should show field error if code is invalid") {
let input = mockInput(.oneTimePassword, value: "ABC")
view.form?.onValueChange(input)
expect(input.valid) == false
}
}
describe("login") {
var interactor: MockPasswordlessInteractor!
beforeEach {
interactor = MockPasswordlessInteractor()
interactor.onLogin = { return nil }
interactor.onRequest = { return nil }
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should trigger action on return of field") {
messagePresenter.error = CredentialAuthError.couldNotLogin
let input = mockInput(.oneTimePassword, value: "123456")
input.returnKey = .done
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beNil())
}
it("should show no error upon success") {
messagePresenter.error = CredentialAuthError.couldNotLogin
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beNil())
}
it("should show error on failure") {
interactor.onLogin = { return .couldNotLogin }
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventuallyNot(beNil())
}
}
}
describe("link sent screen") {
let screen = PasswordlessScreen.linkSent
beforeEach {
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should show code screen") {
expect(presenter.screen) == PasswordlessScreen.linkSent
}
it("should expect title on secondary button") {
expect(view.secondaryButton!.title).to(contain("Did not receive the link"))
}
it("should expect title on secondary button if using magic links") {
options.passwordlessMethod = .magicLink
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
view = presenter.view as? PasswordlessView
expect(view.secondaryButton!.title).to(contain("I have a code"))
}
}
}
context("sms") {
beforeEach {
navigator = MockNavigator()
connection = PasswordlessConnection(name: "custom-sms", strategy: "sms")
messagePresenter = MockMessagePresenter()
options = LockOptions()
options.passwordlessMethod = .code
user = User()
passwordlessActivity = MockPasswordlessActivity()
dispatcher = ObserverStore()
interactor = PasswordlessInteractor(connection: connection, authentication: authentication, dispatcher: dispatcher, user: user, options: options, passwordlessActivity: passwordlessActivity)
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
describe("request screen") {
it("should show request screen") {
expect(presenter.screen) == PasswordlessScreen.request
}
it("should expect phone input in form") {
let form = view.form as! InternationalPhoneInputView
expect(form.type) == InputField.InputType.phone
}
it("should expect country store data in form") {
let form = view.form as! InternationalPhoneInputView
expect(form.countryStore).toNot(beNil())
}
it("should expect no secondary button") {
expect(view.secondaryButton).to(beNil())
}
describe("input") {
it("should update sms") {
let input = mockInput(.phone, value: phone)
view.form?.onValueChange(input)
expect(interactor.identifier) == phone
expect(interactor.validIdentifier) == true
}
it("should show field error if email is invalid") {
let input = mockInput(.phone, value: "0")
view.form?.onValueChange(input)
expect(input.valid) == false
}
it("should update country") {
view.form?.onCountryChange(countryData)
expect(interactor.countryCode?.localizedName) == countryData.localizedName
}
it("should show field error if invalid input type") {
let input = mockInput(.username, value: "0")
view.form?.onValueChange(input)
expect(input.valid) == false
}
}
describe("request code") {
var interactor: MockPasswordlessInteractor!
beforeEach {
interactor = MockPasswordlessInteractor()
interactor.onLogin = { return nil }
interactor.onRequest = { return nil }
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should trigger action on return of field") {
let input = mockInput(.phone, value: phone)
input.returnKey = .done
interactor.onRequest = { return nil }
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beNil())
}
it("should not trigger action with nil button") {
let input = mockInput(.phone, value: phone)
input.returnKey = .done
interactor.onRequest = { return nil }
view.primaryButton = nil
view.form?.onReturn(input)
expect(messagePresenter.message).toEventually(beNil())
expect(messagePresenter.error).toEventually(beNil())
}
it("should trigger action on primary button press") {
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beNil())
}
it("should route to code screen upon success") {
view.primaryButton!.onPress(view.primaryButton!)
expect(navigator.route).toEventually(equal(Route.passwordless(screen: .code, connection: connection)))
}
it("should show error on failure") {
interactor.onRequest = { return .codeNotSent }
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventuallyNot(beNil())
}
}
describe("request link") {
var interactor: MockPasswordlessInteractor!
beforeEach {
options.passwordlessMethod = .magicLink
interactor = MockPasswordlessInteractor()
interactor.onLogin = { return nil }
interactor.onRequest = { return nil }
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should trigger action on return of field") {
let input = mockInput(.phone, value: phone)
input.returnKey = .done
interactor.onRequest = { return nil }
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beNil())
}
it("should trigger action on primary button press") {
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beNil())
}
it("should route to link sent screen upon success") {
view.primaryButton!.onPress(view.primaryButton!)
expect(navigator.route).toEventually(equal(Route.passwordless(screen: .linkSent, connection: connection)))
}
it("should show error on failure") {
interactor.onRequest = { return .codeNotSent }
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventuallyNot(beNil())
}
}
}
describe("code auth screen") {
let screen = PasswordlessScreen.code
beforeEach {
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should show code screen") {
expect(presenter.screen) == PasswordlessScreen.code
}
it("should expect code input in form") {
let form = view.form as! SingleInputView
expect(form.type) == InputField.InputType.oneTimePassword
}
it("should expect title on secondary button") {
expect(view.secondaryButton!.title).to(contain("Did not get the code"))
}
describe("input") {
it("should update code") {
let input = mockInput(.oneTimePassword, value: "123456")
view.form?.onValueChange(input)
expect(presenter.interactor.code) == "123456"
expect(presenter.interactor.validCode) == true
}
it("should show field error if code is invalid") {
let input = mockInput(.oneTimePassword, value: "ABC")
view.form?.onValueChange(input)
expect(input.valid) == false
}
}
describe("login") {
var interactor: MockPasswordlessInteractor!
beforeEach {
interactor = MockPasswordlessInteractor()
interactor.onLogin = { return nil }
interactor.onRequest = { return nil }
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should trigger action on return of field") {
messagePresenter.error = CredentialAuthError.couldNotLogin
let input = mockInput(.oneTimePassword, value: "123456")
input.returnKey = .done
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beNil())
}
it("should show no error upon success") {
messagePresenter.error = CredentialAuthError.couldNotLogin
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beNil())
}
it("should show error on failure") {
interactor.onLogin = { return .couldNotLogin }
view.primaryButton!.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventuallyNot(beNil())
}
}
}
describe("link sent screen") {
let screen = PasswordlessScreen.linkSent
beforeEach {
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
presenter.messagePresenter = messagePresenter
view = presenter.view as? PasswordlessView
}
it("should show code screen") {
expect(presenter.screen) == PasswordlessScreen.linkSent
}
it("should expect title on secondary button") {
expect(view.secondaryButton!.title).to(contain("Did not receive the link"))
}
it("should expect title on secondary button if using magic links") {
options.passwordlessMethod = .magicLink
presenter = PasswordlessPresenter(interactor: interactor, connection: connection, navigator: navigator, options: options, screen: screen)
view = presenter.view as? PasswordlessView
expect(view.secondaryButton!.title).to(contain("I have a code"))
}
}
}
}
}
| mit | 021deb7400c78fa0bd00ce3d9179f2c3 | 44.207513 | 205 | 0.524316 | 6.60162 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.