repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zdrzdr/QEDSwift | Pods/Kingfisher/Sources/KingfisherManager.swift | 1 | 10432 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 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.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
public typealias CompletionHandler = ((image: Image?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
/// RetrieveImageTask represents a task of image retrieving process.
/// It contains an async task of getting image from disk and from network.
public class RetrieveImageTask {
// If task is canceled before the download task started (which means the `downloadTask` is nil),
// the download task should not begin.
var cancelledBeforeDownlodStarting: Bool = false
/// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task.
public var diskRetrieveTask: RetrieveImageDiskTask?
/// The network retrieve task in this image task.
public var downloadTask: RetrieveImageDownloadTask?
/**
Cancel current task. If this task does not begin or already done, do nothing.
*/
public func cancel() {
// From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime.
// It fixed in Xcode 7.1.
// See https://github.com/onevcat/Kingfisher/issues/99 for more.
if let diskRetrieveTask = diskRetrieveTask {
dispatch_block_cancel(diskRetrieveTask)
}
if let downloadTask = downloadTask {
downloadTask.cancel()
} else {
cancelledBeforeDownlodStarting = true
}
}
}
/// Error domain of Kingfisher
public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
private let instance = KingfisherManager()
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
/// Shared manager used by the extensions across Kingfisher.
public class var sharedManager: KingfisherManager {
return instance
}
/// Cache used by this manager
public var cache: ImageCache
/// Downloader used by this manager
public var downloader: ImageDownloader
/**
Default init method
- returns: A Kingfisher manager object with default cache and default downloader.
*/
public init() {
cache = ImageCache.defaultCache
downloader = ImageDownloader.defaultDownloader
}
/**
Get an image with resource.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithResource(resource: Resource,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let task = RetrieveImageTask()
if let optionsInfo = optionsInfo where optionsInfo.forceRefresh {
downloadAndCacheImageWithURL(resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: optionsInfo)
} else {
tryToRetrieveImageFromCacheForKey(resource.cacheKey,
withURL: resource.downloadURL,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: optionsInfo)
}
return task
}
/**
Get an image with `URL.absoluteString` as the key.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at URL and cache it with `URL.absoluteString` value as its key.
If you need to specify the key other than `URL.absoluteString`, please use resource version of this API with `resource.cacheKey` set to what you want.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter URL: The image URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithURL(URL: NSURL,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return retrieveImageWithResource(Resource(downloadURL: URL), optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler)
}
func downloadAndCacheImageWithURL(URL: NSURL,
forKey key: String,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?)
{
let downloader = options?.downloader ?? self.downloader
downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options,
progressBlock: { receivedSize, totalSize in
progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
},
completionHandler: { image, error, imageURL, originalData in
let targetCache = options?.targetCache ?? self.cache
if let error = error where error.code == KingfisherError.NotModified.rawValue {
// Not modified. Try to find the image from cache.
// (The image should be in cache. It should be guaranteed by the framework users.)
targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL)
})
return
}
if let image = image, originalData = originalData {
targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: options?.cacheMemoryOnly ?? true, completionHandler: nil)
}
completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
})
}
func tryToRetrieveImageFromCacheForKey(key: String,
withURL URL: NSURL,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?)
{
let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
// Break retain cycle created inside diskTask closure below
retrieveImageTask.diskRetrieveTask = nil
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
let targetCache = options?.targetCache ?? cache
let diskTask = targetCache.retrieveImageForKey(key, options: options,
completionHandler: { image, cacheType in
if image != nil {
diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: URL)
} else {
self.downloadAndCacheImageWithURL(URL,
forKey: key,
retrieveImageTask: retrieveImageTask,
progressBlock: progressBlock,
completionHandler: diskTaskCompletionHandler,
options: options)
}
})
retrieveImageTask.diskRetrieveTask = diskTask
}
}
| mit | 7eed63878e5cb30021fe2a755f4a62fa | 45.571429 | 162 | 0.651265 | 5.697433 | false | false | false | false |
VBVMI/VerseByVerse-iOS | Pods/VimeoNetworking/VimeoNetworking/Sources/NSError+Extensions.swift | 1 | 10763 | //
// NSError+Extensions.swift
// VimemoUpload
//
// Created by Alfred Hanssen on 2/5/16.
// Copyright © 2016 Vimeo. All rights reserved.
//
// 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
import AFNetworking
/// Stores string constants used to look up Vimeo-api-specific error information
public enum VimeoErrorKey: String
{
case VimeoErrorCode = "VimeoLocalErrorCode" // Wish this could just be VimeoErrorCode but it conflicts with server-side key [AH] 2/5/2016
case VimeoErrorDomain = "VimeoErrorDomain"
}
/// Convenience methods used to parse `NSError`s returned by Vimeo api responses
public extension NSError
{
/// Returns true if the error is a 503 Service Unavailable error
public var isServiceUnavailableError: Bool
{
return self.statusCode == HTTPStatusCode.serviceUnavailable.rawValue
}
/// Returns true if the error is due to an invalid access token
public var isInvalidTokenError: Bool
{
if let urlResponse = self.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] as? HTTPURLResponse, urlResponse.statusCode == HTTPStatusCode.unauthorized.rawValue
{
if let header = urlResponse.allHeaderFields["Www-Authenticate"] as? String, header == "Bearer error=\"invalid_token\""
{
return true
}
}
return false
}
/// Returns true if the error is due to the cancellation of a network task
func isNetworkTaskCancellationError() -> Bool
{
return self.domain == NSURLErrorDomain && self.code == NSURLErrorCancelled
}
/// Returns true if the error is a url connection error
func isConnectionError() -> Bool
{
return [NSURLErrorTimedOut,
NSURLErrorCannotFindHost,
NSURLErrorCannotConnectToHost,
NSURLErrorDNSLookupFailed,
NSURLErrorNotConnectedToInternet,
NSURLErrorNetworkConnectionLost].contains(self.code)
}
/**
Generates a new `NSError`
- parameter domain: The domain in which the error was generated
- parameter code: A unique code identifying the error
- parameter description: A developer-readable description of the error
- returns: a new `NSError`
*/
class func error(withDomain domain: String?, code: Int?, description: String?) -> NSError
{
var error = NSError(domain: VimeoErrorKey.VimeoErrorDomain.rawValue, code: 0, userInfo: nil)
if let description = description
{
let userInfo = [NSLocalizedDescriptionKey: description]
error = error.error(byAddingDomain: domain, code: code, userInfo: userInfo)
}
else
{
error = error.error(byAddingDomain: domain, code: code, userInfo: nil)
}
return error
}
/**
Generates a new error with an added domain
- parameter domain: New domain for the error
- returns: An error with additional information in the user info dictionary
*/
func error(byAddingDomain domain: String) -> NSError
{
return self.error(byAddingDomain: domain, code: nil, userInfo: nil)
}
/**
Generates a new error with added user info
- parameter userInfo: the user info dictionary to append to the existing user info
- returns: An error with additional user info
*/
func error(byAddingUserInfo userInfo: [AnyHashable: Any]) -> NSError
{
return self.error(byAddingDomain: nil, code: nil, userInfo: userInfo)
}
/**
Generates a new error with an added error code
- parameter code: the new error code for the error
- returns: An error with additional information in the user info dictionary
*/
func error(byAddingCode code: Int) -> NSError
{
return self.error(byAddingDomain: nil, code: code, userInfo: nil)
}
/**
Generates a new error with added information
- parameter domain: New domain for the error
- parameter code: the new error code for the error
- parameter userInfo: the user info dictionary to append to the existing user info
- returns: An error with additional information in the user info dictionary
*/
func error(byAddingDomain domain: String?, code: Int?, userInfo: [AnyHashable: Any]?) -> NSError
{
var augmentedInfo = self.userInfo
if let domain = domain
{
augmentedInfo[VimeoErrorKey.VimeoErrorDomain.rawValue] = domain
}
if let code = code
{
augmentedInfo[VimeoErrorKey.VimeoErrorCode.rawValue] = code
}
if let userInfo = userInfo
{
augmentedInfo.append(userInfo as! Dictionary<String, Any>)
}
return NSError(domain: self.domain, code: self.code, userInfo: augmentedInfo)
}
// MARK: -
private struct Constants
{
static let VimeoErrorCodeHeaderKey = "Vimeo-Error-Code"
static let VimeoErrorCodeKeyLegacy = "VimeoErrorCode"
static let VimeoErrorCodeKey = "error_code"
static let VimeoInvalidParametersKey = "invalid_parameters"
static let VimeoUserMessageKey = "error"
static let VimeoDeveloperMessageKey = "developer_message"
}
/// Returns the status code of the failing response, if available
public var statusCode: Int?
{
if let response = self.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] as? HTTPURLResponse
{
return response.statusCode
}
return nil
}
/// Returns the api error code of the failing response, if available
public var vimeoServerErrorCode: Int?
{
if let errorCode = (self.userInfo[Constants.VimeoErrorCodeKeyLegacy] as? Int)
{
return errorCode
}
if let response = self.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] as? HTTPURLResponse,
let vimeoErrorCode = response.allHeaderFields[Constants.VimeoErrorCodeHeaderKey] as? String
{
return Int(vimeoErrorCode)
}
if let json = self.errorResponseBodyJSON,
let errorCode = json[Constants.VimeoErrorCodeKey] as? Int
{
return errorCode
}
return nil
}
/// Returns the invalid parameters of the failing response, if available
public var vimeoInvalidParametersErrorCodes: [Int]
{
var errorCodes: [Int] = []
if let json = self.errorResponseBodyJSON, let invalidParameters = json[Constants.VimeoInvalidParametersKey] as? [[AnyHashable: Any]]
{
for invalidParameter in invalidParameters
{
if let code = invalidParameter[Constants.VimeoErrorCodeKey] as? Int
{
errorCodes.append(code)
}
}
}
return errorCodes
}
/// Returns the api error JSON dictionary, if available
public var errorResponseBodyJSON: [AnyHashable: Any]?
{
if let data = self.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data
{
do
{
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [AnyHashable: Any]
return json
}
catch
{
return nil
}
}
return nil
}
/// Returns the first error code from the api error JSON dictionary if it exists, otherwise returns NSNotFound
public var vimeoInvalidParametersFirstErrorCode: Int
{
return self.vimeoInvalidParametersErrorCodes.first ?? NSNotFound
}
/// Returns the user message from the api error JSON dictionary if it exists
public var vimeoInvalidParametersFirstVimeoUserMessage: String?
{
guard let json = self.errorResponseBodyJSON, let invalidParameters = json[Constants.VimeoInvalidParametersKey] as? [AnyObject] else
{
return nil
}
return invalidParameters.first?[Constants.VimeoUserMessageKey] as? String
}
/// Returns an underscore separated string of all the error codes in the the api error JSON dictionary if any exist, otherwise returns nil
public var vimeoInvalidParametersErrorCodesString: String?
{
let errorCodes = self.vimeoInvalidParametersErrorCodes
guard errorCodes.count > 0 else
{
return nil
}
var result = ""
for code in errorCodes
{
result += "\(code)_"
}
return result.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
}
/// Returns the "error" key from the api error JSON dictionary if it exists, otherwise returns nil
public var vimeoUserMessage: String?
{
guard let json = self.errorResponseBodyJSON else
{
return nil
}
return json[Constants.VimeoUserMessageKey] as? String
}
/// Returns the "developer_message" key from the api error JSON dictionary if it exists, otherwise returns nil
public var vimeoDeveloperMessage: String?
{
guard let json = self.errorResponseBodyJSON else
{
return nil
}
return json[Constants.VimeoDeveloperMessageKey] as? String
}
}
| mit | 1eae57e29caa1ec5731ef83989cdf304 | 33.383387 | 175 | 0.635477 | 5.20658 | false | false | false | false |
blitzagency/ParsedObject | Source/ParsedObject+Operators.swift | 1 | 2890 | //
// ParsedObject+Operators.swift
// FrameworkTest
//
// Created by Adam Venturella on 11/5/14.
// Copyright (c) 2014 BLITZ. All rights reserved.
//
import Foundation
//MARK: - Comparable
extension ParsedObject: Comparable {}
public func ==(lhs: ParsedObject, rhs: ParsedObject) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as NSNumber) == (rhs.object as NSNumber)
case (.String, .String):
return (lhs.object as String) == (rhs.object as String)
case (.Bool, .Bool):
return (lhs.object as Bool) == (rhs.object as Bool)
case (.Array, .Array):
return (lhs.object as NSArray) == (rhs.object as NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as NSDictionary) == (rhs.object as NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: ParsedObject, rhs: ParsedObject) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as NSNumber) <= (rhs.object as NSNumber)
case (.String, .String):
return (lhs.object as String) <= (rhs.object as String)
case (.Bool, .Bool):
return (lhs.object as Bool) == (rhs.object as Bool)
case (.Array, .Array):
return (lhs.object as NSArray) == (rhs.object as NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as NSDictionary) == (rhs.object as NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: ParsedObject, rhs: ParsedObject) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as NSNumber) >= (rhs.object as NSNumber)
case (.String, .String):
return (lhs.object as String) >= (rhs.object as String)
case (.Bool, .Bool):
return (lhs.object as Bool) == (rhs.object as Bool)
case (.Array, .Array):
return (lhs.object as NSArray) == (rhs.object as NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as NSDictionary) == (rhs.object as NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: ParsedObject, rhs: ParsedObject) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as NSNumber) > (rhs.object as NSNumber)
case (.String, .String):
return (lhs.object as String) > (rhs.object as String)
default:
return false
}
}
public func <(lhs: ParsedObject, rhs: ParsedObject) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as NSNumber) < (rhs.object as NSNumber)
case (.String, .String):
return (lhs.object as String) < (rhs.object as String)
default:
return false
}
}
| mit | be0798ec3e1c81419d6a329fd9c99466 | 29.104167 | 75 | 0.609689 | 3.719434 | false | false | false | false |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModel/Public/Default Dependency Implementations/UserDefaultsForceRefreshRequired.swift | 1 | 936 | import Foundation
public struct UserDefaultsForceRefreshRequired: ForceRefreshRequired {
private struct Keys {
static let lastWitnessedAppVersionKey = "EFLastOpenedAppVersion"
}
var userDefaults: UserDefaults = .standard
var versionProviding: AppVersionProviding = BundleAppVersionProviding.shared
public init(userDefaults: UserDefaults = .standard, versionProviding: AppVersionProviding = BundleAppVersionProviding.shared) {
self.userDefaults = userDefaults
self.versionProviding = versionProviding
}
public var isForceRefreshRequired: Bool {
let forceRefreshRequired = userDefaults.string(forKey: Keys.lastWitnessedAppVersionKey) != versionProviding.version
userDefaults.set(versionProviding.version, forKey: Keys.lastWitnessedAppVersionKey)
return forceRefreshRequired
}
public func markForceRefreshNoLongerRequired() {
}
}
| mit | eec1b3b893272151b857200db711e920 | 32.428571 | 131 | 0.755342 | 5.638554 | false | false | false | false |
markohlebar/Fontana | Spreadit/View/VideoViewController.swift | 1 | 3954 | //
// VideoViewController.swift
// Spreadit
//
// Created by Marko Hlebar on 24/01/2016.
// Copyright © 2016 Marko Hlebar. All rights reserved.
//
import UIKit
import BIND
import MediaPlayer
class VideoViewController: BNDViewController {
@IBOutlet weak var videoContainerView: UIView!
lazy var moviePlayerController: MPMoviePlayerController = {
let moviePlayerController = MPMoviePlayerController()
self.videoContainerView.addSubview(moviePlayerController.view)
moviePlayerController.repeatMode = .One
moviePlayerController.backgroundView.backgroundColor = UIColor.whiteColor()
moviePlayerController.controlStyle = .None
moviePlayerController.view.hidden = true
let movieView = moviePlayerController.view
movieView.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[movieView]-0-|",
options: .DirectionLeadingToTrailing,
metrics: nil,
views: ["movieView": movieView])
self.videoContainerView.addConstraints(horizontalConstraints)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[movieView]-0-|",
options: .DirectionLeadingToTrailing,
metrics: nil,
views: ["movieView": movieView])
self.videoContainerView.addConstraints(verticalConstraints)
return moviePlayerController
}()
lazy var segmentedControl: UISegmentedControl = {
let segmentedControl = UISegmentedControl(items: ["Installation", "Usage"])
segmentedControl.addTarget(self, action: "onSegmentedControl:", forControlEvents: .ValueChanged)
return segmentedControl
}()
lazy var videoNames : [String] = {
return ["enabling_keyboard_720", "using_keyboard_720"]
}()
var selectedIndex: Int? {
didSet {
if selectedIndex != NSNotFound {
self.segmentedControl.selectedSegmentIndex = selectedIndex!
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.selectedIndex = NSNotFound
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "moviePlayerStateDidChange:",
name: MPMovieNaturalSizeAvailableNotification,
object: nil)
}
func moviePlayerStateDidChange(notification: NSNotification) {
self.moviePlayerController.view.hidden = false
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.titleView = self.segmentedControl
if self.selectedIndex == NSNotFound {
self.selectedIndex = 0
}
}
override func viewWillAppear(animated: Bool) {
self.onSegmentedControl(self.segmentedControl)
}
override func viewWillDisappear(animated: Bool) {
self.moviePlayerController.stop()
}
func onSegmentedControl(control : UISegmentedControl) {
let videoName = self.videoNames[control.selectedSegmentIndex]
self.playVideoNamed(videoName)
let screenName = "Video \(videoName)"
FNTAppTracker.trackEvent(FNTAppTrackerScreenViewEvent, withTags: [FNTAppTrackerScreenNameTag : screenName])
}
func playVideoNamed(name: String) {
if let videoURL = NSBundle.mainBundle().URLForResource(name, withExtension: "mov") {
playVideo(videoURL)
}
}
func playVideo(videoURL: NSURL) {
self.moviePlayerController.contentURL = videoURL
self.moviePlayerController.prepareToPlay()
self.moviePlayerController.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| agpl-3.0 | c1c0521dcf611f15cf9e2b85597b3dc7 | 33.077586 | 115 | 0.66557 | 5.728986 | false | false | false | false |
mb2dev/BarnaBot | Barnabot/BBIntentDialog.swift | 1 | 1627 | //
// BBIntentDialog.swift
// BarnaBotSample
//
// Created by Mickael Bordage on 10/02/2017.
// Copyright © 2017 Mickael Bordage. All rights reserved.
//
import Foundation
class BBIntentDialog : BBDialog {
var priority:Int
// Pour pouvoir faire des comparaisons entre plusieurs instances de BBIntentDialog
let regex : NSRegularExpression
convenience init(_ regex : NSRegularExpression, priority:Int){
self.init(regex, waterfall : [], priority: priority)
}
convenience init(_ regex : NSRegularExpression, redir : String, priority:Int){
let waterfall : [BBNext] = [{(session : BBSession) -> Void in
session.beginDialog(path: redir)
}]
self.init(regex, waterfall : waterfall, priority: priority)
}
convenience init(_ regex : NSRegularExpression, action: @escaping BBNext, priority:Int){
var waterfall : [BBNext] = [BBNext]()
waterfall.append(action)
self.init(regex, waterfall : waterfall, priority: priority)
}
init(_ regex : NSRegularExpression, waterfall: [BBNext], priority:Int){
self.priority = priority
self.regex = regex
super.init(regex.pattern, waterfall: waterfall)
}
override public var description: String{
var result = ""
result.append("BBIntentDialog \n")
result.append("- steps : \(self.waterfall.count)")
result.append("- priority : \(self.priority)")
return result
}
override func copy() -> BBDialog {
return BBIntentDialog(regex, waterfall : waterfall, priority: 0)
}
}
| bsd-3-clause | e1fd1998a7a94203bddfd49eb75117a2 | 30.882353 | 92 | 0.640221 | 4.116456 | false | false | false | false |
dekatotoro/FluxWithRxSwiftSample | FluxWithRxSwiftSample/Controllers/SearchUser/DataSources/SearchUserTableViewDataSource.swift | 1 | 2027 | //
// SearchUserTableViewDataSource.swift
// FluxWithRxSwiftSample
//
// Created by Yuji Hato on 2016/10/13.
// Copyright © 2016年 dekatotoro. All rights reserved.
//
import UIKit
import RxSwift
class SearchUserTableViewDataSource: NSObject {
weak var tableView: UITableView?
let users = Variable<[GitHubUser]>([])
fileprivate let store: SearchUserStore = .shared
func register(tableView: UITableView) {
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
tableView.registerCell(cell: SearchUserCell.self)
self.tableView = tableView
observeStore()
}
private func observeStore() {
store.rx.searchUser.asObservable()
.map { $0.elements }
.subscribe(onNext: { [unowned self] elements in
self.users.value = elements
self.tableView?.reloadData()
})
.addDisposableTo(rx_disposeBag)
}
}
extension SearchUserTableViewDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(type: SearchUserCell.self)
cell.configure(user: users.value[indexPath.row])
return cell
}
}
extension SearchUserTableViewDataSource: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.5
}
}
extension SearchUserTableViewDataSource: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
SearchUserAction.scrollViewDidEndDragging(decelerate: decelerate)
}
}
| mit | 98188672de8d31556caae606e9ad4fa5 | 27.914286 | 100 | 0.668972 | 5.284595 | false | false | false | false |
seedante/ControlPanelAnimation | Control-Panel-Interactive-Animation/InteractiveAnimation/ViewController.swift | 1 | 4732 | //
// ViewController.swift
// InteractiveAnimation
//
// Created by seedante on 16/6/14.
// Copyright © 2016年 seedante. All rights reserved.
//
import UIKit
/**
Continue the topic "Interactive Animations" in https://www.objc.io/issues/12-animations/interactive-animations/ ,
use UIView Animation/Core Animation to implement control panel open/close animation, which is interactive, interruptible, smooth.
*/
class ViewController: UIViewController {
var pan = UIPanGestureRecognizer()
var tap = UITapGestureRecognizer()
var panelView = UIView()
var panelOpened = true
///0.5s is too short for interaction, you could set it longer for test.
let duration: TimeInterval = 0.5
let relayDuration: TimeInterval = 0.3
let diff: CGFloat = 150
var USE_COREANIMATION = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
panelView.frame = view.bounds
panelView.center.y = view.center.y * (3 - 0.5)
panelView.backgroundColor = UIColor.gray
panelView.layer.cornerRadius = 5
view.addSubview(panelView)
pan.addTarget(self, action: #selector(ViewController.handlePan(_:)))
panelView.addGestureRecognizer(pan)
tap.addTarget(self, action: #selector(ViewController.handleTap(_:)))
panelView.addGestureRecognizer(tap)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func stopMoveAnimation(){
let currentPosition = (panelView.layer.presentation() as! CALayer).position
panelView.layer.removeAllAnimations()
panelView.layer.position = currentPosition
}
func handlePan(_ panGesture: UIPanGestureRecognizer){
switch panGesture.state {
case .began:
stopMoveAnimation()
case .changed:
let point = panGesture.translation(in: view)
panelView.center = CGPoint(x: panelView.center.x, y: panelView.center.y + point.y)
panGesture.setTranslation(CGPoint.zero, in: view)
case .ended, .cancelled:
let gestureVelocity = panGesture.velocity(in: view)
let isUp = gestureVelocity.y < 0 ? true : false
let targetY = isUp ? view.center.y + diff : view.center.y * 2.5
let velocity = abs(gestureVelocity.y) / abs(panelView.center.y - targetY)
// Relay leave speed. You should provide .AllowUserInteraction option otherwise your touch can't interact with moving view.
UIView.animate(withDuration: relayDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: velocity, options: .allowUserInteraction, animations: {
self.panelView.center.y = targetY
}, completion: nil)
self.panelOpened = isUp ? false : true
default:break
}
}
func handleTap(_ geture: UITapGestureRecognizer){
switch geture.state {
case .ended, .cancelled:
let targetY = panelOpened ? view.center.y + diff : view.center.y * 2.5
if USE_COREANIMATION{
let openOrcloseAni = CABasicAnimation(keyPath: "position.y")
openOrcloseAni.isAdditive = true
openOrcloseAni.duration = duration
openOrcloseAni.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// When Core Animation is additive, scope of animation atteched to presentationLayer is: modelLayer + fromValue ~ modelLayer + toValue.
openOrcloseAni.fromValue = panelView.center.y - targetY
openOrcloseAni.toValue = 0
if panelOpened{
panelView.layer.add(openOrcloseAni, forKey: "close")
}else{
panelView.layer.add(openOrcloseAni, forKey: "open")
}
panelView.center.y = targetY
}else{
// UIView Animation is additive since iOS 8. You should provide AllowUserInteraction option otherwise your touch can't interact with moving view.
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 2, options: .allowUserInteraction, animations: {
self.panelView.center.y = targetY
}, completion: nil)
}
panelOpened = !panelOpened
default:break
}
}
}
| mit | fb04b502c3f2761302f293b05071bc30 | 40.482456 | 173 | 0.636287 | 4.82551 | false | false | false | false |
FantasyWei/FWScrollImageView | FWScrollImageView/FWScrollImageView/ViewController.swift | 1 | 1013 | //
// ViewController.swift
// FWScrollImageView
//
// Created by FantasyWei on 2017/3/16.
// Copyright © 2017年 FantasyWei. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scrollView = FWScrollImageView()
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
make.top.equalTo(64)
make.leading.trailing.equalTo(view)
make.height.equalTo(200)
}
let urlString = "http://qt.qq.com/static/pages/news/phone/c13_list_1.shtml?plat=android&version=9709"
scrollView.sendHttpRequest(method: .GET,urlString: urlString, parameters: nil,interval: 2)
// 点击图片的回调
scrollView.callBack = { (index:Int,model:FWScrollModel)-> Void in
print("当前点击的是第\(index+1)张图片,模型是\(model)")
}
}
}
| mit | 7d900bc245a0326f6e07709d817bc28c | 25.944444 | 110 | 0.613402 | 3.97541 | false | false | false | false |
SwifterLC/SinaWeibo | LCSinaWeibo/LCSinaWeibo/Classes/View/Home/PullToRefresh/LCRefreshControl.swift | 1 | 4522 | //
// LCRefreshControl.swift
// 下拉刷新与上拉刷新
//
// Created by 刘成 on 2017/8/13.
// Copyright © 2017年 刘成. All rights reserved.
//
import UIKit
import SnapKit
let kLCRefreshControlHeight:CGFloat = -60
fileprivate let kLCRefreshControlAnimationKey = "kLCRefreshControlAnimationKey"
class LCRefreshControl: UIRefreshControl {
// MARK: - 懒加载控件
/// 刷新视图
lazy var refreshView = LCRefreshView.loadRefreshView()
// MARK: - 设置 界面
/// 设置 UI
fileprivate func setupUI(){
//1> 添加子控件
addSubview(refreshView)
//2> 设置自动布局
refreshView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(self.refreshView.bounds.size)
}
//3> 监听事件
//属性观察
DispatchQueue.main.async {
self.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if isRefreshing {
refreshView.startAnimate()
return
}
let minY = frame.minY
if minY > 0 {
return
}
if minY < kLCRefreshControlHeight && !refreshView.flag{
refreshView.flag = true
}else if minY >= kLCRefreshControlHeight && refreshView.flag{
refreshView.flag = false
}
}
override func endRefreshing() {
super.endRefreshing()
refreshView.stopAnimate()
}
/// 重写开始刷新方法,在刷新方法调用时加载动画
override func beginRefreshing() {
super.beginRefreshing()
refreshView.startAnimate()
}
deinit {
//移除属性观察
removeObserver(self, forKeyPath: "frame")
}
override init() {
super.init()
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
}
/// 下拉刷新视图,处理视图动画效果
class LCRefreshView: UIView {
/// 下拉刷新箭头旋转方向标志,false 为不旋转原生样式,true 为旋转180样式
var flag = false{
didSet{
rotate()
}
}
/**
* 下拉刷新提示视图,在刷新过程中隐藏
*/
@IBOutlet weak var refreshSuperView: UIView!
/**
* 下拉刷新提示文本,提示用户下拉刷新
*/
@IBOutlet weak var refreshPrompt: UILabel!
/**
* 下拉刷新箭头图标,监听 UIRefreshControl frame 的变化改变箭头的方向
*/
@IBOutlet weak var refreshView: UIImageView!
/**
* 刷新过程提示文本,提示用户正在刷新
*/
@IBOutlet weak var loadPrompt: UILabel!
/**
* 刷新过程中显示活动的图标,不断旋转,告诉用户正在刷新
*/
@IBOutlet weak var loadView: UIImageView!
/// 从 XIb 中加载视图对象
///
/// - Returns: 视图对象
class func loadRefreshView()->LCRefreshView{
return UINib(nibName: "LCRefreshView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! LCRefreshView
}
}
// MARK: - 界面动画
extension LCRefreshView{
/// 旋转动画特点,顺时针优先,就近原则
func rotate(){
UIView.animate(withDuration: 0.25, animations: {
let angle = CGFloat.pi + CGFloat(!self.flag ? 0.000001:-0.000001)
self.refreshView.transform = self.refreshView.transform.rotated(by: angle)
})
}
/// 刷新过程,开始动画
func startAnimate() {
//判断动画是否存在
if refreshSuperView.layer.animation(forKey: kLCRefreshControlAnimationKey) != nil{
print("动画已经存在")
return
}
//隐藏下拉提示视图
refreshSuperView.isHidden = true
let baseAnimation = CABasicAnimation(keyPath: "transform.rotation")
baseAnimation.byValue = 2 * CGFloat.pi
baseAnimation.duration = 0.5
//避免切换 tabBar时动画停止
baseAnimation.isRemovedOnCompletion = false
baseAnimation.repeatCount = MAXFLOAT
loadView.layer.add(baseAnimation, forKey: kLCRefreshControlAnimationKey)
}
/// 刷新过程,结束动画
func stopAnimate() {
refreshSuperView.isHidden = false
loadView.layer.removeAllAnimations()
}
}
| mit | 3d889a6b9d05ea8d9c48ee2af71cddef | 27.453237 | 151 | 0.609355 | 4.266451 | false | false | false | false |
Infinisil/ScriptKit | Source/Console.swift | 1 | 2647 | //
// Console.swift
// ScriptKit
//
// Created by Silvan Mosberger on 21/07/16.
//
//
import Foundation
class Console {
let task : Process
let inHandle : FileHandle
static let sharedBash : Console = {
do {
return try Console(shell: "bash")
} catch {
fatalError("Couldn't find bash with /usr/bin/which, standard location should be /bin/bash, error: \(error)")
}
}()
enum WhichError : Error {
case error(standardError: String)
}
static func which(_ command: String) throws -> String? {
let task = Process()
let (o, e) = (Pipe(), Pipe())
task.standardInput = Pipe()
task.standardOutput = o
task.standardError = e
task.environment = ["PATH" : "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"]
task.launchPath = "/usr/bin/which"
task.arguments = [command]
task.launch()
task.waitUntilExit()
if let error = String(data: e.fileHandleForReading.availableData, encoding: .utf8) , !error.isEmpty {
throw WhichError.error(standardError: error)
}
if let out = String(data: o.fileHandleForReading.availableData, encoding: .utf8) , !out.isEmpty {
return out.trimmingCharacters(in: .newlines)
}
return nil
}
init(shell: String = "bash") throws {
task = Process()
guard let path = try Console.which(shell) else {
fatalError("Shell \"\(shell)\" not found with /usr/bin/which")
}
task.launchPath = path
let input = Pipe()
task.standardInput = input
inHandle = input.fileHandleForWriting
let output = Pipe()
task.standardOutput = output
output.fileHandleForReading.readabilityHandler = { h in
if let string = String(data: h.availableData, encoding: .utf8) {
print(string, terminator: "")
}
}
task.launch()
}
var running : Bool {
return task.isRunning
}
let newLine = "\n".data(using: .utf8)!
func input(_ line: String) {
if let data = line.data(using: .utf8) {
inHandle.write(data)
inHandle.write(newLine)
} else {
print("Couldn't write")
}
}
func wait(_ max: TimeInterval = Double.infinity) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + max) {
self.task.terminate()
}
task.waitUntilExit()
}
}
| mit | 6818d6530028edb41cef73d2edcddd41 | 26.28866 | 120 | 0.540612 | 4.441275 | false | false | false | false |
gmoral/SwiftTraining2016 | Training_Swift/LeftViewController.swift | 1 | 4118 | //
// SidePanelViewController.swift
// Training_Swift
//
// Created by Guillermo Moral on 2/16/16.
// Copyright © 2016 Guillermo Moral. All rights reserved.
//
import UIKit
enum LeftMenu: Int
{
case Profile = 0
case MySkill
case AllSkill
case Logout
}
protocol LeftMenuProtocol : class
{
func changeViewController(menu: LeftMenu)
}
class LeftViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, LeftMenuProtocol
{
@IBOutlet weak var tableView: UITableView!
private var data: NSMutableArray = [NSLocalizedString("Home", comment:""), NSLocalizedString("My Skills", comment:""), NSLocalizedString("All Skills", comment:""), NSLocalizedString("Logout", comment:"")]
var delegate: LeftMenuProtocol?
var mainViewController: UIViewController!
var mySkillViewController: UIViewController!
var allSkillViewController: UIViewController!
// MARK: - Constructor
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
// MARK: - UI
override func viewDidLoad()
{
super.viewDidLoad()
tableView.delegate = self;
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.scrollEnabled = false
let aMainViewController = ProfileViewController.instantiate() as! ProfileViewController
mainViewController = UINavigationController(rootViewController: aMainViewController)
let aMySkillViewController = MySkillViewController.instantiate() as! MySkillViewController
mySkillViewController = UINavigationController(rootViewController: aMySkillViewController)
let aAllSkillViewController = AllSkillViewController.instantiate() as! AllSkillViewController
allSkillViewController = UINavigationController(rootViewController: aAllSkillViewController)
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
tableView.reloadData()
}
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: OptionCell = tableView.dequeueReusableCellWithIdentifier(OptionCell.identifier()) as! OptionCell
cell.optionLabel.text = self.data .objectAtIndex(indexPath.row) as? String
cell.selectionStyle = UITableViewCellSelectionStyle.Blue
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if let menu = LeftMenu(rawValue: indexPath.item)
{
changeViewController(menu)
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 60.0
}
// MARK: - Setup
class func instantiate()->UIViewController
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LeftViewController")
return vc
}
func changeViewController(menu: LeftMenu)
{
switch menu
{
case .Profile:
slideMenuController()?.changeMainViewController(mainViewController, close: true)
case .MySkill:
slideMenuController()?.changeMainViewController(mySkillViewController, close: true)
case .AllSkill:
slideMenuController()?.changeMainViewController(allSkillViewController, close: true)
case .Logout:
let window = UIApplication.sharedApplication().keyWindow
window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0)
window?.rootViewController = LoginViewController.instantiate()
window?.makeKeyAndVisible()
}
}
} | mit | 5c3806563827eb93be6bf383beb609aa | 30.922481 | 208 | 0.670148 | 5.678621 | false | false | false | false |
mapsme/omim | iphone/Maps/Core/Theme/Renderers/CheckmarkRenderer.swift | 5 | 605 | import Foundation
extension Checkmark {
@objc override func applyTheme() {
if styleName.isEmpty {
styleName = "Checkmark"
}
for style in StyleManager.shared.getStyle(styleName)
where !style.isEmpty && !style.hasExclusion(view: self) {
CheckmarkRenderer.render(self, style: style)
}
}
}
class CheckmarkRenderer {
class func render(_ control: Checkmark, style: Style) {
if let onTintColor = style.onTintColor {
control.onTintColor = onTintColor
}
if let offTintColor = style.offTintColor {
control.offTintColor = offTintColor
}
}
}
| apache-2.0 | 7c80ac1558308b8a0d4ec845dbaac7a4 | 23.2 | 63 | 0.676033 | 4.29078 | false | false | false | false |
KrishMunot/swift | test/decl/func/throwing_functions.swift | 3 | 5534 | // RUN: %target-parse-verify-swift
enum Exception : ErrorProtocol { case A }
// Basic syntax ///////////////////////////////////////////////////////////////
func bar() throws -> Int { return 0 }
func foo() -> Int { return 0 }
// Currying ///////////////////////////////////////////////////////////////////
func curry1() {
}
func curry1Throws() throws {
}
func curry2() -> () -> () {
return curry1
}
func curry2Throws() throws -> () -> () {
return curry1
}
func curry3() -> () throws -> () {
return curry1Throws
}
func curry3Throws() throws -> () throws -> () {
return curry1Throws
}
var a : () -> () -> () = curry2
var b : () throws -> () -> () = curry2Throws
var c : () -> () throws -> () = curry3
var d : () throws -> () throws -> () = curry3Throws
// Partial application ////////////////////////////////////////////////////////
protocol Parallelogram {
static func partialApply1(_ a: Int) throws
}
func partialApply2<T: Parallelogram>(_ t: T) {
_ = T.partialApply1
}
// Overload resolution/////////////////////////////////////////////////////////
func barG<T>(_ t : T) throws -> T { return t }
func fooG<T>(_ t : T) -> T { return t }
var bGE: (i: Int) -> Int = barG // expected-error{{invalid conversion from throwing function of type '(_) throws -> _' to non-throwing function type '(i: Int) -> Int'}}
var bg: (i: Int) throws -> Int = barG
var fG: (i: Int) throws -> Int = fooG
func fred(_ callback: (UInt8) throws -> ()) throws { }
func rachel() -> Int { return 12 }
func donna(_ generator: () throws -> Int) -> Int { return generator() } // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}}
donna(rachel)
func barT() throws -> Int { return 0 } // expected-note{{}}
func barT() -> Int { return 0 } // expected-error{{invalid redeclaration of 'barT()'}}
func fooT(_ callback: () throws -> Bool) {} //OK
func fooT(_ callback: () -> Bool) {}
// Throwing and non-throwing types are not equivalent.
struct X<T> { }
func specializedOnFuncType1(_ x: X<String throws -> Int>) { }
func specializedOnFuncType2(_ x: X<String -> Int>) { }
func testSpecializedOnFuncType(_ xThrows: X<String throws -> Int>,
xNonThrows: X<String -> Int>) {
specializedOnFuncType1(xThrows) // ok
specializedOnFuncType1(xNonThrows) // expected-error{{cannot convert value of type 'X<String -> Int>' to expected argument type 'X<String throws -> Int>'}}
specializedOnFuncType2(xThrows) // expected-error{{cannot convert value of type 'X<String throws -> Int>' to expected argument type 'X<String -> Int>'}}
specializedOnFuncType2(xNonThrows) // ok
}
// Subtyping
func subtypeResult1(_ x: String -> (Int -> String)) { }
func testSubtypeResult1(_ x1: String -> (Int throws -> String),
x2: String -> (Int -> String)) {
subtypeResult1(x1) // expected-error{{cannot convert value of type 'String -> (Int throws -> String)' to expected argument type 'String -> (Int -> String)'}}
subtypeResult1(x2)
}
func subtypeResult2(_ x: String -> (Int throws -> String)) { }
func testSubtypeResult2(_ x1: String -> (Int throws -> String),
x2: String -> (Int -> String)) {
subtypeResult2(x1)
subtypeResult2(x2)
}
func subtypeArgument1(_ x: (fn: (String -> Int)) -> Int) { }
func testSubtypeArgument1(_ x1: (fn: (String -> Int)) -> Int,
x2: (fn: (String throws -> Int)) -> Int) {
subtypeArgument1(x1)
subtypeArgument1(x2)
}
func subtypeArgument2(_ x: (fn: (String throws -> Int)) -> Int) { }
func testSubtypeArgument2(_ x1: (fn: (String -> Int)) -> Int,
x2: (fn: (String throws -> Int)) -> Int) {
subtypeArgument2(x1) // expected-error{{cannot convert value of type '(fn: (String -> Int)) -> Int' to expected argument type '(fn: (String throws -> Int)) -> Int'}}
subtypeArgument2(x2)
}
// Closures
var c1 = {() throws -> Int in 0}
var c2 : () throws -> Int = c1 // ok
var c3 : () -> Int = c1 // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c4 : () -> Int = {() throws -> Int in 0} // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c5 : () -> Int = { try c2() } // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c6 : () throws -> Int = { do { try c2() } ; return 0 }
var c7 : () -> Int = { do { try c2() } ; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c8 : () -> Int = { do { try c2() } catch _ { var x = 0 } ; return 0 }
var c9 : () -> Int = { do { try c2() } catch Exception.A { var x = 0 } ; return 0 }// expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c10 : () -> Int = { throw Exception.A; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c11 : () -> Int = { try! c2() }
var c12 : () -> Int? = { try? c2() }
// Initializers
struct A {
init(doomed: ()) throws {}
}
func fi1() throws {
A(doomed: ()) // expected-error {{call can throw but is not marked with 'try'}} // expected-warning{{unused}}
}
struct B {
init() throws {}
init(foo: Int) {}
}
B(foo: 0) // expected-warning{{unused}}
| apache-2.0 | 8fce25785e693f9d81d4e77c501d105e | 38.528571 | 213 | 0.585472 | 3.542894 | false | false | false | false |
swift-gtk/SwiftGTK | example/main.swift | 1 | 4076 | //
// main.swift
// example
//
// Created by Artur Gurgul on 07/02/2017.
//
//
enum General:Error {
case CantStartApp
}
class FirstApplication: Application {
var buttonBox:ButtonBox!
var label: Label!
var pressMeButton: Button!
var calendarButton: Button!
var imageButton: Button!
var textView: TextView!
let socket: Socket
let inet: InetAddress
let address: SocketAddress
init() {
guard let socket = Socket(family: .ipv4, type: .stream, protocol: .tcp) else {
//throw General.CantStartApp
fatalError("Can't start the app")
}
self.socket = socket
socket.blocking = false
inet = InetAddress(string: "127.0.0.1")
address = SocketAddress(inet: inet, port: 8866)
super.init(applicationId: "simple.example")
}
func imageButtonClicked(button: Button, args: UnsafeMutableRawPointer...) {
let newWindow = Window(windowType: .topLevel)
newWindow.title = "Just a window"
newWindow.defaultSize = Size(width: 200, height: 200)
let image = Image(filename: "GTK.png")
newWindow.add(image)
newWindow.showAll()
}
func pressMeClicked(button: Button, args: UnsafeMutableRawPointer...) {
label.text = "Oh, you pressed the button."
let newWindow = Window(windowType: .topLevel)
newWindow.title = "Just a window"
newWindow.defaultSize = Size(width: 200, height: 200)
let labelPressed = Label(text: "Oh, you pressed the button.")
newWindow.add(labelPressed)
newWindow.showAll()
}
func callendarButtonClicked(button: Button, args: UnsafeMutableRawPointer...) {
let newWindow = Window(windowType: .topLevel)
newWindow.title = "Just a window"
newWindow.defaultSize = Size(width: 200, height: 200)
let calendar = Calendar()
calendar.year = 2000
calendar.showHeading = true
newWindow.add(calendar)
newWindow.showAll()
}
func startApp() {
_ = run(startApplicationWindow)
}
func startApplicationWindow(applicationWindow: ApplicationWindow) {
buttonBox = ButtonBox(orientation: .vertical)
label = Label()
label.selectable = true
buttonBox.add(label)
pressMeButton = Button(label: "Press")
pressMeButton.label = "Press Me"
pressMeButton.connect(.clicked, callback: pressMeClicked)
buttonBox.add(pressMeButton)
calendarButton = Button(label: "Calendar")
calendarButton.connect(.clicked, callback: callendarButtonClicked)
buttonBox.add(calendarButton)
imageButton = Button(label: "Image")
imageButton.connect(.clicked, callback: imageButtonClicked)
buttonBox.add(imageButton)
textView = TextView()
textView.buffer.text = "This is some text inside of a Gtk.TextView. " +
"Select text and click one of the buttons 'bold', 'italic', " +
"or 'underline' to modify the text accordingly."
buttonBox.add(textView)
applicationWindow.title = "Hello World"
applicationWindow.defaultSize = Size(width: 400, height: 400)
applicationWindow.resizable = true
applicationWindow.add(buttonBox)
}
func newConnection(socket: Socket) {
print("new connection")
}
func startServer() {
do {
try socket.bind(address: address, allowReuse: false)
try socket.listen()
socket.loop(callback: newConnection)
} catch SocketError.cantBind(let message) {
print(message)
} catch SocketError.cantListen(let message) {
print(message)
} catch {
print("unknown error")
}
}
}
_ = FirstApplication().startApp()
| gpl-2.0 | d267e70c5ec7d47c95870e5c6205b597 | 27.704225 | 86 | 0.591021 | 4.668958 | false | false | false | false |
Ghosty141/MenuBarControls | MenuBarControls/SettingsWindowController.swift | 1 | 1584 | //
// SettingsWindowController.swift
// MenuBarControls
//
// Copyright © 2017 Ghostly. All rights reserved.
//
import Cocoa
class SettingsWindowController: NSWindowController, NSWindowDelegate {
var visibleTab: NSViewController?
@IBAction func general(_ sender: NSToolbarItem) {
visibleTab = NSStoryboard(
name: NSStoryboard.Name(rawValue: "Main"),
bundle: nil)
.instantiateController(
withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "General")) as? NSViewController
window?.contentView = visibleTab?.view
}
@IBAction func coverArt(_ sender: NSToolbarItem) {
visibleTab = NSStoryboard(
name: NSStoryboard.Name(rawValue: "Main"),
bundle: nil)
.instantiateController(
withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "CoverArt")) as? NSViewController
window?.contentView = visibleTab?.view
}
@IBAction func about(_ sender: NSToolbarItem) {
visibleTab = NSStoryboard(
name: NSStoryboard.Name(rawValue: "Main"),
bundle: nil)
.instantiateController(
withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "About")) as? NSViewController
window?.contentView = visibleTab?.view
}
@IBAction func quit(_ sender: NSToolbarItem) {
NSApplication.shared.terminate(self)
}
override func windowDidLoad() {
window?.level = NSWindow.Level(rawValue: NSWindow.Level.RawValue(kCGFloatingWindowLevel))
}
}
| gpl-3.0 | 7269fa98aab93d8d564cab7299b473d4 | 31.306122 | 104 | 0.650663 | 5.276667 | false | false | false | false |
khizkhiz/swift | test/Interpreter/builtin_bridge_object.swift | 2 | 4877 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -parse-stdlib %s -o %t/a.out
// RUN: %target-run %t/a.out | FileCheck %s
// REQUIRES: executable_test
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Swift
import SwiftShims
class C {
deinit { print("deallocated") }
}
#if arch(i386) || arch(arm)
// We have no ObjC tagged pointers, and two low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0003
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#elseif arch(x86_64)
// We have ObjC tagged pointers in the lowest and highest bit
let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0006
let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0001
#elseif arch(arm64)
// We have ObjC tagged pointers in the highest bit
let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0000
#elseif arch(powerpc64) || arch(powerpc64le)
// We have no ObjC tagged pointers, and three low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#endif
func bitPattern(x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
func nonPointerBits(x: Builtin.BridgeObject) -> UInt {
return bitPattern(x) & NATIVE_SPARE_BITS
}
// Try without any bits set.
if true {
let x = C()
let bo = Builtin.castToBridgeObject(x, 0._builtinWordValue)
let bo2 = bo
let x1: C = Builtin.castReferenceFromBridgeObject(bo)
let x2: C = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
print(nonPointerBits(bo) == 0)
// CHECK-NEXT: true
var bo3 = Builtin.castToBridgeObject(C(), 0._builtinWordValue)
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: true
let bo4 = bo3
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
_fixLifetime(bo4)
}
// CHECK-NEXT: deallocated
// CHECK-NEXT: deallocated
// Try with all spare bits set.
if true {
let x = C()
let bo = Builtin.castToBridgeObject(x, NATIVE_SPARE_BITS._builtinWordValue)
let bo2 = bo
let x1: C = Builtin.castReferenceFromBridgeObject(bo)
let x2: C = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
print(nonPointerBits(bo) == NATIVE_SPARE_BITS)
// CHECK-NEXT: true
var bo3 = Builtin.castToBridgeObject(C(), NATIVE_SPARE_BITS._builtinWordValue)
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: true
let bo4 = bo3
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
_fixLifetime(bo4)
}
// CHECK-NEXT: deallocated
// CHECK-NEXT: deallocated
import Foundation
func nonNativeBridgeObject(o: AnyObject) -> Builtin.BridgeObject {
let tagged = ((Builtin.reinterpretCast(o) as UInt) & OBJC_TAGGED_POINTER_BITS) != 0
return Builtin.castToBridgeObject(
o, tagged ? 0._builtinWordValue : NATIVE_SPARE_BITS._builtinWordValue)
}
// Try with a (probably) tagged pointer. No bits may be masked into a
// non-native object.
if true {
let x = NSNumber(integer: 22)
let bo = nonNativeBridgeObject(x)
let bo2 = bo
let x1: NSNumber = Builtin.castReferenceFromBridgeObject(bo)
let x2: NSNumber = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
var bo3 = nonNativeBridgeObject(NSNumber(integer: 22))
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
}
var unTaggedString: NSString {
return NSString(format: "A long string that won't fit in a tagged pointer")
}
// Try with an un-tagged pointer.
if true {
let x = unTaggedString
let bo = nonNativeBridgeObject(x)
let bo2 = bo
let x1: NSString = Builtin.castReferenceFromBridgeObject(bo)
let x2: NSString = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
var bo3 = nonNativeBridgeObject(unTaggedString)
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
}
func hitOptionalGenerically<T>(x: T?) {
switch x {
case .some:
print("some")
case .none:
print("none")
}
}
func hitOptionalSpecifically(x: Builtin.BridgeObject?) {
switch x {
case .some:
print("some")
case .none:
print("none")
}
}
if true {
// CHECK-NEXT: true
print(sizeof(Optional<Builtin.BridgeObject>.self)
== sizeof(Builtin.BridgeObject.self))
var bo: Builtin.BridgeObject? = nil
// CHECK-NEXT: none
hitOptionalSpecifically(bo)
// CHECK-NEXT: none
hitOptionalGenerically(bo)
bo = Builtin.castToBridgeObject(C(), 0._builtinWordValue)
// CHECK-NEXT: some
hitOptionalSpecifically(bo)
// CHECK: some
hitOptionalGenerically(bo)
}
| apache-2.0 | bf9256a00e61c4bab4b5db7a08618edc | 24.534031 | 85 | 0.69879 | 3.297498 | false | false | false | false |
Harley-xk/SimpleDataKit | Example/Pods/Comet/Comet/Extensions/UINavigationController+Comet.swift | 2 | 886 | //
// UINavigationController+Comet.swift
// Pods
//
// Created by Harley on 2017/2/9.
//
//
import Foundation
import UIKit
extension UINavigationController {
/// 替换当前导航控制器栈顶的视图
open func replaceTop(with viewController: UIViewController, animated: Bool = true) {
var vcs = self.viewControllers
vcs.removeLast()
vcs.append(viewController)
setViewControllers(vcs, animated: animated)
}
/// 简化 push 函数
open func push(_ viewController: UIViewController, animated: Bool = true) {
pushViewController(viewController, animated: animated)
}
/// 简化 pop 函数,且不强制要求接收返回值
@discardableResult
open func pop(animated: Bool = true) -> UIViewController? {
let poped = popViewController(animated: animated)
return poped
}
}
| mit | 354e564c878f7cd2583f616fb5a93434 | 24.5625 | 88 | 0.661369 | 4.421622 | false | false | false | false |
joerocca/GitHawk | Local Pods/SwipeCellKit/Source/SwipeCollectionViewCell.swift | 2 | 17782 | //
// SwipeCollectionViewCell.swift
// SwipeCellKit
//
// Created by Ryan Nystrom on 6/26/17.
//
//
import UIKit
open class SwipeCollectionViewCell: UICollectionViewCell {
public weak var delegate: SwipeCollectionViewCellDelegate?
public var canDelete = false
var animator: SwipeAnimator?
var deleting = false
var state = SwipeState.center
var originalCenter: CGFloat = 0
weak var collectionView: UICollectionView?
var actionsView: SwipeActionsView?
var originalLayoutMargins: UIEdgeInsets = .zero
lazy var panGestureRecognizer: UIPanGestureRecognizer = {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
gesture.delegate = self
return gesture
}()
lazy var tapGestureRecognizer: UITapGestureRecognizer = {
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(gesture:)))
gesture.delegate = self
return gesture
}()
let elasticScrollRatio: CGFloat = 0.4
var scrollRatio: CGFloat = 1.0
/// :nodoc:
override open var center: CGPoint {
set {
if !deleting {
super.center = newValue
}
actionsView?.visibleWidth = abs(frame.minX)
}
get {
return super.center
}
}
/// :nodoc:
open override var frame: CGRect {
set { super.frame = state.isActive ? CGRect(origin: CGPoint(x: frame.minX, y: newValue.minY), size: newValue.size) : newValue }
get { return super.frame }
}
/// :nodoc:
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
/// :nodoc:
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
deinit {
collectionView?.panGestureRecognizer.removeTarget(self, action: nil)
}
func configure() {
clipsToBounds = false
addGestureRecognizer(tapGestureRecognizer)
addGestureRecognizer(panGestureRecognizer)
}
/// :nodoc:
override open func prepareForReuse() {
super.prepareForReuse()
reset()
}
/// :nodoc:
override open func didMoveToSuperview() {
super.didMoveToSuperview()
var view: UIView = self
while let superview = view.superview {
view = superview
if let collectionView = view as? UICollectionView {
self.collectionView = collectionView
collectionView.panGestureRecognizer.removeTarget(self, action: nil)
collectionView.panGestureRecognizer.addTarget(self, action: #selector(handleTablePan(gesture:)))
return
}
}
}
@objc func handlePan(gesture: UIPanGestureRecognizer) {
guard let target = gesture.view else { return }
switch gesture.state {
case .began:
stopAnimatorIfNeeded()
originalCenter = center.x
if state == .center || state == .animatingToCenter {
let velocity = gesture.velocity(in: target)
let orientation: SwipeActionsOrientation = velocity.x > 0 ? .left : .right
showActionsView(for: orientation)
}
case .changed:
guard let actionsView = actionsView else { return }
let translation = gesture.translation(in: target).x
scrollRatio = 1.0
// Check if dragging past the center of the opposite direction of action view, if so
// then we need to apply elasticity
if (translation + originalCenter - bounds.midX) * actionsView.orientation.scale > 0 {
target.center.x = gesture.elasticTranslation(in: target,
withLimit: .zero,
fromOriginalCenter: CGPoint(x: originalCenter, y: 0)).x
scrollRatio = elasticScrollRatio
return
}
if let expansionStyle = actionsView.options.expansionStyle {
let expanded = expansionStyle.shouldExpand(view: self, gesture: gesture, in: collectionView!)
let targetOffset = expansionStyle.targetOffset(for: self, in: collectionView!)
let currentOffset = abs(translation + originalCenter - bounds.midX)
if expanded && !actionsView.expanded && targetOffset > currentOffset {
let centerForTranslationToEdge = bounds.midX - targetOffset * actionsView.orientation.scale
let delta = centerForTranslationToEdge - originalCenter
animate(toOffset: centerForTranslationToEdge)
gesture.setTranslation(CGPoint(x: delta, y: 0), in: superview!)
} else {
target.center.x = gesture.elasticTranslation(in: target,
withLimit: CGSize(width: targetOffset, height: 0),
fromOriginalCenter: CGPoint(x: originalCenter, y: 0),
applyingRatio: expansionStyle.targetOverscrollElasticity).x
}
actionsView.setExpanded(expanded: expanded, feedback: true)
} else {
target.center.x = gesture.elasticTranslation(in: target,
withLimit: CGSize(width: actionsView.preferredWidth, height: 0),
fromOriginalCenter: CGPoint(x: originalCenter, y: 0),
applyingRatio: elasticScrollRatio).x
if (target.center.x - originalCenter) / translation != 1.0 {
scrollRatio = elasticScrollRatio
}
}
case .ended:
guard let actionsView = actionsView else { return }
let velocity = gesture.velocity(in: target)
state = targetState(forVelocity: velocity)
if actionsView.expanded == true, let expandedAction = actionsView.expandableAction {
perform(action: expandedAction)
} else {
let targetOffset = targetCenter(active: state.isActive)
let distance = targetOffset - center.x
let normalizedVelocity = velocity.x * scrollRatio / distance
animate(toOffset: targetOffset, withInitialVelocity: normalizedVelocity) { _ in
if self.state == .center {
self.reset()
}
}
if !state.isActive {
notifyEditingStateChange(active: false)
}
}
default: break
}
}
@discardableResult
func showActionsView(for orientation: SwipeActionsOrientation) -> Bool {
guard let collectionView = collectionView,
let indexPath = collectionView.indexPath(for: self),
let actions = delegate?.collectionView(collectionView, editActionsForRowAt: indexPath, for: orientation),
actions.count > 0
else {
return false
}
originalLayoutMargins = super.layoutMargins
// Remove highlight and deselect any selected cells
isHighlighted = false
let selectedIndexPaths = collectionView.indexPathsForSelectedItems
selectedIndexPaths?.forEach { collectionView.deselectItem(at: $0, animated: false) }
// Temporarily remove table gestures
collectionView.setGestureEnabled(false)
configureActionsView(with: actions, for: orientation)
return true
}
func configureActionsView(with actions: [SwipeAction], for orientation: SwipeActionsOrientation) {
guard let collectionView = collectionView,
let indexPath = collectionView.indexPath(for: self) else { return }
let options = delegate?.collectionView(collectionView, editActionsOptionsForRowAt: indexPath, for: orientation) ?? SwipeTableOptions()
self.actionsView?.removeFromSuperview()
self.actionsView = nil
let actionsView = SwipeActionsView(maxSize: bounds.size,
options: options,
orientation: orientation,
actions: actions)
actionsView.delegate = self
addSubview(actionsView)
actionsView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
actionsView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 2).isActive = true
actionsView.topAnchor.constraint(equalTo: topAnchor).isActive = true
if orientation == .left {
actionsView.rightAnchor.constraint(equalTo: leftAnchor).isActive = true
} else {
actionsView.leftAnchor.constraint(equalTo: rightAnchor).isActive = true
}
self.actionsView = actionsView
state = .dragging
notifyEditingStateChange(active: true)
}
func notifyEditingStateChange(active: Bool) {
guard let actionsView = actionsView,
let collectionView = collectionView,
let indexPath = collectionView.indexPath(for: self) else { return }
if active {
delegate?.collectionView(collectionView, willBeginEditingRowAt: indexPath, for: actionsView.orientation)
} else {
delegate?.collectionView(collectionView, didEndEditingRowAt: indexPath, for: actionsView.orientation)
}
}
func animate(duration: Double = 0.7, toOffset offset: CGFloat, withInitialVelocity velocity: CGFloat = 0, completion: ((Bool) -> Void)? = nil) {
stopAnimatorIfNeeded()
layoutIfNeeded()
let animator: SwipeAnimator = {
if velocity != 0 {
if #available(iOS 10, *) {
let velocity = CGVector(dx: velocity, dy: velocity)
let parameters = UISpringTimingParameters(mass: 1.0, stiffness: 100, damping: 18, initialVelocity: velocity)
return UIViewPropertyAnimator(duration: 0.0, timingParameters: parameters)
} else {
return UIViewSpringAnimator(duration: duration, damping: 1.0, initialVelocity: velocity)
}
} else {
if #available(iOS 10, *) {
return UIViewPropertyAnimator(duration: duration, dampingRatio: 1.0)
} else {
return UIViewSpringAnimator(duration: duration, damping: 1.0)
}
}
}()
animator.addAnimations({
self.center = CGPoint(x: offset, y: self.center.y)
self.layoutIfNeeded()
})
if let completion = completion {
animator.addCompletion(completion: completion)
}
self.animator = animator
animator.startAnimation()
}
func stopAnimatorIfNeeded() {
if animator?.isRunning == true {
animator?.stopAnimation(true)
}
}
@objc func handleTap(gesture: UITapGestureRecognizer) {
hideSwipe(animated: true)
}
@objc func handleTablePan(gesture: UIPanGestureRecognizer) {
if gesture.state == .began {
hideSwipe(animated: true)
}
}
// Override so we can accept touches anywhere within the cell's minY/maxY.
// This is required to detect touches on the `SwipeActionsView` sitting alongside the
// `SwipeTableCell`.
/// :nodoc:
override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let superview = superview else { return false }
let point = convert(point, to: superview)
if !UIAccessibilityIsVoiceOverRunning() {
for cell in collectionView?.swipeCells ?? [] {
if (cell.state == .left || cell.state == .right) && !cell.contains(point: point) {
collectionView?.hideSwipeCell()
return false
}
}
}
return contains(point: point)
}
func contains(point: CGPoint) -> Bool {
return point.y > frame.minY && point.y < frame.maxY
}
/// :nodoc:
open override var isHighlighted: Bool {
didSet {
super.isHighlighted = isHighlighted && state == .center
}
}
/// :nodoc:
override open var layoutMargins: UIEdgeInsets {
get {
return frame.origin.x != 0 ? originalLayoutMargins : super.layoutMargins
}
set {
super.layoutMargins = newValue
}
}
}
extension SwipeCollectionViewCell {
func targetState(forVelocity velocity: CGPoint) -> SwipeState {
guard let actionsView = actionsView else { return .center }
switch actionsView.orientation {
case .left:
return (velocity.x < 0 && !actionsView.expanded) ? .center : .left
case .right:
return (velocity.x > 0 && !actionsView.expanded) ? .center : .right
}
}
func targetCenter(active: Bool) -> CGFloat {
guard let actionsView = actionsView, active == true else { return bounds.midX }
return bounds.midX - actionsView.preferredWidth * actionsView.orientation.scale
}
func reset() {
deleting = false
state = .center
collectionView?.setGestureEnabled(true)
actionsView?.removeFromSuperview()
actionsView = nil
}
}
extension SwipeCollectionViewCell: SwipeActionsViewDelegate {
func swipeActionsView(_ swipeActionsView: SwipeActionsView, didSelect action: SwipeAction) {
perform(action: action)
}
func perform(action: SwipeAction) {
guard let actionsView = actionsView else { return }
if action == actionsView.expandableAction, let expansionStyle = actionsView.options.expansionStyle {
// Trigger the expansion (may already be expanded from drag)
actionsView.setExpanded(expanded: true)
switch expansionStyle.completionAnimation {
case .bounce:
perform(action: action, hide: true)
case .fill(let fillOption):
performFillAction(action: action, fillOption: fillOption)
}
} else {
perform(action: action, hide: action.hidesWhenSelected)
}
}
func perform(action: SwipeAction, hide: Bool) {
guard let collectionView = collectionView, let indexPath = collectionView.indexPath(for: self) else { return }
if hide {
hideSwipe(animated: true)
}
action.handler?(action, indexPath)
}
func performFillAction(action: SwipeAction, fillOption: SwipeExpansionStyle.FillOptions) {
guard let actionsView = actionsView,
let collectionView = collectionView,
let indexPath = collectionView.indexPath(for: self) else { return }
let newCenter = bounds.midX - (bounds.width + actionsView.minimumButtonWidth) * actionsView.orientation.scale
action.completionHandler = { [weak self] style in
action.completionHandler = nil
self?.delegate?.collectionView(collectionView, didEndEditingRowAt: indexPath, for: actionsView.orientation)
switch style {
case .delete:
self?.mask = actionsView.createDeletionMask()
if self?.canDelete == true {
collectionView.deleteItems(at: [indexPath])
}
UIView.animate(withDuration: 0.3, animations: {
self?.center.x = newCenter
self?.mask?.frame.size.height = 0
if fillOption.timing == .after {
actionsView.alpha = 0
}
}) { [weak self] _ in
self?.mask = nil
self?.reset()
}
case .reset:
self?.hideSwipe(animated: true)
}
}
let invokeAction = {
action.handler?(action, indexPath)
if let style = fillOption.autoFulFillmentStyle {
action.fulfill(with: style)
}
}
animate(duration: 0.3, toOffset: newCenter) { _ in
if fillOption.timing == .after {
self.deleting = true
invokeAction()
}
}
if fillOption.timing == .with {
self.deleting = true
invokeAction()
}
}
}
extension SwipeCollectionViewCell: UIGestureRecognizerDelegate {
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == tapGestureRecognizer {
if UIAccessibilityIsVoiceOverRunning() {
collectionView?.hideSwipeCell()
}
let cell = collectionView?.swipeCells.first(where: { $0.state.isActive })
return cell == nil ? false : true
}
if gestureRecognizer == panGestureRecognizer,
let view = gestureRecognizer.view,
let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer
{
let translation = gestureRecognizer.translation(in: view)
return abs(translation.y) <= abs(translation.x)
}
return true
}
}
extension SwipeCollectionViewCell: Swipeable {}
| mit | 70874b25b38c91600bcca3625740a4a5 | 33.528155 | 148 | 0.583905 | 5.605927 | false | false | false | false |
naokits/my-programming-marathon | RACPlayground/Pods/Loggerithm/Source/Loggerithm.swift | 3 | 13043 | //
// Loggerithm.swift
// Loggerithm
//
// Created by Honghao Zhang on 2014-12-10.
// Copyright (c) 2015 Honghao Zhang (张宏昊)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public struct Loggerithm {
/// A default logger instance.
public static let defaultLogger = Loggerithm()
/// Log level current used.
public var logLevel = LogLevel.defaultLevel
/// Whether should show date & time field, ture for showing, false for hidding.
public var showDateTime = true
/// Whether should show log level field, ture for showing, false for hidding.
public var showLogLevel = true
/// Whether should show file name field, ture for showing, false for hidding.
public var showFileName = true
/// Whether should show line number field, ture for showing, false for hidding.
public var showLineNumber = true
/// Whether should show function name field, ture for showing, false for hidding.
public var showFunctionName = true
/// Whether should output color log.
public var useColorfulLog = false
/// Color used for verbose log string.
public var verboseColor: Color? {
set {
LoggerColor.verboseColor = newValue
}
get {
return LoggerColor.verboseColor
}
}
/// Color used for debug log string.
public var debugColor: Color? {
set {
LoggerColor.debugColor = newValue
}
get {
return LoggerColor.debugColor
}
}
/// Color used for info log string.
public var infoColor: Color? {
set {
LoggerColor.infoColor = newValue
}
get {
return LoggerColor.infoColor
}
}
/// Color used for warning log string.
public var warningColor: Color? {
set {
LoggerColor.warningColor = newValue
}
get {
return LoggerColor.warningColor
}
}
/// Color used for error log string.
public var errorColor: Color? {
set {
LoggerColor.errorColor = newValue
}
get {
return LoggerColor.errorColor
}
}
/// NSDateFromatter used internally.
private let dateFormatter = NSDateFormatter()
/// LogFunction used, print for DEBUG, NSLog for Production.
#if DEBUG
private let LogFunction: (format: String) -> Void = {format in print(format)}
private let UsingNSLog = false
#else
private let LogFunction: (format: String, args: CVarArgType...) -> Void = NSLog
private let UsingNSLog = true
#endif
public init() {
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") //24H
dateFormatter.dateFormat = "y-MM-dd HH:mm:ss.SSS"
// Check to see whether XcodeColors is installed and enabled
// useColorfulLog will be turned on when environment variable "XcodeColors" == "YES"
if let xcodeColorsEnabled = NSProcessInfo().environment["XcodeColors"] as String? where xcodeColorsEnabled == "YES" {
useColorfulLog = true
}
}
/**
Prinln an new line, without any fileds. This will ignore any filed settings.
*/
public func emptyLine() {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.LogFunction(format: "")
})
}
/**
Logs textual representation of `value` with .Verbose level.
- parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`.
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- returns: The string logged out.
*/
public func verbose<T>(value: T, function: String = #function, file: String = #file, line: Int = #line) -> String? {
return verbose("\(value)", function: function, file: file, line: line)
}
/**
Logs an message with formatted string and arguments list with .Verbose level.
- parameter format: Formatted string
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- parameter args: Arguments list
- returns: The string logged out.
*/
public func verbose(format: String = "", function: String = #function, file: String = #file, line: Int = #line, args: CVarArgType...) -> String? {
if .Verbose >= logLevel {
return log(.Verbose, function: function, file: file, line: line, format: format, args: args)
}
return nil
}
/**
Logs textual representation of `value` with .Debug level.
- parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`.
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- returns: The string logged out.
*/
public func debug<T>(value: T, function: String = #function, file: String = #file, line: Int = #line) -> String? {
return debug("\(value)", function: function, file: file, line: line)
}
/**
Logs an message with formatted string and arguments list with .Debug level.
- parameter format: Formatted string
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- parameter args: Arguments list
- returns: The string logged out.
*/
public func debug(format: String = "", function: String = #function, file: String = #file, line: Int = #line, args: CVarArgType...) -> String?
{
if .Debug >= logLevel {
return log(.Debug, function: function, file: file, line: line, format: format, args: args)
}
return nil
}
/**
Logs textual representation of `value` with .Info level.
- parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`.
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- returns: The string logged out.
*/
public func info<T>(value: T, function: String = #function, file: String = #file, line: Int = #line) -> String? {
return info("\(value)", function: function, file: file, line: line)
}
/**
Logs an message with formatted string and arguments list with .Info level.
- parameter format: Formatted string
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- parameter args: Arguments list
- returns: The string logged out.
*/
public func info(format: String = "", function: String = #function, file: String = #file, line: Int = #line, args: CVarArgType...) -> String?
{
if .Info >= logLevel {
return log(.Info, function: function, file: file, line: line, format: format, args: args)
}
return nil
}
/**
Logs textual representation of `value` with .Warning level.
- parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`.
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- returns: The string logged out.
*/
public func warning<T>(value: T, function: String = #function, file: String = #file, line: Int = #line) -> String? {
return warning("\(value)", function: function, file: file, line: line)
}
/**
Logs an message with formatted string and arguments list with .Warning level.
- parameter format: Formatted string
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- parameter args: Arguments list
- returns: The string logged out.
*/
public func warning(format: String = "", function: String = #function, file: String = #file, line: Int = #line, args: CVarArgType...) -> String?
{
if .Warning >= logLevel {
return log(.Warning, function: function, file: file, line: line, format: format, args: args)
}
return nil
}
/**
Logs textual representation of `value` with .Error level.
- parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`.
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- returns: The string logged out.
*/
public func error<T>(value: T, function: String = #function, file: String = #file, line: Int = #line) -> String? {
return error("\(value)", function: function, file: file, line: line)
}
/**
Logs an message with formatted string and arguments list with .Error level.
- parameter format: Formatted string
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- parameter args: Arguments list
- returns: The string logged out.
*/
public func error(format: String = "", function: String = #function, file: String = #file, line: Int = #line, args: CVarArgType...) -> String?
{
if .Error >= logLevel {
return log(.Error, function: function, file: file, line: line, format: format, args: args)
}
return nil
}
/**
Logs an message with formatted string and arguments list.
- parameter level: Log level
- parameter format: Formatted string
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- parameter args: Arguments list
- returns: The string logged out.
*/
public func logWithLevel(level: LogLevel, _ format: String = "", function: String = #function, file: String = #file, line: Int = #line, args: CVarArgType...) -> String?
{
if level >= logLevel {
return log(level, file: file, function: function, line: line, format: format, args: args)
}
return nil
}
/**
Construct a log message, log it out and return it.
- parameter level: Log level
- parameter function: Function name
- parameter file: File name
- parameter line: Line number
- parameter format: Formatted string
- parameter args: Arguments list
- returns: The string logged out.
*/
private func log(level: LogLevel, function: String = #function, file: String = #file, line: Int = #line, format: String, args: [CVarArgType]) -> String
{
let dateTime = showDateTime ? (UsingNSLog ? "" : "\(dateFormatter.stringFromDate(NSDate())) ") : ""
let levelString = showLogLevel ? "[\(LogLevel.descritionForLogLevel(level))] " : ""
var fileLine = ""
if showFileName {
fileLine += "[" + (file as NSString).lastPathComponent
if showLineNumber {
fileLine += ":\(line)"
}
fileLine += "] "
}
let functionString = showFunctionName ? function : ""
let message: String
if args.count == 0 {
message = format
} else {
message = String(format: format, arguments: args)
}
let infoString = "\(dateTime)\(levelString)\(fileLine)\(functionString)".stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
let logString = infoString + (infoString.isEmpty ? "" : ": ") + "\(message)"
let outputString = useColorfulLog ? LoggerColor.applyColorForLogString(logString, withLevel: level) : logString
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.LogFunction(format: outputString)
// })
return logString
}
}
| mit | a9d82c73c968471651b34d2c971fcffd | 34.620219 | 172 | 0.613024 | 4.601836 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/User/View/CPDeveloperInfoView.swift | 1 | 5388 | //
// CPDeveloperInfoView.swift
// BeeFun
//
// Created by WengHengcong on 3/10/16.
// Copyright © 2016 JungleSong. All rights reserved.
//
import UIKit
protocol UserProfileActionProtocol: class {
func viewFollowAction()
func viewReposAction()
func viewFollowingAction()
}
class CPDeveloperInfoView: UIView {
var avatarImgV: UIImageView = UIImageView()
var nameLabel: UILabel = UILabel()
var emailLabel: UILabel = UILabel()
var followerBtn: UIButton = UIButton()
var reposBtn: UIButton = UIButton()
var followingBtn: UIButton = UIButton()
weak var userActionDelegate: UserProfileActionProtocol?
var developer: ObjUser? {
didSet {
div_fillData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
div_customView()
}
init(obj: ObjUser) {
super.init(frame: CGRect.zero)
self.developer = obj
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func div_customView() {
addSubview(avatarImgV)
addSubview(nameLabel)
addSubview(emailLabel)
addSubview(followerBtn)
addSubview(reposBtn)
addSubview(followingBtn)
backgroundColor = UIColor.white
let imgW: CGFloat = 70.0
let imgX: CGFloat = (ScreenSize.width-imgW)/2.0
self.avatarImgV.layer.cornerRadius = imgW/2
self.avatarImgV.layer.masksToBounds = true
avatarImgV.frame = CGRect(x: imgX, y: 16.0, width: imgW, height: imgW)
nameLabel.frame = CGRect(x: 0, y: avatarImgV.bottom+6.0, width: ScreenSize.width, height: 21.0)
nameLabel.font = UIFont.bfSystemFont(ofSize: 19.0)
nameLabel.textColor = UIColor.iOS11Black
nameLabel.textAlignment = .center
emailLabel.frame = CGRect(x: 0, y: nameLabel.bottom+5.0, width: ScreenSize.width, height: 21.0)
emailLabel.font = UIFont.bfSystemFont(ofSize: 14.0)
emailLabel.textColor = UIColor.iOS11Black
emailLabel.textAlignment = .center
let imgEdgeInsets1 = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 10)
let borderWidth: CGFloat = 0.5
let btnY = emailLabel.bottom+8.0
let btnW = ScreenSize.width/3.0
let btnH: CGFloat = 36.0
let btnArr1: [UIButton] = [followerBtn, reposBtn, followingBtn]
for (index, btn) in btnArr1.enumerated() {
let btnX = btnW*CGFloat(index)
btn.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
btn.titleLabel?.font = UIFont.bfSystemFont(ofSize: 12.0)
btn.backgroundColor = UIColor.white
btn.imageEdgeInsets = imgEdgeInsets1
btn.layer.borderColor = UIColor.bfLineBackgroundColor.cgColor
btn.layer.borderWidth = borderWidth
btn.setTitleColor(UIColor.bfRedColor, for: UIControlState())
btn.titleLabel?.numberOfLines = 0
btn.titleLabel?.textAlignment = .center
}
followerBtn.setTitle("0 \n"+"Follower".localized, for: UIControlState())
followerBtn.addTarget(self, action: #selector(CPDeveloperInfoView.div_followAction), for: .touchUpInside)
reposBtn.setTitle("0 \n"+"Repositories".localized, for: UIControlState())
reposBtn.addTarget(self, action: #selector(CPDeveloperInfoView.div_reposAction), for: .touchUpInside)
followingBtn.setTitle("0 \n"+"Following".localized, for: UIControlState())
followingBtn.addTarget(self, action: #selector(CPDeveloperInfoView.div_followingAction), for: .touchUpInside)
}
func div_fillData() {
if let avatarUrl = developer!.avatar_url {
avatarImgV.kf.setImage(with: URL(string: avatarUrl)!)
}
nameLabel.text = developer!.name
if let email = developer!.email {
emailLabel.isHidden = false
emailLabel.text = email
} else {
emailLabel.isHidden = true
}
if let followerCount = developer!.followers {
followerBtn.setTitle("\(followerCount) \n"+"Follower".localized, for: UIControlState())
}
if let reposCount = developer!.public_repos {
reposBtn.setTitle("\(reposCount) \n"+"Repositories".localized, for: UIControlState())
}
if let followingCount = developer!.following {
followingBtn.setTitle("\(followingCount) \n"+"Following".localized, for: UIControlState())
}
}
@objc func div_followAction() {
if let followerCount = developer!.followers {
if followerCount == 0 {
return
}
}
if self.userActionDelegate != nil {
self.userActionDelegate!.viewFollowAction()
}
}
@objc func div_reposAction() {
if let reposCount = developer!.public_repos {
if reposCount == 0 {
return
}
}
if self.userActionDelegate != nil {
self.userActionDelegate!.viewReposAction()
}
}
@objc func div_followingAction() {
if let followingCount = developer!.following {
if followingCount == 0 {
return
}
}
if self.userActionDelegate != nil {
self.userActionDelegate!.viewFollowingAction()
}
}
}
| mit | b7ac6784aa5a23f689fe5b8239a42f32 | 29.264045 | 117 | 0.617041 | 4.474252 | false | false | false | false |
jaouahbi/OMProgressImageView | ExampleSwift/ExampleSwift/ViewController.swift | 1 | 2660 | //
// Copyright 2015 - Jorge Ouahbi
//
// 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.
//
//
// ViewController.swift
// OMProgressImageView
//
// Created by Jorge Ouahbi on 27/3/15.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var progressH:OMProgressImageView?
@IBOutlet weak var progressV:OMProgressImageView?
@IBOutlet weak var progressR:OMProgressImageView?
@IBOutlet weak var progressC:OMProgressImageView?
override func viewDidLoad() {
super.viewDidLoad()
let image:UIImage = UIImage(named: "1")!
progressH?.type = .Horizontal
progressH?.image = image;
progressH?.backgroundColor = UIColor.blackColor()
progressH?.grayScale = false
progressH?.showing = true
progressV?.type = .Vertical
progressV?.image = image;
progressV?.backgroundColor = UIColor.clearColor()
progressV?.grayScale = false
progressV?.showing = false
progressR?.type = .Radial
progressR?.image = image;
progressR?.backgroundColor = UIColor.blueColor()
progressR?.grayScale = false
progressR?.showing = false
progressC?.type = .Circular
progressC?.image = image;
progressC?.backgroundColor = UIColor.grayColor()
progressC?.grayScale = false
progressC?.showing = true
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
self.progressH?.setProgress(1.0, animate: true)
self.progressV?.setProgress(1.0, animate: true)
self.progressR?.setProgress(1.0, animate: true)
self.progressC?.setProgress(1.0, animate: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 522c0199a52df436d47069cbf64fd78a | 31.839506 | 77 | 0.609774 | 4.562607 | false | false | false | false |
fluidpixel/tvOS-controller | iPhone-controller/ViewController.swift | 1 | 6008 | //
// ViewController.swift
// iPhone-controller
//
// Created by Paul Jones on 02/11/2015.
// Copyright © 2015 Fluid Pixel Limited. All rights reserved.
//
import UIKit
import CoreMotion
import SceneKit
class ViewController: UIViewController, TVCPhoneSessionDelegate {
var remote = TVCPhoneSession()
let motion = CMMotionManager()
var buttonEnabled = 0
var speedSquared : Float = 0.0
@IBOutlet weak var speed: UILabel!
@IBOutlet var TouchPad: UIPanGestureRecognizer!
@IBOutlet var messageArea:UILabel!
@IBOutlet weak var AccelerateButton: UIButton!
@IBOutlet weak var BreakButton: UIButton!
//for touchpad-to canvas on tv
var point = CGPoint.zero
var swiped = false
@IBOutlet weak var textMessage: UITextView!
@IBAction func button1Pressed() {
send("Button", text: 1)
buttonEnabled = 1
//set up accelerometer readings
if motion.deviceMotionAvailable {
motion.deviceMotionUpdateInterval = 0.5
motion.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data: CMDeviceMotion?, error :NSError?) -> Void in
if error == nil && data != nil {
let temp = data!.attitude
let accel : [Float] = [Float(temp.pitch), Float(temp.yaw), Float(temp.roll)]
self.send("Accelerometer", text: accel)
}else {
self.write((error?.localizedDescription)!)
}
})
}
}
@IBAction func button2Pressed() {
send("Button", text: 2)
buttonEnabled = 2
motion.stopDeviceMotionUpdates()
}
@IBAction func button3Pressed() {
send("Button", text: 3)
buttonEnabled = 3
motion.stopDeviceMotionUpdates()
}
//Button tap controls
@IBAction func OnAccelerateTapped(sender: UIButton) {
//Note: Touch inside disables the time the same way touch outside does,
// so the user can hold the button to gain acceleration
// 1 - accelerate
// 0 - release
// -1 - break
send("Speed", text: 0)
}
@IBAction func OnAccelerateReleased(sender: UIButton) {
send("Speed", text: 0)
}
@IBAction func AcceleratePressed(sender: UIButton) {
send("Speed", text: 1)
}
@IBAction func OnBreakTapped(sender: UIButton) {
send("Speed", text: 0)
}
@IBAction func BreakPressed(sender: UIButton) {
send("Speed", text: -1)
}
@IBAction func OnBreakReleased(sender: UIButton) {
send("Speed", text: 0)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
swiped = false
if touches.first != nil {
let touch = touches.first!
if buttonEnabled == 2 {
point = touch.locationInView(self.view)
send("DrawBegin", text: [point.x, point.y])
}
}
super.touchesBegan(touches, withEvent: event)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
swiped = true
if touches.first != nil {
let touch = touches.first!
if buttonEnabled == 2 {
let currentPoint : CGPoint = touch.locationInView(view)
send("DrawMove", text: [currentPoint.x, currentPoint.y])
point = currentPoint
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if !swiped {
if buttonEnabled == 2 {
send("DrawEnd", text: [point.x, point.y])
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.remote.delegate = self
self.view?.multipleTouchEnabled = true
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func send(identifier: String, text:AnyObject) {
self.write("\(text)")
self.remote.sendMessage([identifier:text], replyHandler: { (reply) -> Void in
self.write("Reply received: \(reply)")
if var tempSpeed = reply["Reply"] as? Float {
tempSpeed = sqrt(tempSpeed)
self.speed.text = "\(tempSpeed)mph"
}
}) { (error) -> Void in
self.write("ERROR : \(error)")
}
}
private func write(text:String) {
dispatch_async(dispatch_get_main_queue()) {
let existingText = self.textMessage.text!
self.textMessage.text = "\(existingText)\n\(text)"
}
}
func didConnect() {
self.write("Connected")
}
func didDisconnect() {
self.write("Disconnected")
}
func didReceiveBroadcast(message: [String : AnyObject]) {
self.write("Broadcast received: \(message)")
}
func didReceiveBroadcast(message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
self.didReceiveBroadcast(message)
replyHandler(["Reply":0])
}
func didReceiveMessage(message: [String : AnyObject]) {
self.write("Message received: \(message)")
}
func didReceiveMessage(message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
self.didReceiveMessage(message)
replyHandler(["Reply":0])
}
}
| mit | cc62b322ebc70baccea30c4861e59fe7 | 28.885572 | 147 | 0.572499 | 4.832663 | false | false | false | false |
wayfair/brickkit-ios | Source/Models/BrickSection.swift | 1 | 5828 | //
// BrickSection.swift
// BrickKit
//
// Created by Ruben Cagnie on 7/5/17.
// Copyright © 2017 Wayfair. All rights reserved.
//
import Foundation
public protocol BrickSectionOrderDataSource: class {
func brickAndIndex(atIndex brickIndex: Int, section: BrickSection) -> (Brick, Int)?
}
open class BrickSection: Brick {
open var bricks: [Brick]
open var inset: CGFloat
open var edgeInsets: UIEdgeInsets
open var alignRowHeights: Bool
open var alignment: BrickAlignment
internal fileprivate(set) var collectionIndex: Int = 0
internal fileprivate(set) var collectionIdentifier: String = ""
internal fileprivate(set) var sectionCount: Int = 0
internal fileprivate(set) var sectionIndexPaths: [CollectionInfo: [Int: IndexPath]] = [:] // Variable that keeps track of the indexpaths of the sections
/// Optional dictionary that holds the identifier of a brick as a key and the value is the nib that should be used for that brick
/// These nibs will be registered, when setting this BrickSection on a BrickCollectionView
open var nibIdentifiers: [String: UINib]?
open var classIdentifiers: [String: AnyClass]?
open internal(set) weak var brickCollectionView: BrickCollectionView?
open weak var orderDataSource: BrickSectionOrderDataSource?
open weak var repeatCountDataSource: BrickRepeatCountDataSource? {
didSet {
sectionIndexPaths.removeAll()
}
}
public init(_ identifier: String = "", width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 0)), backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, bricks: [Brick], inset: CGFloat = 0, edgeInsets: UIEdgeInsets = .zero, alignRowHeights: Bool = false, alignment: BrickAlignment = BrickAlignment(horizontal: .left, vertical: .top)) {
self.bricks = bricks
self.inset = inset
self.edgeInsets = edgeInsets
self.alignRowHeights = alignRowHeights
self.alignment = alignment
super.init(identifier, size: BrickSize(width: width, height: height), backgroundColor: backgroundColor, backgroundView: backgroundView)
}
/// Invalidate the brick counts for a given collection. Recalculate where sections are in the tree
func invalidateIfNeeded(in collection: CollectionInfo) -> [Int: IndexPath] {
if let sectionIndexPaths = self.sectionIndexPaths[collection] {
return sectionIndexPaths
}
return invalidateSectionIndexPaths(in: collection)
}
/// Invalidate the counts for a given dimension
func invalidateCounts(in collection: CollectionInfo) {
sectionIndexPaths[collection] = nil
}
func invalidateSectionIndexPaths(in collection: CollectionInfo) -> [Int: IndexPath] {
var sectionIndexPaths: [Int: IndexPath] = [:]
var sectionCount = 0
BrickSection.addSection(§ionIndexPaths, sectionCount: §ionCount, bricks: [self], repeatCountDataSource: repeatCountDataSource, in: collection)
self.sectionIndexPaths[collection] = sectionIndexPaths
self.sectionCount = sectionCount
return sectionIndexPaths
}
func brickAndIndex(atIndex brickIndex: Int, in collection: CollectionInfo) -> (Brick, Int)? {
if let orderDataSource = orderDataSource, let brickAndIndex = orderDataSource.brickAndIndex(atIndex: brickIndex, section: self) {
return brickAndIndex
} else {
var index = 0
for brick in self.bricks {
if brickIndex < index + brick.count(for: collection) {
return (brick, brickIndex - index)
}
index += brick.count(for: collection)
}
}
return nil
}
/// Add a section
static fileprivate func addSection(_ sectionIndexPaths: inout [Int: IndexPath], sectionCount: inout Int, bricks: [Brick], repeatCountDataSource: BrickRepeatCountDataSource?, atIndexPath indexPath: IndexPath? = nil, in collection: CollectionInfo) {
let sectionId = sectionCount
sectionCount += 1
if let indexPath = indexPath {
sectionIndexPaths[sectionId] = indexPath
}
var index = 0
for brick in bricks {
brick.counts[collection] = repeatCountDataSource?.repeatCount(for: brick.identifier, with: collection.index, collectionIdentifier: collection.identifier) ?? brick.count(for: collection)
if let sectionModel = brick as? BrickSection {
// Do not set a repeat count on a section
if brick.count(for: collection) != 1 {
fatalError("Repeat count on a section is not allowed (requested \(brick.count(for: collection))). Please use `CollectionBrick`")
}
BrickSection.addSection(§ionIndexPaths, sectionCount: §ionCount, bricks: sectionModel.bricks, repeatCountDataSource: sectionModel.repeatCountDataSource ?? repeatCountDataSource, atIndexPath: IndexPath(row: index, section: sectionId), in: collection)
}
index += brick.count(for: collection)
}
}
// Mark: - CustomStringConvertible
/// Convenience method to show description with an indentation
override internal func descriptionWithIndentationLevel(_ indentationLevel: Int) -> String {
var description = super.descriptionWithIndentationLevel(indentationLevel)
description += " inset: \(inset) edgeInsets: \(edgeInsets)"
var brickDescription = ""
for brick in bricks {
brickDescription += "\n"
brickDescription += "\(brick.descriptionWithIndentationLevel(indentationLevel + 1))"
}
description += brickDescription
return description
}
}
| apache-2.0 | 18f25e889d5461b003840763c9bc0038 | 42.485075 | 399 | 0.681826 | 5.097988 | false | false | false | false |
27629678/web_dev | client/Demo/websocket/WebSocketClient.swift | 1 | 2306 | //
// WebSocketClient.swift
// Demo
//
// Created by hzyuxiaohua on 2017/1/17.
// Copyright © 2017年 XY Network Co., Ltd. All rights reserved.
//
import Foundation
import SocketIO
import SocketRocket
class WebSocketClient {
private var socket: SocketIOClient? = nil
static var client: WebSocketClient = WebSocketClient()
public func connect(url: String) -> Bool {
socket = SocketIOClient(socketURL: URL(string: url)!, config: [.log(false), .forcePolling(false)]);
installHandler(withSocket: socket)
socket?.connect()
return true
}
public func write(data: Any?) {
var message: Data? = nil
if data is String {
message = (data as! String).data(using: .utf8)
} else if (data is Data) {
message = data as? Data
} else {
return
}
guard message != nil else {
return
}
socket?.emit("data", with: [message!])
}
private func installHandler(withSocket socket:SocketIOClient?) -> Void {
guard socket != nil else {
return
}
socket?.on("connect") { data, ack in
print("connection has established")
if ack.expected {
ack.with("hei, connected successfully.")
}
let ack = socket?.emitWithAck("register", with: ["xiaoming"])
ack?.timingOut(after: 20, callback: { (data) in
print("ack.res \(data[0])")
})
}
socket?.onAny { (event) in
print("recevie event:\(event)")
}
socket?.on("greeting", callback: { (data, ack) in
print("receive message:\(data)")
})
}
public func uploadFile(withPath path: String, complete: @escaping (Any, Error?) -> Void) {
let content = try! Data(contentsOf: URL(string: "file://" + path)!)
if content.count == 0 || socket?.status != .connected {
return
}
let ack = socket?.emitWithAck("bundle", with: ["bundle.zip", content])
ack?.timingOut(after: 30, callback: { (res) in
print("upload event res \(res)")
})
}
}
| mit | c33d402762b2252f44db4c494cc2d12d | 27.085366 | 107 | 0.521059 | 4.560396 | false | false | false | false |
miken01/SwiftData | SwiftData/Classes/SwiftDataManager.swift | 1 | 7250 | //
// SwiftDataManager.swift
// SwiftData
//
// Created by Mike Neill on 10/26/15.
// Copyright © 2015 Mike's App Shop. All rights reserved.
//
import Foundation
import CoreData
import os
class SwiftDataManager {
//MARK: - Singleton
static let sharedManager = SwiftDataManager()
//MARK: - Properties
var config: SwiftDataConfiguration?
lazy var managedObjectContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
fileprivate let saveQueue = DispatchQueue(label: "SwiftDataManager.saveQueue")
fileprivate let saveAndWaitQueue = DispatchQueue(label: "SwiftDataManager.saveAndWaitQueue")
private var modelName: String {
get {
if let v = config?.databaseFileName {
return v
}
return "SwiftData"
}
}
private var libraryDirectory: URL {
guard let path = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).last else {
os_log("[SwiftDataManager][databaseDirectory] databaseDirectory")
fatalError("Unable to obtain database directory URL")
}
return URL(fileURLWithPath: path)
}
private var databaseUrl: URL {
guard let appGroupName = config?.appGroupName else {
return libraryDirectory.appendingPathComponent(modelName + ".sqlite")
}
guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName) else {
fatalError("Unable to get AppGroup URL")
}
return url.appendingPathComponent(modelName + ".sqlite")
}
//MARK: - Initialization
required init() {
}
class func initialize(config: SwiftDataConfiguration) {
sharedManager.config = config
}
//MARK: - CoreData Stack Setup
lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: modelName)
let storeDescription = NSPersistentStoreDescription(url: databaseUrl)
container.persistentStoreDescriptions = [storeDescription]
weak var _container = container
container.loadPersistentStores {(storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
} else {
_container?.viewContext.automaticallyMergesChangesFromParent = true
_container?.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyStoreTrump
}
}
return container
}()
//MARK: Multiple MOCs
func registerBackgroundContext() -> NSManagedObjectContext {
let ctx = storeContainer.newBackgroundContext()
ctx.automaticallyMergesChangesFromParent = true
return ctx
}
//MARK: MISC
func logInfo(method: String, message: String) {
NSLog("[SwiftDataManager][\(method)] Info: \(message)")
}
func logError(method: String, message: String) {
NSLog("[SwiftDataManager][\(method)] Error: \(message)")
}
}
extension SwiftDataManager {
//MARK: - NSManagedObjectContext
func executeFetchRequest(fetchRequest: NSFetchRequest<NSFetchRequestResult>) -> AnyObject? {
do {
let results = try self.managedObjectContext.fetch(fetchRequest)
return results as AnyObject?
} catch let e as NSError {
self.logError(method: "executeFetchRequest", message: "\(e)")
return nil
}
}
func saveManagedObjectContext() {
saveQueue.async {[weak self] in
guard let moc = self?.managedObjectContext else {
return
}
guard moc.hasChanges else { return }
print("[SwiftDataManager][saveManagedObjectContext] Start save")
do {
print("[SwiftDataManager][saveManagedObjectContext] Try save")
try moc.save()
print("[SwiftDataManager][saveManagedObjectContext] Save complete")
} catch _ as NSError {
os_log("[SwiftDataManager][saveManagedObjectContext] Unable to save MOC")
// fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func saveManagedObjectContextAndWait() {
saveAndWaitQueue.sync {[weak self] in
guard let moc = self?.managedObjectContext else {
return
}
guard moc.hasChanges else { return }
print("[SwiftDataManager][saveManagedObjectContextAndWait] Start save")
moc.performAndWait {
do {
print("[SwiftDataManager][saveManagedObjectContextAndWait] Try save")
try moc.save()
print("[SwiftDataManager][saveManagedObjectContextAndWait] Save complete")
} catch _ as NSError {
os_log("[SwiftDataManager][saveManagedObjectContextAndWait] Unable to save MOC")
// fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
func save(managedObjectContext moc: NSManagedObjectContext) {
saveQueue.async {
print("[SwiftDataManager][save:managedObjectContext] Start save")
guard moc.hasChanges else { return }
do {
print("[SwiftDataManager][save:managedObjectContext] try save")
try moc.save()
print("[SwiftDataManager][save:managedObjectContext] Save complete")
} catch _ as NSError {
os_log("[SwiftDataManager][save:managedObjectContext] Unable to save MOC")
// fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func save(managedObjectContextAndWait moc: NSManagedObjectContext) {
saveAndWaitQueue.sync {
guard moc.hasChanges else { return }
print("[SwiftDataManager][save:managedObjectContext] Start save")
moc.performAndWait {
do {
print("[SwiftDataManager][save:managedObjectContextAndWait] try save")
try moc.save()
print("[SwiftDataManager][save:managedObjectContextAndWait] Save complete")
} catch _ as NSError {
os_log("[SwiftDataManager][save:managedObjectContextAndWait] Unable to save MOC")
// fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
func deleteObject(object: NSManagedObject) {
self.managedObjectContext.delete(object)
}
}
| gpl-3.0 | fb3147e1ef7ba86a11573d48589bf1f4 | 30.517391 | 116 | 0.568906 | 6.101852 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS | NoticiasLeganes/Position/Position.swift | 1 | 1320 | //
// Position.swift
// NoticiasLeganes
//
// Created by Alvaro Blazquez Montero on 16/6/17.
// Copyright © 2017 Alvaro Blazquez Montero. All rights reserved.
//
import UIKit
import SwiftyJSON
enum PositionKey: String {
case position, team, name , crestURI, points, playedGames
case wins = "won", draws = "draw", losses = "lost", standing = "standings"
case type, table, total = "TOTAL"
}
struct Position {
var position : Int = 0
var teamName : String = ""
var crestURI : String = ""
var points : Int = 0
var playedGames : Int = 0
var wins : Int = 0
var draws : Int = 0
var losses : Int = 0
}
extension Position {
init (json: JSON) {
self.init()
self.position = json[PositionKey.position.rawValue].intValue
self.teamName = json[PositionKey.team.rawValue][PositionKey.name.rawValue].stringValue
self.crestURI = json[PositionKey.crestURI.rawValue].stringValue
self.points = json[PositionKey.points.rawValue].intValue
self.playedGames = json[PositionKey.playedGames.rawValue].intValue
self.wins = json[PositionKey.wins.rawValue].intValue
self.draws = json[PositionKey.draws.rawValue].intValue
self.losses = json[PositionKey.losses.rawValue].intValue
}
}
| mit | 43e090d7cae016b419dfe3542f313faf | 31.170732 | 91 | 0.654284 | 3.574526 | false | false | false | false |
milseman/swift | test/PlaygroundTransform/array_did_set.swift | 15 | 1123 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
struct S {
var a : [Int] = [] {
didSet {
print("Set")
}
}
}
var s = S()
s.a = [3,2]
s.a.append(300)
// CHECK: [{{.*}}] $builtin_log[s='S(a: [])']
// CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry
// CHECK-NEXT: Set
// CHECK-NEXT: [{{.*}}] $builtin_postPrint
// CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit
// CHECK-NEXT: [{{.*}}] $builtin_log[s='S(a: [3, 2])']
// CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry
// CHECK-NEXT: Set
// CHECK-NEXT: [{{.*}}] $builtin_postPrint
// CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit
// CHECK-NEXT: [{{.*}}] $builtin_log[a='[3, 2, 300]']
| apache-2.0 | 1a8be23ef1e71e463204a53a12d36afe | 36.433333 | 197 | 0.60285 | 3.010724 | false | false | false | false |
y0ke/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Settings/AASettingsSessionsController.swift | 2 | 3054 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
public class AASettingsSessionsController: AAContentTableController {
private var sessionsCell: AAManagedArrayRows<ARApiAuthSession, AACommonCell>?
public init() {
super.init(style: AAContentTableStyle.SettingsGrouped)
navigationItem.title = AALocalized("SettingsAllSessions")
content = ACAllEvents_Settings.PRIVACY()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func tableDidLoad() {
section { (s) -> () in
s.footerText = AALocalized("PrivacyTerminateHint")
s.danger("PrivacyTerminate") { (r) -> () in
r.selectAction = { () -> Bool in
self.confirmDangerSheetUser("PrivacyTerminateAlert", tapYes: { [unowned self] () -> () in
// Terminating all sessions and reload list
self.executeSafe(Actor.terminateAllSessionsCommand(), successBlock: { (val) -> Void in
self.loadSessions()
})
}, tapNo: nil)
return true
}
}
}
section { (s) -> () in
self.sessionsCell = s.arrays() { (r: AAManagedArrayRows<ARApiAuthSession, AACommonCell>) -> () in
r.bindData = { (c: AACommonCell, d: ARApiAuthSession) -> () in
if d.getAuthHolder().ordinal() != ARApiAuthHolder.THISDEVICE().ordinal() {
c.style = .Normal
c.setContent(d.getDeviceTitle())
} else {
c.style = .Hint
c.setContent("(Current) \(d.getDeviceTitle())")
}
}
r.selectAction = { (d) -> Bool in
if d.getAuthHolder().ordinal() != ARApiAuthHolder.THISDEVICE().ordinal() {
self.confirmDangerSheetUser("PrivacyTerminateAlertSingle", tapYes: { [unowned self] () -> () in
// Terminating session and reload list
self.executeSafe(Actor.terminateSessionCommandWithId(d.getId()), successBlock: { [unowned self] (val) -> Void in
self.loadSessions()
})
}, tapNo: nil)
}
return true
}
}
}
// Request sessions load
loadSessions()
}
private func loadSessions() {
execute(Actor.loadSessionsCommand(), successBlock: { [unowned self] (val) -> Void in
self.sessionsCell!.data = (val as! JavaUtilList).toArray().toSwiftArray()
self.managedTable.tableView.reloadData()
}, failureBlock: nil)
}
}
| agpl-3.0 | 671965b9ae69d26388b2ad5ccaa0c971 | 37.175 | 140 | 0.495416 | 5.167513 | false | false | false | false |
joalbright/Gameboard | Games/BoardController/BoardViewController.swift | 1 | 4903 | //
// ViewController.swift
// Games
//
// Created by Jo Albright on 2/3/16.
// Copyright © 2016 Jo Albright. All rights reserved.
//
import UIKit
enum Direction: UInt {
case right = 1
case left = 2
case down = 8
case up = 4
var name: String {
switch self {
case .down: return "Down"
case .up: return "Up"
case .left: return "Left"
case .right: return "Right"
}
}
}
class BoardViewController: UIViewController {
@IBOutlet weak var boardView: BoardView!
@IBOutlet weak var playerLabel: UILabel!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
boardView?.board?.playerChange = { [weak self] player in self?.playerLabel?.text = "Player \(player)" }
boardView?.board?.showAlert = { [weak self] title, message in
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let resetAction = UIAlertAction(title: "Reset", style: .default) { [weak self] _ in
self?.boardView?.board?.reset()
self?.boardView?.updateBoard()
}
alertVC.addAction(resetAction)
// present VC
self?.present(alertVC, animated: true)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
guard let square = boardView?.coordinate(touch) else { return }
boardView?.selectSquare(square)
}
@IBAction func swipe(_ sender: UISwipeGestureRecognizer) {
guard let direction = Direction(rawValue: sender.direction.rawValue) else { return }
boardView?.swipe(direction)
}
// @IBAction func chooseDifficulty(sender: UISegmentedControl) {
//
// boardView?.board?.difficulty = Difficulty(sender.selectedSegmentIndex)
// boardView?.updateBoard()
//
// }
@IBAction func resetBoard(sender: Any) {
boardView?.board?.reset()
boardView?.updateBoard()
}
}
@IBDesignable class GradientView: UIView {
@IBInspectable var startColor: UIColor = .white
@IBInspectable var endColor: UIColor = .black
override func draw(_ rect: CGRect) {
let startPoint = CGPoint(x: 0, y: 0)
let endPoint = CGPoint(x: 1, y: 1)
let context = UIGraphicsGetCurrentContext()
let colors: CFArray = [startColor.cgColor,endColor.cgColor] as CFArray
guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors, locations: [0, 1]) else { return }
let s = CGPoint(x: frame.width * startPoint.x, y: frame.height * startPoint.y)
let e = CGPoint(x: frame.width * endPoint.x, y: frame.height * endPoint.y)
context?.drawLinearGradient(gradient, start: s, end: e, options: .drawsAfterEndLocation)
}
}
@IBDesignable class BoardView : UIView {
var board: Gameboard!
var boardView: UIView?
@IBInspectable var padding: CGFloat = 0
@IBInspectable var bgColor: UIColor = .white
@IBInspectable var fgColor: UIColor = .black
@IBInspectable var player1Color: UIColor = .systemRed
@IBInspectable var player2Color: UIColor = .systemBlue
@IBInspectable var selectedColor: UIColor = .white
@IBInspectable var highlightColor: UIColor = .white
override func prepareForInterfaceBuilder() { updateBoard() }
override func didMoveToWindow() { updateBoard() }
override func layoutSubviews() { updateBoard() }
func updateBoard() {
board?.padding = padding
board?.colors.background = bgColor
board?.colors.foreground = fgColor
board?.colors.player1 = player1Color
board?.colors.player2 = player2Color
board?.colors.selected = selectedColor
board?.colors.highlight = highlightColor
boardView?.removeFromSuperview()
boardView = board?.visualize(bounds)
guard let boardView = boardView else { return }
addSubview(boardView)
}
func coordinate(_ touch: UITouch) -> Square? {
guard let board = board else { return nil }
let w = (frame.width - board.padding * 2) / board.gridSize
let h = (frame.height - board.padding * 2) / board.gridSize
let loc = touch.location(in: self)
let c = Int((loc.x - board.padding) / w)
let r = Int((loc.y - board.padding) / h)
return (r,c)
}
func selectSquare(_ square: Square) { }
func swipe(_ direction: Direction) { }
func checkDone() { }
}
| apache-2.0 | 6ff57ab33b6477945671fb516da8e30a | 27.011429 | 134 | 0.594859 | 4.650854 | false | false | false | false |
PunchThrough/bean-ibeacon-demo-ios | Bean iB Demo/ViewController.swift | 1 | 1453 | //
// ViewController.swift
// Bean iB Demo
//
// Created by Matthew Lewis on 12/18/15.
// Copyright © 2015 Punch Through Design. All rights reserved.
//
import UIKit
class ViewController: UIViewController, BeaconInfoDelegate {
// MARK: - Interface Builder
@IBOutlet var container: UIView!
@IBOutlet weak var insideRegionLabel: UILabel!
@IBOutlet weak var beaconCountLabel: UILabel!
@IBOutlet weak var beaconsFoundLabel: UILabel!
// MARK: - UIViewController
override func viewDidLoad() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.delegate = self
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
// MARK: - BeaconInfoDelegate
func foundBeacons(num: Int) {
beaconCountLabel.text = "\(num)"
if (num == 1) {
beaconsFoundLabel.text = "iBeacon found"
} else {
beaconsFoundLabel.text = "iBeacons found"
}
}
func enteredRegion() {
insideRegionLabel.text = "Inside region"
self.view.backgroundColor = UIColor(red:0.18, green:0.80, blue:0.44, alpha:1.0) // Flat UI: Emerald
}
func exitedRegion() {
insideRegionLabel.text = "Outside region"
self.view.backgroundColor = UIColor(red:0.20, green:0.60, blue:0.86, alpha:1.0) // Flat UI: Peter River
}
}
| mit | 09deb085eaa7fdbf6dcf94b73a33cd93 | 26.923077 | 112 | 0.634298 | 4.233236 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPressKit/WordPressKit/RemotePlan.swift | 2 | 2543 | import Foundation
public typealias PricedPlan = (plan: RemotePlan, price: String)
public typealias SitePricedPlans = (siteID: Int, activePlan: RemotePlan, availablePlans: [PricedPlan])
public typealias RemotePlanFeatures = [PlanID: [RemotePlanFeature]]
public typealias PlanID = Int
/// Represents a WordPress.com free or paid plan.
/// - seealso: [WordPress.com Store](https://store.wordpress.com/plans/)
public struct RemotePlan {
public let id: PlanID
public let title: String
public let fullTitle: String
public let tagline: String
public let iconUrl: URL
public let activeIconUrl: URL
public let productIdentifier: String?
public let featureGroups: [RemotePlanFeatureGroupPlaceholder]
public init(id: PlanID, title: String, fullTitle: String, tagline: String,
iconUrl: URL, activeIconUrl: URL, productIdentifier: String?,
featureGroups: [RemotePlanFeatureGroupPlaceholder]) {
self.id = id
self.title = title
self.fullTitle = fullTitle
self.tagline = tagline
self.iconUrl = iconUrl
self.activeIconUrl = activeIconUrl
self.productIdentifier = productIdentifier
self.featureGroups = featureGroups
}
}
extension RemotePlan {
public var isFreePlan: Bool {
return productIdentifier == nil
}
public var isPaidPlan: Bool {
return !isFreePlan
}
}
extension RemotePlan: Equatable {}
public func == (lhs: RemotePlan, rhs: RemotePlan) -> Bool {
return lhs.id == rhs.id
}
extension RemotePlan: Hashable {
public var hashValue: Int {
return id.hashValue
}
}
extension RemotePlan: Comparable {}
public func < (lhs: RemotePlan, rhs: RemotePlan) -> Bool {
return lhs.id < rhs.id
}
protocol Identifiable {
var id: Int { get }
}
extension RemotePlan: Identifiable {}
extension Array where Element: Identifiable {
func withID(_ searchID: Int) -> Element? {
return filter({ $0.id == searchID }).first
}
}
public struct RemotePlanFeature {
public let slug: String
public let title: String
public let description: String
public let iconURL: URL?
}
public struct RemotePlanFeatureGroupPlaceholder {
public let title: String?
public let slugs: [String]
}
public struct RemotePlanFeatureGroup {
public var title: String?
public var features: [RemotePlanFeature]
public init(title: String?, features: [RemotePlanFeature]) {
self.title = title;
self.features = features;
}
}
| gpl-2.0 | 6d08ce2e8cc3279dce522e0e47fcad65 | 26.641304 | 102 | 0.686591 | 4.203306 | false | false | false | false |
jvesala/teknappi | teknappi/teknappi/AppDelegate.swift | 1 | 2936 | //
// AppDelegate.swift
// teknappi
//
// Created by Jussi Vesala on 9.11.2015.
// Copyright © 2015 Jussi Vesala. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let window = window {
UserDataRepository.reset()
let tabBarController = UITabBarController()
let tabBarHeight = tabBarController.tabBar.frame.size.height
let myVC1 = ContactRequestViewController(tabBarHeight: tabBarHeight)
myVC1.tabBarItem = UITabBarItem(title: "Yhteydenotto", image: UIImage(named: "phone"), tag: 1)
let myVC2 = UserDataViewController(tabBarHeight: tabBarHeight)
myVC2.tabBarItem = UITabBarItem(title: "Omat tiedot", image: UIImage(named: "man"), tag: 2)
let controllers = [myVC1, myVC2]
tabBarController.viewControllers = controllers
window.rootViewController = tabBarController
window.makeKeyAndVisible()
}
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:.
}
}
| gpl-3.0 | 058c94627a700a7b2b2168fe6592e3f9 | 44.153846 | 285 | 0.721635 | 5.326679 | false | false | false | false |
syxc/ZhihuDaily | ZhihuDaily/Classes/Controllers/Base/FYNavigationController.swift | 1 | 2541 | //
// FYNavigationController.swift
// ZhihuDaily
//
// Created by syxc on 16/2/2.
// Copyright © 2016年 syxc. All rights reserved.
//
import UIKit
class FYNavigationController: UINavigationController,
UIGestureRecognizerDelegate, UINavigationControllerDelegate {
// MARK: StatusBarStyle
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return super.preferredStatusBarStyle()
}
override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
return super.preferredStatusBarUpdateAnimation()
}
override func prefersStatusBarHidden() -> Bool {
return super.prefersStatusBarHidden()
}
override func viewDidLoad() {
weak var weakSelf = self
if self.respondsToSelector(Selector("interactivePopGestureRecognizer")) {
self.interactivePopGestureRecognizer?.delegate = weakSelf
self.delegate = weakSelf
}
}
override func pushViewController(viewController: UIViewController, animated: Bool) {
if self.respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated {
self.interactivePopGestureRecognizer?.enabled = false
}
super.pushViewController(viewController, animated: animated)
}
override func popToRootViewControllerAnimated(animated: Bool) -> [UIViewController]? {
if self.respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated {
self.interactivePopGestureRecognizer?.enabled = false
}
return super.popToRootViewControllerAnimated(animated)
}
override func popToViewController(viewController: UIViewController, animated: Bool) -> [UIViewController]? {
if self.respondsToSelector(Selector("interactivePopGestureRecognizer")) {
self.interactivePopGestureRecognizer?.enabled = false
}
return super.popToViewController(viewController, animated: animated)
}
// MARK: UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
if self.respondsToSelector(Selector("interactivePopGestureRecognizer")) {
self.interactivePopGestureRecognizer?.enabled = true
}
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.interactivePopGestureRecognizer {
if self.viewControllers.count < 2 || self.visibleViewController == self.viewControllers[0] {
return false
}
}
return true
}
}
| mit | 475f99baf46d2cafb1fc744a7211cadd | 31.126582 | 147 | 0.748227 | 6.115663 | false | false | false | false |
mumbler/PReVo-iOS | PoshReVo/Subaj Paghoj/Artikoloj/ArtikoloViewController.swift | 1 | 19870 | //
// ArtikoloViewController.swift
// PoshReVo
//
// Created by Robin Hill on 3/11/16.
// Copyright © 2016 Robin Hill. All rights reserved.
//
import Foundation
import UIKit
import TTTAttributedLabel
import ReVoModeloj
import ReVoDatumbazo
let subArtikolChelIdent = "subArtikolaChelo"
let artikolChelIdent = "artikolaChelo"
let artikolKapIdent = "artikolaKapo"
let artikolPiedIdent = "artikolaPiedo"
let artikolNevideblaPiedoIdent = "artikolaNevideblaPiedo"
/*
Pagho kiu montras la artikolojn kun difinoj kaj tradukoj
*/
class ArtikoloViewController : UIViewController, Stilplena {
private enum ChelSpeco {
case Vorto(titolo: String, teksto: String), GrupKapo(titolo: String?, teksto: String?), Traduko(titolo: String, teksto: String)
}
@IBOutlet var vortTabelo: UITableView?
var artikolo: Artikolo? = nil
var tradukListo: [Traduko]? = nil
var konservitaMarko: String? = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init?(enartikolo: Artikolo) {
super.init(nibName: "ArtikoloViewController", bundle: nil)
artikolo = enartikolo
}
init?(enartikolo: Artikolo, enmarko: String) {
super.init(nibName: "ArtikoloViewController", bundle: nil)
artikolo = enartikolo
konservitaMarko = enmarko
}
override func viewDidLoad() {
prepariTradukListon()
prepariNavigaciajnButonojn()
title = (artikolo?.titolo ?? "") + Iloj.superLit((artikolo?.ofc ?? ""))
vortTabelo?.contentInset = UIEdgeInsets(top: -1, left: 0, bottom: 0, right: 0)
automaticallyAdjustsScrollViewInsets = false
if #available(iOS 11.0, *) {
vortTabelo?.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
}
vortTabelo?.delegate = self
vortTabelo?.dataSource = self
vortTabelo?.register(UINib(nibName: "ArtikoloTableViewCell", bundle: nil), forCellReuseIdentifier: artikolChelIdent)
vortTabelo?.register(UINib(nibName: "SubArtikoloTableViewCell", bundle: nil), forCellReuseIdentifier: subArtikolChelIdent)
vortTabelo?.register(UINib(nibName: "ArtikoloKapoTableViewHeaderFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: artikolKapIdent)
vortTabelo?.register(UINib(nibName: "ArtikoloPiedButonoTableViewHeaderFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: artikolPiedIdent)
NotificationCenter.default.addObserver(self, selector: #selector(elektisTradukLingvojn), name: NSNotification.Name(rawValue: AtentigoNomoj.elektisTradukLingvojn), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeDidChange(forChildContentContainer:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
efektivigiStilon()
}
override func viewWillAppear(_ animated: Bool) {
if konservitaMarko != nil {
DispatchQueue.main.async { [weak self] in
self?.saltiAlMarko(self?.konservitaMarko ?? "", animacii: false)
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let veraArtikolo = artikolo {
UzantDatumaro.visitisPaghon(Listero(veraArtikolo.titolo, veraArtikolo.indekso))
}
}
// MARK: - View-agordado
func prepariNavigaciajnButonojn() {
// Por meti du butonoj malproksime unu al la alia, oni devas krei UIView kiu enhavas
// du UIButton-ojn, kaj uzi tion kiel la vera rightBarButtonItem
let butonujo = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 30))
// Elekti plena stelo se la artikolo estas konservia, alie la malplena
let bildo = UzantDatumaro.konservitaj.contains { (nuna: Listero) -> Bool in
return nuna.indekso == artikolo?.indekso
} ? UIImage(named: "pikto_stelo_plena") : UIImage(named: "pikto_stelo")
let konservButono = UIButton()
konservButono.tintColor = UzantDatumaro.stilo.navTintKoloro
konservButono.setImage(bildo?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate), for: .normal)
konservButono.addTarget(self, action: #selector(premisKonservButonon), for: UIControl.Event.touchUpInside)
konservButono.imageView?.contentMode = .scaleAspectFit
let serchButono = UIButton()
serchButono.tintColor = UzantDatumaro.stilo.navTintKoloro
serchButono.setImage(UIImage(named: "pikto_lupeo")?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate), for: .normal)
serchButono.addTarget(self, action: #selector(premisSerchButonon), for: .touchUpInside)
serchButono.contentHorizontalAlignment = .right
butonujo.addSubview(konservButono)
butonujo.addSubview(serchButono)
serchButono.frame = CGRect(x: 34, y: 0, width: 36, height: 30)
konservButono.frame = CGRect(x: 0, y: 0, width: 34, height: 30)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: butonujo)
}
// Krei liston de tradukoj por montri - tiuj kiuj estas kaj en la listo de
// tradukoj por la artikolo kaj la elektitaj traduk-lingvoj
func prepariTradukListon() {
tradukListo = [Traduko]()
for traduko in artikolo?.tradukoj ?? [] {
if UzantDatumaro.tradukLingvoj.contains(traduko.lingvo) {
tradukListo?.append(traduko)
}
}
tradukListo?.sort(by: { (unua: Traduko, dua: Traduko) -> Bool in
return unua.lingvo.nomo.compare(dua.lingvo.nomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
})
}
// MARK: - Stilplena
func efektivigiStilon() {
navigationController?.navigationBar.tintColor = UzantDatumaro.stilo.navTintKoloro
vortTabelo?.backgroundColor = UzantDatumaro.stilo.fonKoloro
vortTabelo?.indicatorStyle = UzantDatumaro.stilo.scrollKoloro
vortTabelo?.reloadData()
}
// MARK: - Paĝ-agoj
// Haste movi la ekranon al la dezirata vorto en la artikolo
func saltiAlMarko(_ marko: String, animacii: Bool) {
var sumo = 0
for subartikolo in artikolo?.subartikoloj ?? [] {
if artikolo?.subartikoloj.count ?? 0 > 1 { sumo += 1 }
for vorto in subartikolo.vortoj {
if vorto.marko == marko {
vortTabelo?.scrollToRow(at: IndexPath(row: sumo, section: 0), at: .top, animated: animacii)
return
}
sumo += 1
}
}
}
// MARK: - UI agoj
// Reiri al la ingo pagho kaj igi ghin montri la serch-paghon
@objc func premisSerchButonon() {
if let ingo = (navigationController as? ChefaNavigationController)?.viewControllers.first as? IngoPaghoViewController {
ingo.montriPaghon(Pagho.Serchi)
}
navigationController?.popToRootViewController(animated: true)
}
// Konservi au malkonservi la artikolon
@objc func premisKonservButonon() {
UzantDatumaro.shanghiKonservitecon(artikolo: Listero(artikolo!.titolo, artikolo!.indekso))
prepariNavigaciajnButonojn()
}
// Montri la traduk-lingvoj elektilon
@objc func premisPliajnTradukojnButonon() {
let navigaciilo = HelpaNavigationController()
let elektilo = TradukLingvojElektiloTableViewController(style: .grouped)
navigaciilo.viewControllers.append(elektilo)
navigationController?.present(navigaciilo, animated: true, completion: nil)
}
@objc func premisChelon(_ rekonilo: UILongPressGestureRecognizer) {
if let chelo = rekonilo.view as? ArtikoloTableViewCell, rekonilo.state == .began {
let mesagho: UIAlertController = UIAlertController(title: NSLocalizedString("artikolo chelo agoj titolo", comment: ""), message: nil, preferredStyle: .actionSheet)
mesagho.addAction( UIAlertAction(title: NSLocalizedString("artikolo chelo ago kopii", comment: ""), style: .default, handler: { (ago: UIAlertAction) -> Void in
let tabulo = UIPasteboard.general
tabulo.string = chelo.chefaEtikedo?.text as? String ?? ""
}))
mesagho.addAction( UIAlertAction(title: NSLocalizedString("Nenio", comment: ""), style: .cancel, handler: nil))
if let prezentilo = mesagho.popoverPresentationController {
prezentilo.sourceView = chelo;
prezentilo.sourceRect = chelo.bounds;
}
present(mesagho, animated: true, completion: nil)
}
}
@objc func elektisTradukLingvojn() {
prepariTradukListon()
vortTabelo?.reloadSections(IndexSet(integer: 1), with: .fade)
if vortTabelo?.numberOfRows(inSection: 1) ?? 0 > 0 {
vortTabelo?.scrollToRow(at: IndexPath(row: 0, section: 1), at: .top, animated: true)
}
}
}
// MARK: - UITableViewDelegate & UITableViewDataSource
extension ArtikoloViewController : UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
let tradukSumo = artikolo?.tradukoj.count ?? 0, videblaSumo = tradukListo?.count ?? 0
return 1 + ((videblaSumo > 0 || tradukSumo - videblaSumo > 0) ? 1 : 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rez = 0
if section == 0 {
for subartikolo in artikolo!.subartikoloj {
if artikolo?.subartikoloj.count ?? 0 > 1 { rez += 1 }
rez += subartikolo.vortoj.count
}
return rez
} else if section == 1 {
rez = tradukListo?.count ?? 0
}
return rez
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let artikolo = artikolo else { fatalError("Devas esti artikolo") }
let chelSpeco: ChelSpeco
if indexPath.section == 0 {
if artikolo.subartikoloj.count == 1 {
let subartikolo = artikolo.subartikoloj.first!
let vorto = subartikolo.vortoj[indexPath.row]
chelSpeco = .Vorto(titolo: vorto.kunaTitolo, teksto: vorto.teksto)
}
else {
if let vorto = vortoDeIndexPath(indexPath) {
chelSpeco = .Vorto(titolo: vorto.kunaTitolo, teksto: vorto.teksto)
}
else if let grupTeksto = grupTekstoDeIndexPath(indexPath) {
chelSpeco = .GrupKapo(titolo: nil, teksto: grupTeksto)
}
else {
fatalError("AHH")
}
}
} else if indexPath.section == 1,
let traduko = tradukListo?[indexPath.row] {
chelSpeco = .Traduko(titolo: traduko.lingvo.nomo, teksto: traduko.teksto)
} else {
fatalError("Sekcia numero malvalidas")
}
switch chelSpeco {
case .Vorto(let titolo, let teksto):
let novaChelo = tableView.dequeueReusableCell(withIdentifier: artikolChelIdent, for: indexPath) as! ArtikoloTableViewCell
pretigiArtikolaChelo(chelo: novaChelo, titolo: titolo, teksto: teksto)
return novaChelo
case .GrupKapo(let titolo, let teksto):
let novaChelo = tableView.dequeueReusableCell(withIdentifier: subArtikolChelIdent, for: indexPath) as! SubArtikoloTableViewCell
pretigiSubArtikolaChelo(chelo: novaChelo, titolo: titolo, teksto: teksto, unua: indexPath.row == 0)
return novaChelo
case .Traduko(let titolo, let teksto):
let novaChelo = tableView.dequeueReusableCell(withIdentifier: artikolChelIdent, for: indexPath) as! ArtikoloTableViewCell
pretigiArtikolaChelo(chelo: novaChelo, titolo: titolo, teksto: teksto)
return novaChelo
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return nil
}
let novaKapo: ArtikoloKapoTableViewHeaderFooterView
if let trovKapo = vortTabelo?.dequeueReusableHeaderFooterView(withIdentifier: artikolKapIdent) as? ArtikoloKapoTableViewHeaderFooterView {
novaKapo = trovKapo
} else {
novaKapo = ArtikoloKapoTableViewHeaderFooterView()
}
if section == 1 {
novaKapo.prepari()
novaKapo.etikedo?.text = NSLocalizedString("artikolo tradukoj etikedo", comment: "")
}
return novaKapo
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 0 && tableView.numberOfSections > 1 {
if let trovPiedo = vortTabelo?.dequeueReusableHeaderFooterView(withIdentifier: artikolNevideblaPiedoIdent) as? ArtikoloNevideblaTableHeaderFooterView {
return trovPiedo
}
return ArtikoloNevideblaTableHeaderFooterView(frame: .zero)
}
else if section == 1 && artikolo?.tradukoj.count ?? 0 > 0 {
let novaPiedo: ArtikoloPiedButonoTableViewHeaderFooterView
if let trovPiedo = vortTabelo?.dequeueReusableHeaderFooterView(withIdentifier: artikolPiedIdent) as? ArtikoloPiedButonoTableViewHeaderFooterView {
novaPiedo = trovPiedo
} else {
novaPiedo = ArtikoloPiedButonoTableViewHeaderFooterView()
}
novaPiedo.prepari()
novaPiedo.butono?.addTarget(self, action: #selector(premisPliajnTradukojnButonon), for: .touchUpInside)
return novaPiedo
}
return nil
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 1 {
return UITableView.automaticDimension
}
return 1
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 && tableView.numberOfSections > 1 {
return 16
}
else if section == 1 {
let desc = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
return 50 + desc.pointSize - 14
}
return 1
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
if section == 1 {
return 32
}
return 0
}
func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
if section == 0 && tableView.numberOfSections > 1 {
return 16
}
else if section == 1 {
let desc = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
return 50 + desc.pointSize - 14
}
return 0
}
}
// MARK: - Chelo-starigado
extension ArtikoloViewController {
private func pretigiArtikolaChelo(chelo: ArtikoloTableViewCell, titolo: String, teksto: String) {
chelo.prepari(titolo: titolo, teksto: teksto)
chelo.chefaEtikedo?.delegate = self
pretigiChelAccessibility(chelo: chelo, titolo: titolo, teksto: teksto)
pretigiRekonilon(por: chelo)
}
private func pretigiSubArtikolaChelo(chelo: SubArtikoloTableViewCell, titolo: String?, teksto: String?, unua: Bool = false) {
chelo.prepari(titolo: titolo, teksto: teksto, unua: unua)
chelo.chefaEtikedo?.delegate = self
pretigiChelAccessibility(chelo: chelo, titolo: titolo, teksto: teksto)
pretigiRekonilon(por: chelo)
}
private func pretigiChelAccessibility(chelo: UITableViewCell, titolo: String?, teksto: String?) {
chelo.isAccessibilityElement = true
if titolo == nil || teksto == nil {
chelo.accessibilityLabel = titolo ?? teksto
}
else if let titolo = titolo,
let teksto = teksto {
chelo.accessibilityLabel = [titolo, teksto].joined(separator: ",")
}
}
private func pretigiRekonilon(por chelo: UITableViewCell) {
for rekonilo in chelo.gestureRecognizers ?? [] {
chelo.removeGestureRecognizer(rekonilo)
}
let rekonilo = UILongPressGestureRecognizer(target: self, action: #selector(premisChelon(_:)))
chelo.addGestureRecognizer(rekonilo)
}
}
// MARK: - TTTAttributedLabelDelegate
extension ArtikoloViewController : TTTAttributedLabelDelegate {
// Uzanto premis ligilon - iri al la dezirata sekcio de la artikolo, au montri novan artikolon
func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL?) {
let marko = url?.absoluteString ?? ""
let partoj = marko.components(separatedBy: ".")
if partoj.count == 0 {
return
}
if partoj[0] == artikolo?.indekso {
if partoj.count >= 2 {
saltiAlMarko(partoj[0] + "." + partoj[1], animacii: true)
}
} else {
if let artikolo = VortaroDatumbazo.komuna.artikolo(porIndekso: partoj[0]) {
navigationItem.backBarButtonItem = UIBarButtonItem(title: self.artikolo?.titolo, style: .plain, target: nil, action: nil)
(self.navigationController as? ChefaNavigationController)?.montriArtikolon(artikolo, marko: marko)
}
}
}
}
// MARK: - Helpiloj
extension ArtikoloViewController {
private func vortoDeIndexPath(_ indexPath: IndexPath) -> Vorto? {
guard let artikolo = artikolo else { fatalError("Devas esti artikolo") }
var sumo = 0
for subartikolo in artikolo.subartikoloj {
if sumo == indexPath.row {
return nil
}
if indexPath.row < sumo + subartikolo.vortoj.count + 1 {
return subartikolo.vortoj[indexPath.row - sumo - 1]
}
sumo += subartikolo.vortoj.count + 1
}
return nil
}
private func grupTekstoDeIndexPath(_ indexPath: IndexPath) -> String? {
guard let artikolo = artikolo else { fatalError("Devas esti artikolo") }
var sumo = 0
for subartikolo in artikolo.subartikoloj {
if sumo == indexPath.row {
return subartikolo.teksto
}
if indexPath.row < sumo + subartikolo.vortoj.count + 1 {
return nil
}
sumo += subartikolo.vortoj.count + 1
}
return nil
}
// Respondi al mediaj shanghoj
func didChangePreferredContentSize(notification: NSNotification) -> Void {
vortTabelo?.reloadData()
}
}
| mit | 83b341019251fd756841db37439020c9 | 37.4294 | 195 | 0.620495 | 4.093962 | false | false | false | false |
AlesTsurko/DNMKit | DNMModel/SpannerArguments.swift | 1 | 593 | //
// SpannerArguments.swift
// DNMModel
//
// Created by James Bean on 11/6/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import Foundation
public struct SpannerArguments {
public var exponent: Float = 1
// is there a memory advantage to using []? rather than [] ... ?
public var widthArgs: [Float] = []
public var dashArgs: [Float] = []
public var colorArgs: [(Float, Float, Float)] = []
public var zigZagArgs: [Float] = []
public var waveArgs: [Float] = []
public var controlPointArgs: [Float] = []
public init() { }
} | gpl-2.0 | 5aa4d29225c41a2c9d68523f259151c2 | 23.708333 | 68 | 0.614865 | 3.72327 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Controllers/Chat/ChatButton.swift | 1 | 4454 | import UIKit
final class ChatButton: UIButton {
var title: String? {
didSet {
buttonTitleLabel.text = title
}
}
var shouldShowArrow: Bool = false {
didSet {
arrowImageView.isHidden = !shouldShowArrow
if shouldShowArrow {
titleToRightConstraint?.isActive = false
titleToArrowConstraint?.isActive = true
} else {
titleToArrowConstraint?.isActive = false
titleToRightConstraint?.isActive = true
}
}
}
var leftImage: UIImage? {
didSet {
if let image = leftImage {
leftImageView.image = image
leftImageView.isHidden = false
titleToLeftConstraint?.isActive = false
titleToLeftImageConstraint?.isActive = true
leftImageWidthConstraint?.constant = image.size.width
leftImageHeightConstraint?.constant = image.size.height
} else {
leftImageView.isHidden = true
titleToLeftConstraint?.isActive = true
titleToLeftImageConstraint?.isActive = false
leftImageWidthConstraint?.constant = 0
leftImageHeightConstraint?.constant = 0
}
}
}
private lazy var buttonTitleLabel: UILabel = {
let view = UILabel()
view.font = Theme.preferredRegular()
view.textColor = Theme.tintColor
view.adjustsFontForContentSizeCategory = true
return view
}()
private lazy var arrowImageView: UIImageView = {
let view = UIImageView()
view.image = ImageAsset.chat_buttons_arrow.withRenderingMode(.alwaysTemplate)
view.tintColor = Theme.tintColor
view.isHidden = true
return view
}()
private lazy var leftImageView: UIImageView = {
let view = UIImageView()
view.isHidden = true
view.tintColor = Theme.tintColor
return view
}()
private var titleToLeftConstraint: NSLayoutConstraint?
private var titleToLeftImageConstraint: NSLayoutConstraint?
private var titleToRightConstraint: NSLayoutConstraint?
private var titleToArrowConstraint: NSLayoutConstraint?
private var leftImageHeightConstraint: NSLayoutConstraint?
private var leftImageWidthConstraint: NSLayoutConstraint?
override init(frame: CGRect) {
super.init(frame: frame)
layer.borderColor = Theme.tintColor.cgColor
layer.borderWidth = 1
layer.cornerRadius = 18
clipsToBounds = true
let layoutGuide = UILayoutGuide()
addLayoutGuide(layoutGuide)
addSubview(leftImageView)
addSubview(buttonTitleLabel)
addSubview(arrowImageView)
layoutGuide.centerX(to: self)
layoutGuide.top(to: self)
layoutGuide.bottom(to: self)
layoutGuide.left(to: self, relation: .equalOrGreater)
layoutGuide.right(to: self, relation: .equalOrLess)
leftImageView.centerY(to: layoutGuide)
leftImageView.left(to: layoutGuide, offset: 15)
leftImageHeightConstraint = leftImageView.height(0)
leftImageWidthConstraint = leftImageView.width(0)
buttonTitleLabel.top(to: layoutGuide, offset: 8)
buttonTitleLabel.bottom(to: layoutGuide, offset: -8)
titleToLeftConstraint = buttonTitleLabel.left(to: layoutGuide, offset: 15)
titleToLeftImageConstraint = buttonTitleLabel.leftToRight(of: leftImageView, offset: 5, isActive: false)
titleToRightConstraint = buttonTitleLabel.right(to: layoutGuide, offset: -15)
titleToArrowConstraint = buttonTitleLabel.rightToLeft(of: arrowImageView, offset: -5, isActive: false)
arrowImageView.centerY(to: layoutGuide)
arrowImageView.right(to: layoutGuide, offset: -15)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setTintColor(_ color: UIColor) {
layer.borderColor = color.cgColor
arrowImageView.tintColor = color
leftImageView.tintColor = color
buttonTitleLabel.textColor = color
}
override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
buttonTitleLabel.font = Theme.preferredRegular()
}
}
| gpl-3.0 | 7e826814db7e8115d7f01dfc859be9dd | 31.043165 | 112 | 0.650651 | 5.505562 | false | false | false | false |
modocache/swift | test/type/protocol_composition.swift | 1 | 5389 | // RUN: %target-parse-verify-swift
func canonical_empty_protocol() -> Any {
return 1
}
protocol P1 {
func p1()
func f(_: Int) -> Int
}
protocol P2 : P1 {
func p2()
}
protocol P3 {
func p3()
}
protocol P4 : P3 {
func p4()
func f(_: Double) -> Double
}
typealias Any1 = protocol<> // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}}
typealias Any2 = protocol< > // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}}
// Okay to inherit a typealias for Any type.
protocol P5 : Any { }
protocol P6 : protocol<> { } // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}}
// expected-error@-1 {{protocol composition is neither allowed nor needed here}}
typealias P7 = Any & Any1
extension Int : P5 { }
typealias Bogus = P1 & Int // expected-error{{non-protocol type 'Int' cannot be used within a protocol composition}}
func testEquality() {
// Remove duplicates from protocol-conformance types.
let x1 : (_ : P2 & P4) -> ()
let x2 : (_ : P3 & P4 & P2 & P1) -> ()
x1 = x2
_ = x1
// Singleton protocol-conformance types, after duplication, are the same as
// simply naming the protocol type.
let x3 : (_ : P2 & P1) -> ()
let x4 : (_ : P2) -> ()
x3 = x4
_ = x3
// Empty protocol-conformance types are empty.
let x5 : (_ : Any) -> ()
let x6 : (_ : Any2) -> ()
x5 = x6
_ = x5
let x7 : (_ : P1 & P3) -> ()
let x8 : (_ : P2) -> ()
x7 = x8 // expected-error{{cannot assign value of type '(P2) -> ()' to type '(P1 & P3) -> ()'}}
_ = x7
}
// Name lookup into protocol-conformance types
func testLookup() {
let x1 : P2 & P1 & P4
x1.p1()
x1.p2()
x1.p3()
x1.p4()
var _ : Int = x1.f(1)
var _ : Double = x1.f(1.0)
}
protocol REPLPrintable {
func replPrint()
}
protocol SuperREPLPrintable : REPLPrintable {
func superReplPrint()
}
protocol FooProtocol {
func format(_ kind: UnicodeScalar, layout: String) -> String
}
struct SuperPrint : REPLPrintable, FooProtocol, SuperREPLPrintable {
func replPrint() {}
func superReplPrint() {}
func format(_ kind: UnicodeScalar, layout: String) -> String {}
}
struct Struct1 {}
extension Struct1 : REPLPrintable, FooProtocol {
func replPrint() {}
func format(_ kind: UnicodeScalar, layout: String) -> String {}
}
func accept_manyPrintable(_: REPLPrintable & FooProtocol) {}
func return_superPrintable() -> FooProtocol & SuperREPLPrintable {}
func testConversion() {
// Conversions for literals.
var x : REPLPrintable & FooProtocol = Struct1()
accept_manyPrintable(Struct1())
// Conversions for nominal types that conform to a number of protocols.
let sp : SuperPrint
x = sp
accept_manyPrintable(sp)
// Conversions among existential types.
var x2 : protocol<SuperREPLPrintable, FooProtocol> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{12-53=SuperREPLPrintable & FooProtocol}}
x2 = x // expected-error{{value of type 'FooProtocol & REPLPrintable' does not conform to 'FooProtocol & SuperREPLPrintable' in assignment}}
x = x2
// Subtyping
var _ : () -> FooProtocol & SuperREPLPrintable = return_superPrintable
// FIXME: closures make ABI conversions explicit. rdar://problem/19517003
var _ : () -> protocol<FooProtocol, REPLPrintable> = { return_superPrintable() } // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{17-53=FooProtocol & REPLPrintable}}
}
// Test the parser's splitting of >= into > and =.
var x : protocol<P5>= 17 // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{9-22=P5=}}
var y : protocol<P5, P7>= 17 // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{9-26=(P5 & P7)=}}
typealias A1 = protocol<> // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}} {{16-26=Any}}
typealias A2 = protocol<>? // expected-warning {{'protocol<>' syntax is deprecated; use 'Any' instead}} {{16-27=Any?}}
typealias B1 = protocol<P1,P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-31=P1 & P2}}
typealias B2 = protocol<P1, P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-32=P1 & P2}}
typealias B3 = protocol<P1 ,P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-32=P1 & P2}}
typealias B4 = protocol<P1 , P2> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} {{16-33=P1 & P2}}
typealias C1 = protocol<Any, P1> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{16-33=P1}}
typealias C2 = protocol<P1, Any> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{16-33=P1}}
typealias D = protocol<P1> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{15-27=P1}}
typealias E = protocol<Any> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{15-28=Any}}
typealias F = protocol<Any, Any> // expected-warning {{'protocol<...>' composition syntax is deprecated and not needed here}} {{15-33=Any}}
| apache-2.0 | 68bb10e6a3d91dfb4d5ab529fa32cf49 | 37.769784 | 223 | 0.664502 | 3.691096 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/EnterAmount/EnterAmountPageBuilder.swift | 1 | 8707 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainNamespace
import DIKit
import Localization
import PlatformKit
import PlatformUIKit
import RIBs
import RxCocoa
import RxSwift
import ToolKit
import UIKit
protocol EnterAmountPageBuildable {
func build(
listener: EnterAmountPageListener,
sourceAccount: SingleAccount,
destinationAccount: TransactionTarget,
action: AssetAction,
navigationModel: ScreenNavigationModel
) -> EnterAmountPageRouter
}
final class EnterAmountPageBuilder: EnterAmountPageBuildable {
private let fiatCurrencyService: FiatCurrencyServiceAPI
private let transactionModel: TransactionModel
private let priceService: PriceServiceAPI
private let analyticsEventRecorder: AnalyticsEventRecorderAPI
private let app: AppProtocol
init(
transactionModel: TransactionModel,
priceService: PriceServiceAPI = resolve(),
fiatCurrencyService: FiatCurrencyServiceAPI = resolve(),
exchangeProvider: ExchangeProviding = resolve(),
analyticsEventRecorder: AnalyticsEventRecorderAPI = resolve(),
app: AppProtocol = resolve()
) {
self.priceService = priceService
self.analyticsEventRecorder = analyticsEventRecorder
self.transactionModel = transactionModel
self.fiatCurrencyService = fiatCurrencyService
self.app = app
}
func build(
listener: EnterAmountPageListener,
sourceAccount: SingleAccount,
destinationAccount: TransactionTarget,
action: AssetAction,
navigationModel: ScreenNavigationModel
) -> EnterAmountPageRouter {
let displayBundle = DisplayBundle.bundle(for: action, sourceAccount: sourceAccount)
let amountViewable: AmountViewable
let amountViewInteracting: AmountViewInteracting
let amountViewPresenting: AmountViewPresenting
switch action {
case .sell:
guard let crypto = sourceAccount.currencyType.cryptoCurrency else {
fatalError("Expected a crypto as a source account.")
}
guard let fiat = destinationAccount.currencyType.fiatCurrency else {
fatalError("Expected a fiat as a destination account.")
}
amountViewInteracting = AmountTranslationInteractor(
fiatCurrencyClosure: {
Observable.just(fiat)
},
cryptoCurrencyService: DefaultCryptoCurrencyService(currencyType: sourceAccount.currencyType),
priceProvider: AmountTranslationPriceProvider(transactionModel: transactionModel),
defaultCryptoCurrency: crypto,
initialActiveInput: .fiat
)
amountViewPresenting = AmountTranslationPresenter(
interactor: amountViewInteracting as! AmountTranslationInteractor,
analyticsRecorder: analyticsEventRecorder,
displayBundle: displayBundle.amountDisplayBundle,
inputTypeToggleVisibility: .visible,
app: app
)
amountViewable = AmountTranslationView(presenter: amountViewPresenting as! AmountTranslationPresenter)
case .swap,
.send,
.interestWithdraw,
.interestTransfer:
guard let crypto = sourceAccount.currencyType.cryptoCurrency else {
fatalError("Expected a crypto as a source account.")
}
amountViewInteracting = AmountTranslationInteractor(
fiatCurrencyClosure: { [fiatCurrencyService] in
fiatCurrencyService.tradingCurrency.asObservable()
},
cryptoCurrencyService: DefaultCryptoCurrencyService(currencyType: sourceAccount.currencyType),
priceProvider: AmountTranslationPriceProvider(transactionModel: transactionModel),
defaultCryptoCurrency: crypto,
initialActiveInput: .fiat
)
amountViewPresenting = AmountTranslationPresenter(
interactor: amountViewInteracting as! AmountTranslationInteractor,
analyticsRecorder: analyticsEventRecorder,
displayBundle: displayBundle.amountDisplayBundle,
inputTypeToggleVisibility: .visible,
app: app
)
amountViewable = AmountTranslationView(presenter: amountViewPresenting as! AmountTranslationPresenter)
case .deposit,
.withdraw:
amountViewInteracting = SingleAmountInteractor(
currencyService: fiatCurrencyService,
inputCurrency: sourceAccount.currencyType
)
amountViewPresenting = SingleAmountPresenter(
interactor: amountViewInteracting as! SingleAmountInteractor
)
amountViewable = SingleAmountView(presenter: amountViewPresenting as! SingleAmountPresenter)
case .buy:
guard let cryptoAccount = destinationAccount as? CryptoAccount else {
fatalError("Expected a crypto as a destination account.")
}
amountViewInteracting = AmountTranslationInteractor(
fiatCurrencyClosure: { [fiatCurrencyService] in
fiatCurrencyService.tradingCurrency.asObservable()
},
cryptoCurrencyService: EnterAmountCryptoCurrencyProvider(transactionModel: transactionModel),
priceProvider: AmountTranslationPriceProvider(transactionModel: transactionModel),
defaultCryptoCurrency: cryptoAccount.asset,
initialActiveInput: .fiat
)
let maxLimitPublisher = transactionModel.state.publisher
.compactMap { $0.source as? PaymentMethodAccount }
.compactMap(\.paymentMethodType.topLimit.fiatValue)
.ignoreFailure(setFailureType: Never.self)
.eraseToAnyPublisher()
amountViewPresenting = AmountTranslationPresenter(
interactor: amountViewInteracting as! AmountTranslationInteractor,
analyticsRecorder: analyticsEventRecorder,
displayBundle: displayBundle.amountDisplayBundle,
inputTypeToggleVisibility: .visible,
app: app,
maxLimitPublisher: maxLimitPublisher
)
let ref = blockchain.app.configuration.prefill.is.enabled
let isEnabled = try? app.remoteConfiguration.get(ref) as? Bool
amountViewable = AmountTranslationView(
presenter: amountViewPresenting as! AmountTranslationPresenter,
prefillButtonsEnabled: isEnabled ?? false
)
default:
unimplemented()
}
let digitPadViewModel = provideDigitPadViewModel()
let continueButtonTitle = String(format: LocalizationConstants.Transaction.preview, action.name)
let continueButtonViewModel = ButtonViewModel.primary(with: continueButtonTitle)
let viewController = EnterAmountViewController(
displayBundle: displayBundle,
devicePresenterType: DevicePresenter.type,
digitPadViewModel: digitPadViewModel,
continueButtonViewModel: continueButtonViewModel,
recoverFromInputError: { [transactionModel] in
transactionModel.process(action: .showErrorRecoverySuggestion)
},
amountViewProvider: amountViewable
)
let interactor = EnterAmountPageInteractor(
transactionModel: transactionModel,
presenter: viewController,
amountInteractor: amountViewInteracting,
action: action,
navigationModel: navigationModel
)
interactor.listener = listener
let router = EnterAmountPageRouter(
interactor: interactor,
viewController: viewController
)
return router
}
// MARK: - Private methods
private func provideDigitPadViewModel() -> DigitPadViewModel {
let highlightColor = Color.black.withAlphaComponent(0.08)
let model = DigitPadButtonViewModel(
content: .label(text: MoneyValueInputScanner.Constant.decimalSeparator, tint: .titleText),
background: .init(highlightColor: highlightColor)
)
return DigitPadViewModel(
padType: .number,
customButtonViewModel: model,
contentTint: .titleText,
buttonHighlightColor: highlightColor
)
}
}
| lgpl-3.0 | b81a939b95ce985ed5b17170159540eb | 40.855769 | 114 | 0.660005 | 6.231926 | false | false | false | false |
klaaspieter/Letters | Sources/Extensions/RecorderError+Letters.swift | 1 | 2122 | extension RecorderError: AlertConvertible {
var alert: Alert {
switch self {
case .capturing(let error):
return error.alert
case .exporting(let error):
return error.alert
case .composing(let error):
return error.alert
}
}
}
extension CaptureError: AlertConvertible {
var alert: Alert {
let title = "Something went wrong while recording"
let recoverySuggestion: String
let buttons: [String]
switch self {
case .invalidOutputURL,
.invalidAsset,
.missingOutput,
.fileAlreadyExists,
.noDataCaptured,
.unknown:
recoverySuggestion = "The recording failed due to an internal error. Please try again."
buttons = []
case .missingInput:
recoverySuggestion = "Your camera or screen could not be recorded. Please ensure no other applications are actively recording your screen or using the camera and try again."
buttons = []
case .diskFull:
recoverySuggestion = "The recording failed because your disk is full. Would you like to open the partial recordings in Finder?"
buttons = ["Open in Finder", "Cancel"]
case .outOfMemory:
recoverySuggestion = "The recording failed because your system is out of memory. Would you like to open the partial recordings in Finder?"
buttons = ["Open in Finder", "Cancel"]
}
return Alert(title: title, recoverySuggestion: recoverySuggestion, buttons: buttons)
}
}
extension ComposeError: AlertConvertible {
var alert: Alert {
return Alert(
title: "Something went wrong while recording",
recoverySuggestion: "The recording failed due to an internal error. Would you like to open the partial recordings in Finder?",
buttons: ["Open in Finder", "Cancel"]
)
}
}
extension ExportError: AlertConvertible {
var alert: Alert {
return Alert(
title: "Something went wrong while recording",
recoverySuggestion: "The recording failed due to an internal error. Would you like to open the partial recordings in Finder?",
buttons: ["Open in Finder", "Cancel"]
)
}
}
| mit | 3caae96b38ef3f64ecb267d90157068e | 30.671642 | 179 | 0.68426 | 4.779279 | false | false | false | false |
huonw/swift | validation-test/stdlib/CollectionCompatibility.swift | 3 | 3630 | // RUN: rm -rf %t ; mkdir -p %t
// RUN: %target-build-swift %s -o %t/a.out3 -swift-version 3 && %target-run %t/a.out3
// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-run %t/a.out4
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
//===--- MyCollection -----------------------------------------------------===//
/// A simple collection that attempts to use an Int16 IndexDistance
struct MyCollection<Element>: Collection {
var _elements: [Element]
typealias IndexDistance = Int16
typealias Index = Int16
var startIndex: Index { return 0 }
var endIndex: Index { return numericCast(_elements.count) }
subscript(i: Index) -> Element { return _elements[Int(i)] }
func index(after: Index) -> Index { return after+1 }
}
//===--- MyBidiCollection -------------------------------------------------===//
/// A simple collection that attempts to use an Int16 IndexDistance
struct MyBidiCollection<Element>: BidirectionalCollection {
var _elements: [Element]
typealias Index = Int64
var startIndex: Index { return 0 }
var endIndex: Index { return numericCast(_elements.count) }
subscript(i: Index) -> Element { return _elements[Int(i)] }
func index(after: Index) -> Index { return after+1 }
func index(before: Index) -> Index { return before-1 }
func index(_ i: Index, advancedBy d: Int64) -> Index { return i+d }
}
let CollectionDistance = TestSuite("Collection.IndexDistance")
CollectionDistance.test("Int16/distance") {
let c = MyCollection<Int>(_elements: [1,2,3])
let d: Int16 = c.distance(from: c.startIndex, to: c.endIndex)
expectEqual(3, d)
// without type context, you now get an Int
var i = c.distance(from: c.startIndex, to: c.endIndex)
expectType(Int.self, &i)
expectType(MyCollection<Int>.IndexDistance.self, &i)
}
CollectionDistance.test("Int16/advance") {
let c = MyCollection<Int>(_elements: [1,2,3])
let d: Int16 = 1
var i = c.index(c.startIndex, offsetBy: d)
expectEqual(1, i)
c.formIndex(&i, offsetBy: d)
expectEqual(2, i)
let j = c.index(c.startIndex, offsetBy: d, limitedBy: c.endIndex)
expectEqual(1, j)
var b = c.formIndex(&i, offsetBy: d, limitedBy: c.endIndex)
expectTrue(b)
expectEqual(3, i)
b = c.formIndex(&i, offsetBy: d+5, limitedBy: c.endIndex)
expectFalse(b)
expectEqual(3, i)
let k = c.index(c.startIndex, offsetBy: d+5, limitedBy: c.endIndex)
expectEqual(nil, k)
checkCollection(c, [1,2,3], stackTrace: SourceLocStack()) { $0 == $1 }
}
CollectionDistance.test("Int64/distance") {
let c = MyBidiCollection<Int>(_elements: [1,2,3])
let d: Int16 = c.distance(from: c.startIndex, to: c.endIndex)
expectEqual(3, d)
// without type context, you now get an Int
var i = c.distance(from: c.startIndex, to: c.endIndex)
expectType(Int.self, &i)
expectType(MyCollection<Int>.IndexDistance.self, &i)
}
CollectionDistance.test("Int64/advance") {
let c = MyBidiCollection<Int>(_elements: [1,2,3])
let d: Int16 = 1
var i = c.index(c.startIndex, offsetBy: d)
expectEqual(1, i)
c.formIndex(&i, offsetBy: d)
expectEqual(2, i)
let j = c.index(c.startIndex, offsetBy: d, limitedBy: c.endIndex)
expectEqual(1, j)
var b = c.formIndex(&i, offsetBy: d, limitedBy: c.endIndex)
expectTrue(b)
expectEqual(3, i)
b = c.formIndex(&i, offsetBy: d+5, limitedBy: c.endIndex)
expectFalse(b)
expectEqual(3, i)
let k = c.index(c.startIndex, offsetBy: d+5, limitedBy: c.endIndex)
expectEqual(nil, k)
checkCollection(c, [1,2,3], stackTrace: SourceLocStack()) { $0 == $1 }
checkBidirectionalCollection(c, [1,2,3])
}
runAllTests()
| apache-2.0 | d8087ea7ea476696fb41d7007fddc61c | 32.302752 | 85 | 0.664187 | 3.367347 | false | true | false | false |
jshultz/ios9-swift2-core-data-demo | Core Data Demo/AppDelegate.swift | 1 | 6117 | //
// AppDelegate.swift
// Core Data Demo
//
// Created by Jason Shultz on 10/3/15.
// Copyright © 2015 HashRocket. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Open-Sky-Media--LLC.Core_Data_Demo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Core_Data_Demo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 43d9b7294e38ecf882ce2225b4d54d83 | 54.099099 | 291 | 0.719261 | 5.863854 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/WrappedModels/BasicSensorAppearance.swift | 1 | 3428 | /*
* Copyright 2019 Google LLC. 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 Foundation
import third_party_sciencejournal_ios_ScienceJournalProtos
/// A wrapper for a GSJBasicSensorAppearance that represents a sensor's display attributes.
class BasicSensorAppearance {
/// The locale of the sensor's host device.
var locale: String {
get {
return backingProto.locale
}
set {
backingProto.locale = newValue
}
}
/// Display name.
var name: String {
get {
return backingProto.name
}
set {
backingProto.name = newValue
}
}
/// Displayed string representing the units of the value.
var units: String {
get {
return backingProto.units
}
set {
backingProto.units = newValue
}
}
/// Asset path to the small icon (for tab display).
var iconPath: IconPath?
/// Asset path to the large icon (for snapshot or trigger note display).
var largeIconPath: IconPath?
/// Short description of the sensor.
var shortDescription: String {
get {
return backingProto.shortDescription
}
set {
backingProto.shortDescription = newValue
}
}
/// Allows a sensor to specify that it should be rounded in a particular way.
var pointsAfterDecimal: Int32 {
get {
return backingProto.pointsAfterDecimal
}
set {
backingProto.pointsAfterDecimal = newValue
}
}
/// The UI-friendly name of the sensor, including units.
var title: String {
return Sensor.titleForSensorName(name, withUnits: units)
}
/// A proto representation of the basic sensor appearance.
var proto: GSJBasicSensorAppearance {
backingProto.iconPath = iconPath?.proto
backingProto.largeIconPath = largeIconPath?.proto
return backingProto
}
/// Designated initializer.
///
/// - Parameters:
/// - proto: A basic sensor appearance proto.
init(proto: GSJBasicSensorAppearance) {
backingProto = proto
iconPath = proto.hasIconPath ? IconPath(proto: proto.iconPath) : nil
largeIconPath = proto.hasLargeIconPath ? IconPath(proto: proto.largeIconPath) : nil
}
/// Initializes a basic sensor appearance from a sensor.
convenience init(sensor: Sensor) {
let proto = GSJBasicSensorAppearance()
proto.locale = Locale.current.identifier
proto.name = sensor.name
proto.units = sensor.unitDescription
proto.shortDescription = sensor.textDescription
proto.pointsAfterDecimal = sensor.pointsAfterDecimal
// For built-in sensors, the same icon path can describe both small and large icons.
let iconPathProto = IconPath(type: .builtin, pathString: sensor.sensorId).proto
proto.iconPath = iconPathProto
proto.largeIconPath = iconPathProto
self.init(proto: proto)
}
// MARK: - Private
// The private backing proto.
let backingProto: GSJBasicSensorAppearance
}
| apache-2.0 | c3643eba585c31adb12659a9f394e03c | 27.098361 | 91 | 0.701284 | 4.328283 | false | false | false | false |
BlackBricks/Swift-Project-Template | Project-iOS/XLProjectName/XLProjectName/Helpers/Extensions/AppDelegate+XLProjectName.swift | 1 | 825 | //
// AppDelegate+XLProjectName.swift
// XLProjectName
//
// Created by XLAuthorName ( XLAuthorWebsite )
// Copyright (c) 2016 XLOrganizationName. All rights reserved.
//
import Eureka
import Foundation
extension AppDelegate {
/**
Set up your Eureka default row customization here
*/
func stylizeEurekaRows() {
let genericHorizontalMargin = CGFloat(50)
BaseRow.estimatedRowHeight = 58
EmailRow.defaultRowInitializer = {
$0.placeholder = NSLocalizedString("E-mail Address", comment: "")
$0.placeholderColor = .gray
}
EmailRow.defaultCellSetup = { cell, _ in
cell.layoutMargins = UIEdgeInsets.zero
cell.contentView.layoutMargins.left = genericHorizontalMargin
cell.height = { 58 }
}
}
}
| mit | 8b7b1e538419eab06452114c757d432d | 24 | 77 | 0.64 | 4.714286 | false | false | false | false |
yuvalt/SwiftySettings | Tests/OptionsTests.swift | 1 | 4354 | //
// OptionsTests.swift
//
//
// SwiftySettings
// Created by Tomasz Gebarowski on 24/08/15.
// Copyright © 2015 codica Tomasz Gebarowski <gebarowski at gmail.com>.
// All rights reserved.
//
// 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
@testable import SwiftySettings
class ValueChangedConfiguration : QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("value change closure") { (sharedExampleContext: SharedExampleContext) in
it("triggers when value changes") {
let element = sharedExampleContext()["element"]
let newValue = sharedExampleContext()["newValue"]
let returnedKey = sharedExampleContext()["key"]
waitUntil(action: { done in
element.valueChanged = {
(key, value) -> Void in
expect(value).to(equal(newValue))
expect(key).to(equal(returnedKey))
done()
}
element.value = switchNewValue
})
}
}
}
}
class Options: QuickSpec {
override func spec() {
describe("OptionsSection") {
var optionsSection: OptionsSection? = nil
beforeEach {
optionsSection = OptionsSection(key: "section-key",
title: "Section title") {
[Option(title: "Option 1", optionId: 1),
Option(title: "Option 2", optionId: 2),
Option(title: "Option 3", optionId: 3)]
}
}
it("has valid options stored") {
let options = optionsSection?.items as? [Option]
expect(options).toNot(beNil())
expect(options!.count).to(equal(3))
}
it("any of options is not moving to previous view controller") {
let options = optionsSection?.items as? [Option]
expect(options!.filter {!$0.navigateBack}.count).to(equal(3))
}
it("every Option can access its parent container key") {
let options = optionsSection?.items as? [Option]
for option in options! {
expect(option.container.key).to(equal(optionsSection!.key))
}
}
it("should trigger ValueChanged when value changes") {
itBehavesLike("value change closure") {
["element" : Switch(key: "keyX", title: "Title 1"),
"newValue" : true ,
"key" : "keyX"]
}
/*
let switchNewValue = true
let switchKey = "key1"
waitUntil(action: { done in
let s = Switch(key: switchKey, title: "Title 1", valueChangedClosure: {
(key, value) -> Void in
expect(value).to(equal(switchNewValue))
expect(key).to(equal(switchKey))
done()
})
s.value = switchNewValue
})
*/
}
}
}
} | mit | 5146b1c7781c7955f3a280479b10430f | 36.213675 | 96 | 0.555938 | 5.08528 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/network/SjekkUtApi.swift | 1 | 25965 | //
// SjekkUt.swift
// SjekkUt
//
// Created by Henrik Hartz on 27/07/16.
// Copyright © 2016 Den Norske Turistforening. All rights reserved.
//
import Foundation
import Alamofire
import SAMKeychain
import UserNotifications
class SjekkUtApi: DntManager {
static let instance = SjekkUtApi()
// dependency injection for singletons
lazy var mapOffliner: MapboxOffliner = {
return MapboxOffliner.instance
}()
lazy var location:Location = {
return Location.instance
}()
lazy var model: ModelController = {
return ModelController.instance
}()
lazy var turbasen: TurbasenApi = {
return TurbasenApi.instance
}()
lazy var defaults: UserDefaults = {
return UserDefaults.standard
}()
var authenticationHeaders: HTTPHeaders! {
guard let userId = DntApi.instance.user?.identifier,
let userToken = SAMKeychain.password(forService: SjekkUtKeychainServiceName,
account: kSjekkUtDefaultsToken) else {
return [:];
}
return [
"X-User-Id": "\(userId)",
"X-User-Token": userToken
]
}
override var isOffline: Bool {
didSet {
if isOffline != oldValue {
// delay to allow reporting offline requests
delay((offlineRequests?.count)! > 0 ? 2 : 0) {
self.getData()
}
}
}
}
var visitDistanceLimitMeters: Double {
set {
defaults.set(newValue, forKey: kSjekkUtDefaultsVisitDistance)
defaults.synchronize()
}
get {
return defaults.object(forKey: kSjekkUtDefaultsVisitDistance) as? Double ?? 100
}
}
var visitQuarantineLimitSeconds: Double {
set {
defaults.set(newValue, forKey: kSjekkUtDefaultsVisitQuarantine)
defaults.synchronize()
}
get {
return defaults.object(forKey: kSjekkUtDefaultsVisitQuarantine) as? Double ?? 3600
}
}
required init(forDomain aDomain: String = "sjekkut.app.dnt.no/api/v3") {
super.init(forDomain: aDomain)
NotificationCenter.default.addObserver(self, selector: #selector(updateNotificationPreference), name: kSjekkUtNotificationLocationChanged.Name(), object: nil)
}
func getData() {
getProfile()
getApiSpec()
}
// MARK: profile
func getProfile(_ finishedHandler:((Error?)->Void)? = nil) {
guard let userId = DntApi.instance.user?.identifier else {
//showErrorMessage(String.localizedStringWithFormat("No user id, please log in again"))
return
}
let requestUrl = kSjekkUtUrl + "/brukere/\(userId)"
request(requestUrl, method: .get, headers: authenticationHeaders)
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
if let jsonData = value as? [AnyHashable: Any],
let json = jsonData["data"] as? [AnyHashable: Any] {
self.parseProfile(json)
}
finishedHandler?(nil)
case .failure(let error):
DntManager.logError(error as NSError)
finishedHandler?(error)
}
}
}
func parseProfile(_ json: [AnyHashable: Any]) {
if let checkinsJSON = json["innsjekkinger"] as? [[AnyHashable: Any]] {
self.updateCheckins(checkinsJSON)
}
if let projectsJSON = json["lister"] as? [String] {
self.updateProjects(projectsJSON)
}
}
// MARK: api spec
func getApiSpec() {
let requestUrl: URLConvertible = kSjekkUtUrl + "/"
request(requestUrl, method: .get, headers: authenticationHeaders)
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
if let json = value as? [AnyHashable: Any] {
self.parseSpec(json)
}
case .failure(let error):
DntManager.logError(error as NSError!)
}
}
}
func parseSpec(_ json: [AnyHashable: Any]) {
guard let checkin = json["checkin_new"] as? [AnyHashable: Any],
let rules = checkin["rules"] as? [AnyHashable: Any] else {
logErrorMessage("unable to find checkin rules")
return
}
if let maxDistance = rules["max_distance"] as? Double {
visitDistanceLimitMeters = maxDistance
}
if let maxInterval = rules["quarantine"] as? Double {
visitQuarantineLimitSeconds = maxInterval
}
}
// MARK: projects
func updateProjects(_ projectsArray: [String]) {
model.save {
var leaveProject = Project.allEntities() as? [Project] ?? []
for projectJSON in projectsArray {
let aProject = Project.insertOrUpdate(projectJSON)
aProject.user = DntUser.current()
// only change record if it's different
if aProject.isParticipating == nil || !aProject.isParticipating!.boolValue {
aProject.isParticipating = NSNumber.init(value: true)
}
// make sure it's correctly hidden if expired
if let projectId = aProject.identifier {
aProject.isHidden = NSNumber(value: aProject.isExpired)
self.turbasen.getProjectAnd(projectId, { _ in }, aFailHandler: {})
}
if let projectIndex = leaveProject.index(of: aProject) {
leaveProject.remove(at: projectIndex)
}
}
// not participating in remaining objects
for aProject: Project in leaveProject {
if aProject.isParticipating!.boolValue {
aProject.isParticipating = false
aProject.user = nil
}
}
}
}
func doJoin(_ aProject: Project, finishHandler: ((Error?)->Void)? = nil) -> DataRequest {
let requestUrl: URLConvertible = kSjekkUtUrl + "/lister/\(aProject.identifier!)/blimed"
let aRequest = request(requestUrl, method:.post, headers:authenticationHeaders)
.validate()
.responseJSON { response in
var theError: Error? = nil
switch response.result {
case .success(let value):
if let json = value as? [AnyHashable: Any],
let jsonData = json["data"] as? [AnyHashable: Any] {
self.parseProfile(jsonData)
self.analytics.track("Server registrerte påmelding", ["projectid": "\(aProject.identifier!)"])
}
case .failure(let error):
self.failHandler(error, for: response, retry: true)
theError = error
}
if let finished = finishHandler {
finished(theError)
}
}
return aRequest
}
func doLeave(_ aProject: Project) -> DataRequest {
let requestUrl = kSjekkUtUrl + "/lister/\(aProject.identifier!)/meldav"
let aRequest = self.request(requestUrl, method:.post, headers:authenticationHeaders)
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
if let json = value as? [AnyHashable: Any],
let jsonData = json["data"] as? [AnyHashable: Any] {
self.parseProfile(jsonData)
self.analytics.track("Server registrerte avmelding", ["projectid": "\(aProject.identifier!)"])
}
MapboxOffliner.deleteTiles(forProject:aProject)
case .failure(let error as NSError):
// in the case of offline we need to specify that the request should be retried when
// the device comes back online
if self.isOffline || error.isOffline {
aProject.isParticipating = false
}
self.failHandler(error, for: response, retry: true)
default:
break
}
}
return aRequest
}
// MARK: checkins
func updateCheckins(_ checkinsArray: [[AnyHashable: Any]]) {
model.save {
for checkinJson in checkinsArray {
_ = Checkin.insertOrUpdate(checkinJson)
}
}
}
func getPlaceCheckins(_ aPlace: Place, finishHandler: (()->Void)? = nil) {
guard let placeId = aPlace.identifier else {
logErrorMessage("no place id")
finishHandler?()
return
}
self.request(CheckinRouter.List(placeId: placeId))
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
if let json = value as? [AnyHashable: Any],
let jsonArray = json["data"] as? [[AnyHashable: Any]] {
self.updateCheckins(jsonArray)
}
case .failure(let error):
DntManager.logError(error as NSError)
}
finishHandler?()
}
}
func doPlaceCheckin(_ aPlace: Place, finishHandler:@escaping (_ response: DataResponse<Any>) -> Void) -> DataRequest? {
guard let currentLocation = location.currentLocation?.coordinate else {
showErrorMessage(NSLocalizedString("Missing location ", comment: "error message when checkin in without location"))
return nil
}
guard let placeId = aPlace.identifier else {
showErrorMessage(NSLocalizedString("Missing place id", comment: "error message when checkin in without place id"))
return nil
}
let someParameters: Parameters = [
"lat": currentLocation.latitude,
"lon": currentLocation.longitude,
"public": defaults.bool(forKey: kSjekkUtDefaultsPublicVisits)
]
return request(CheckinRouter.Create(placeId: placeId, params: someParameters))
.validate()
.responseJSON { response in
// in the case of offline checkins we need to fake a successful result for the finish handler
var aResponse:DataResponse<Any>? = response
switch response.result {
case .success:
if let json = response.result.value as? [AnyHashable: Any] {
self.handleCheckinSuccess(with: json, for: aPlace)
}
case .failure(let error as NSError):
print("checkin failed with error: \(error)")
// in the case of offline checkins we need to specify that a customized request should be retried when
// the device comes back online
if self.isOffline || error.isOffline {
print("is offline")
var aRetryRequest: URLRequest?
(aRetryRequest, aResponse) = self.offlineCheckin(for: aPlace, with: someParameters, using: response)
let offlineResponse = DataResponse<Any>.init(request: aRetryRequest, response: nil, data: nil, result: response.result)
self.failHandler(error, for: offlineResponse, retry: true)
}
else {
self.failHandler(error, for: response)
}
default:
break
}
if let theResponse = aResponse {
finishHandler(theResponse)
}
}
}
func updateCheckin(path checkinPath:String, with anImage:UIImage, success: ((Checkin?)->Void)? = nil) {
let memoryThreshold = SessionManager.multipartFormDataEncodingMemoryThreshold
upload(multipartFormData: { (formData) in
if let imageData = UIImageJPEGRepresentation(anImage, 0.8) {
formData.append(imageData, withName: "photo", fileName: "selfie.jpg", mimeType: "image/jpeg")
}
}, usingThreshold: memoryThreshold,
to: kSjekkUtUrl + checkinPath,
method: .put,
headers: authenticationHeaders) { (encodingResult) in
switch encodingResult {
case .success(let uploadRequest, _, _):
uploadRequest.responseJSON { response in
switch response.result {
case .success(let value):
var checkin:Checkin? = nil
if let responseData = value as? [AnyHashable: Any],
let json = responseData["data"] as? [AnyHashable: Any ] {
self.model.save {
checkin = Checkin.insertOrUpdate(json)
// try to extract the new photo id for tracking
if let photoId = checkin?.photo?.identifier {
self.analytics.track("Server oppdaterte besøk med bilde", ["photoid": photoId])
}
}
}
if let successHandler = success {
successHandler(checkin)
}
case .failure(let error):
self.failHandler(error, for: response)
}
}
case .failure(let error):
self.failHandler(error)
}
}
}
func publish(_ checkin:Checkin, withGuestbookComment comment:String, success:(()->Void)? = nil) -> DataRequest? {
guard let placeId = checkin.place?.identifier,
let checkinId = checkin.identifier else {
logErrorMessage("failed to find place or id for checkin")
return nil
}
var params: Parameters = ["comment": comment, "public": true]
if let photo = checkin.photo, let photoId = photo.identifier {
params["photo"] = photoId
}
let aRequest = request(CheckinRouter.Update(placeId: placeId, checkinId: checkinId, params: params))
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
if let jsonData = value as? [AnyHashable: Any],
let json = jsonData["data"] as? [AnyHashable: Any] {
checkin.update(json)
self.analytics.track("Server registrerte gjestebokinnlegg", ["placeid": placeId, "checkinid": checkinId])
}
if let successHandler = success {
successHandler()
}
case .failure(let error):
self.failHandler(error, for: response)
}
}
return aRequest
}
func updateGuestbookFor(place:Place, success:(()->Void)? = nil) {
guard let placeId = place.identifier else {
logErrorMessage("failed to find id for place")
return
}
request(CheckinRouter.List(placeId: placeId))
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
if let jsonData = value as? [AnyHashable: Any],
let checkinArray = jsonData["data"] as? [[AnyHashable: Any]] {
// retain the private checkins since `logg` only shows the ones
// who are public
let oldPrivateCheckins = Set<Checkin>.init(place.checkins?.filter({ !$0.isPublic }) ?? [])
// collect updated checkins from API
var updatedCheckins = Set<Checkin>()
for checkinJson in checkinArray {
let checkin = Checkin.insertOrUpdate(checkinJson)
updatedCheckins.insert(checkin)
}
// append the private checkins to keep the count correct
place.checkins = updatedCheckins.union(oldPrivateCheckins)
if let successHandler = success {
successHandler()
}
}
case .failure(let error):
self.failHandler(error, for: response)
}
}
}
func unpublish(_ checkin:Checkin, success:(()->Void)? = nil) {
guard let placeId = checkin.place?.identifier,
let checkinId = checkin.identifier else {
logErrorMessage("failed to find place or id for checkin")
return
}
let requestUrl = kSjekkUtUrl + "/steder/\(placeId)/besok/\(checkinId)"
request(requestUrl, method:.put, parameters: ["comment": "", "public": false], encoding: JSONEncoding.default, headers: authenticationHeaders)
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
if let jsonData = value as? [AnyHashable: Any],
let json = jsonData["data"] as? [AnyHashable: Any] {
checkin.update(json)
self.analytics.track("Server slettet gjestebokinnlegg", ["placeid": placeId, "checkinid": checkinId])
}
if let successHandler = success {
successHandler()
}
case .failure(let error):
self.failHandler(error, for: response)
}
}
}
func handleCheckinSuccess(with json: [AnyHashable: Any], for aPlace: Place) {
model.save {
let checkin = Checkin.insertOrUpdate((json["data"] as? [AnyHashable:Any])!)
aPlace.addCheckinsObject(checkin)
NotificationCenter.default.post(name: SjekkUtCheckedInNotification.Name(), object:checkin)
if let placeId = aPlace.identifier,
let checkinId = checkin.identifier {
self.analytics.track("Server registrerte besøk", ["placeid": placeId, "checkinid": checkinId])
}
}
for project: Project in aPlace.projects ?? [] {
if !(project.isParticipating?.boolValue)! {
_ = self.doJoin(project)
}
}
}
func offlineCheckin(for aPlace: Place, with parameters:[AnyHashable: Any], using response:DataResponse<Any>) -> (URLRequest?, DataResponse<Any>?) {
// a random identifier we can use to update the entity with the API data when it POSTs the
// actual checkin
let aRandomId = "offline-\(NSUUID().uuidString)"
let currentLocation:CLLocationCoordinate2D = (location.currentLocation?.coordinate)!
var checkin: Checkin?
model.save {
checkin = Checkin.insert()
if (checkin != nil) {
checkin!.identifier = aRandomId
checkin!.date = Date()
checkin!.latitute = currentLocation.latitude as NSNumber?
checkin!.longitude = currentLocation.longitude as NSNumber?
checkin!.isOffline = true
checkin!.isPublic = self.defaults.bool(forKey: kSjekkUtDefaultsPublicVisits)
checkin!.user = DntApi.instance.user
aPlace.addCheckinsObject(checkin!)
}
}
if checkin != nil {
do {
try model.managedObjectContext.obtainPermanentIDs(for: [checkin!])
// store the temporary ID and retry the operation later
var offlineRequest: URLRequest = response.request!
offlineRequest.setValue(checkin!.objectID.uriRepresentation().absoluteString,
forHTTPHeaderField: kSjekkUtConstantTemporaryManagedObjectIdHeaderKey)
// add the timestamp as the current time instead of the upload time
let mutatedParameters = NSMutableDictionary.init(dictionary: ["timestamp": Checkin.dateFormatter().string(from: Date()) ])
do {
mutatedParameters.addEntries(from: parameters)
let httpBody = try JSONSerialization.data(withJSONObject: mutatedParameters, options: JSONSerialization.WritingOptions(rawValue: UInt(0)))
offlineRequest.httpBody = httpBody
} catch(let error as NSError) {
DntManager.logError(error)
}
// fake correct result
let aResponse = DataResponse<Any>.init(request: response.request, response: response.response, data: response.data, result: Result<Any>.success("asdf"))
NotificationCenter.default.post(name: SjekkUtCheckedInNotification.Name(), object:checkin)
return (offlineRequest, aResponse)
} catch (let error as NSError) {
DntManager.logError(error)
return (nil, nil)
}
}
return (nil, nil)
}
func doChangePublicCheckin(_ enablePublicCheckin: Bool, finishHandler:@escaping (() -> (Void))) {
model.save {
DntApi.instance.user?.publicCheckins = enablePublicCheckin
self.defaults.set(enablePublicCheckin, forKey: kSjekkUtDefaultsPublicVisits)
finishHandler()
}
}
// MARK: notification and geofencing
var currentRegionLocation: CLLocation? = nil
var isNotificationsEnabled: Bool {
get {
return defaults.bool(forKey: "com.dnt.sjekkut.NotifyPlace")
}
}
var haveAskedNotificationPermission: Bool {
get {
return defaults.bool(forKey: #function)
}
set {
defaults.set(newValue, forKey: #function)
defaults.synchronize()
}
}
@objc func updateNotificationPreference() {
if self.isNotificationsEnabled {
self.updateMonitoredRegions()
}
else {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
}
func updateMonitoredRegions() {
guard let currentLocation = location.currentLocation, isNotificationsEnabled else {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
return
}
guard let regionDistance = currentRegionLocation?.distance(from: currentLocation) else {
addLocationNotifications()
return
}
if (regionDistance > 500) {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
addLocationNotifications()
}
}
func addLocationNotifications() {
currentRegionLocation = location.currentLocation
// find the nearest 20 places
let nearestPlaces = Place.nearestPlaces(within: kSjekkUtConstantNearbyLimitMeters, limitedTo: kSjekkUtConstantNearbyLimitCount)
// add them to region monitoring
for aPlace in nearestPlaces {
// but if we can already check in we don't care
if aPlace.canCheckIn() {
continue
}
addLocationNotification(for:aPlace)
}
}
func addLocationNotification(for place:Place) {
let center = UNUserNotificationCenter.current()
guard let placeName = place.name,
let placeId = place.identifier else {
return
}
let content = UNMutableNotificationContent.init()
content.title = NSLocalizedString("Almost there", comment: "check in local notification title")
content.sound = UNNotificationSound.init(named: "cuckoo.caf")
content.body = NSString.localizedUserNotificationString(forKey: "You're getting close to %@", arguments: [placeName])
content.userInfo = ["place-identifier": placeId]
let visitDistanceLimit = defaults.double(forKey: kSjekkUtDefaultsVisitDistance)
let radius = visitDistanceLimit
let aRegion = CLCircularRegion.init(center: place.location().coordinate, radius: radius, identifier: placeId)
let trigger = UNLocationNotificationTrigger.init(region: aRegion, repeats: false)
let request = UNNotificationRequest.init(identifier: placeId, content: content, trigger: trigger)
center.add(request) { (error) in
if let error = error {
SjekkUtApi.logError(error)
}
}
}
}
| mit | ee00b6821fd5b9bcc12134558da251e3 | 39.374806 | 168 | 0.540195 | 5.353887 | false | false | false | false |
sgr-ksmt/i18nSwift | Demo/Demo/ViewController.swift | 1 | 2382 | //
// ViewController.swift
// Demo
//
// Created by Suguru Kishimoto on 3/26/17.
// Copyright © 2017 Suguru Kishimoto. All rights reserved.
//
import UIKit
import i18nSwift
class ViewController: UIViewController {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var alertButton: UIButton! {
didSet {
alertButton.addTarget(self, action: #selector(alertButtonDidTap(_:)), for: .touchUpInside)
}
}
@IBOutlet private weak var selectLanguageButton: UIButton! {
didSet {
selectLanguageButton.addTarget(self, action: #selector(selectLanguageButtonDidTap(_:)), for: .touchUpInside)
}
}
private var observer: LanguageObserver?
override func viewDidLoad() {
super.viewDidLoad()
update()
self.observer = LanguageObserver { [weak self] _ in
self?.update()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func update() {
titleLabel.text = Language.displayName()
alertButton.setTitle(i18n.t(.alertButton), for: [])
selectLanguageButton.setTitle(i18n.t(.chooseLanguage), for: [])
}
@objc private func alertButtonDidTap(_: UIButton) {
let alert = UIAlertController(title: i18n.t(.alertTitle), message: i18n.t(.alertMessage), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: i18n.t(.ok) , style: .default) { _ in })
show(alert, sender: nil)
}
@objc private func selectLanguageButtonDidTap(_: UIButton) {
let actionSheet = UIAlertController(title: nil, message: i18n.t(.chooseLanguage), preferredStyle: .actionSheet)
Language.availableLanguages(includeBase: false).forEach { language in
let title = Language.displayName(for: language).map { Language.current == language ? "\($0) ✔︎" : $0 } ?? ""
actionSheet.addAction(UIAlertAction(title: title, style: .default) { _ in
Language.current = language
})
}
actionSheet.addAction(UIAlertAction(title: i18n.t(.useSystem), style: .destructive) { _ in
Language.reset()
})
actionSheet.addAction(UIAlertAction(title: i18n.t(.cancel), style: .cancel) { _ in })
show(actionSheet, sender: nil)
}
}
| mit | 164018b229ad0008148b32b4ef4dfcb7 | 32.957143 | 121 | 0.628944 | 4.442991 | false | false | false | false |
stripe/stripe-ios | StripeUICore/StripeUICoreTests/Unit/Elements/TextFieldElementTest.swift | 1 | 3748 | //
// TextFieldElementTest.swift
// StripeUICoreTests
//
// Created by Yuki Tokuhiro on 8/23/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import XCTest
@testable @_spi(STP) import StripeUICore
class TextFieldElementTest: XCTestCase {
struct Configuration: TextFieldElementConfiguration {
var defaultValue: String?
var label: String = "label"
func maxLength(for text: String) -> Int { "default value".count }
}
func testNoDefaultValue() {
let element = TextFieldElement(configuration: Configuration(defaultValue: nil))
XCTAssertTrue(element.textFieldView.text.isEmpty)
XCTAssertTrue(element.text.isEmpty)
}
func testDefaultValue() {
let element = TextFieldElement(configuration: Configuration(defaultValue: "default value"))
XCTAssertEqual(element.textFieldView.text, "default value")
XCTAssertEqual(element.text, "default value")
}
func testInvalidDefaultValueIsSanitized() {
let element = TextFieldElement(configuration: Configuration(
defaultValue: "\ndefault\n value that is too long and contains disallowed characters")
)
XCTAssertEqual(element.textFieldView.text, "default value")
XCTAssertEqual(element.text, "default value")
}
func testEmptyStringsFailDefaultConfigurationValidation() {
let sut = Configuration()
XCTAssertEqual(sut.validate(text: "", isOptional: false), .invalid(TextFieldElement.Error.empty))
XCTAssertEqual(sut.validate(text: " ", isOptional: false), .invalid(TextFieldElement.Error.empty))
XCTAssertEqual(sut.validate(text: " \n", isOptional: false), .invalid(TextFieldElement.Error.empty))
}
func testMultipleCharacterChangeInEmptyFieldIsAutofill() {
let element = TextFieldElement(configuration: Configuration(defaultValue: nil))
XCTAssertEqual(element.didReceiveAutofill, false)
_ = element.textFieldView.textField(element.textFieldView.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "This is autofill")
element.textFieldView.textDidChange()
XCTAssertEqual(element.didReceiveAutofill, true)
}
func testSingleCharacterChangeInEmptyFieldIsNotAutofill() {
let element = TextFieldElement(configuration: Configuration(defaultValue: nil))
XCTAssertEqual(element.didReceiveAutofill, false)
_ = element.textFieldView.textField(element.textFieldView.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "T")
element.textFieldView.textDidChange()
XCTAssertEqual(element.didReceiveAutofill, false)
}
func testMultipleCharacterChangeInPopulatedFieldIsNotAutofill() {
let element = TextFieldElement(configuration: Configuration(defaultValue: "default value"))
XCTAssertEqual(element.didReceiveAutofill, false)
_ = element.textFieldView.textField(element.textFieldView.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "This is autofill")
element.textFieldView.textDidChange()
XCTAssertEqual(element.didReceiveAutofill, false)
}
func testSingleCharacterChangeInPopulatedFieldIsNotAutofill() {
let element = TextFieldElement(configuration: Configuration(defaultValue: "default value"))
XCTAssertEqual(element.didReceiveAutofill, false)
_ = element.textFieldView.textField(element.textFieldView.textField, shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "T")
element.textFieldView.textDidChange()
XCTAssertEqual(element.didReceiveAutofill, false)
}
}
| mit | ab9f6a7415d2b14df8d173b4ea8079d4 | 47.038462 | 174 | 0.729384 | 5.049865 | false | true | false | false |
BellAppLab/Backgroundable | Sources/Backgroundable/Backgroundable+Operation.swift | 1 | 2468 | //
// Backgroundable+Operation.swift
// Example
//
// Created by André Campana on 02/08/2020.
// Copyright © 2020 Bell App Lab. All rights reserved.
//
import Foundation
@nonobjc
extension Operation {
/**
Compares two `Operation`s and returns the one which should be cancelled.
- parameters:
- operation: The second operation to be compared to the receiver.
- returns:
- The operation that should be cancelled between the received and the other operation, according to the receiver's `uniquenessPolicy` flag. If the receiver is not an instance of `AsyncOperation`, `nil` is returned.
## See Also:
- `AsyncOperationUniquenessPolicy`
*/
func operationToCancel(_ operation: Operation) -> Operation?
{
guard let policy = (self as? AsyncOperation)?.uniquenessPolicy else { return nil }
guard let name = name, let otherName = operation.name, name == otherName else { return nil }
guard isFinished == false, operation.isFinished == false else { return nil }
guard isCancelled == false, operation.isCancelled == false else { return nil }
guard isExecuting == false else { return nil }
switch policy {
case .drop, .ignore: return nil
case .replace: return operation
}
}
/**
Compares two `Operation`s and returns the one which should be added to a queue.
- parameters:
- operation: The second operation to be compared to the receiver.
- returns:
- The operation that should be added between the received and the other operation, according to the receiver's `uniquenessPolicy` flag. If the receiver is not an instance of `AsyncOperation`, `self` is returned.
## See Also:
- `AsyncOperationUniquenessPolicy`
*/
func operationToAdd(_ operation: Operation) -> Operation?
{
guard let policy = (self as? AsyncOperation)?.uniquenessPolicy else { return self }
guard let name = name, let otherName = operation.name, name == otherName else { return self }
guard isFinished == false else { return nil }
guard operation.isFinished == false else { return self }
guard isCancelled == false else { return nil }
guard operation.isCancelled == false else { return self }
guard isExecuting == false else { return nil }
switch policy {
case .drop, .ignore: return nil
case .replace: return self
}
}
}
| mit | 69db9ebb01aada5d4b040c7d63afc90e | 35.264706 | 222 | 0.660989 | 4.715105 | false | false | false | false |
tndatacommons/Compass-iOS | Compass/src/Util/DefaultsManager.swift | 1 | 1774 | //
// DefaultsManager.swift
// Compass
//
// Created by Ismael Alonso on 7/15/16.
// Copyright © 2016 Tennessee Data Commons. All rights reserved.
//
import Foundation
class DefaultsManager{
/*------------------------*
* AWARD RELATED DEFAULTS *
*------------------------*/
private static let newBadgeIdArrayKey = "new_badges";
static func addNewAward(badge: Badge){
let defaults = NSUserDefaults.standardUserDefaults();
var badgeIds = [Int]();
if let storedArray = defaults.arrayForKey(newBadgeIdArrayKey) as? [Int]{
badgeIds = storedArray;
}
badgeIds.append(badge.getId());
defaults.setObject(badgeIds, forKey: newBadgeIdArrayKey);
}
static func removeNewAward(badge: Badge){
let defaults = NSUserDefaults.standardUserDefaults();
if let storedArray = defaults.arrayForKey(newBadgeIdArrayKey) as? [Int]{
let newArray = storedArray.filter{ $0 != badge.getId() };
defaults.setObject(newArray, forKey: newBadgeIdArrayKey);
}
}
static func emptyNewAwardsRecords(){
NSUserDefaults.standardUserDefaults().setObject([Int](), forKey: newBadgeIdArrayKey);
}
static func getNewAwardCount() -> Int{
let defaults = NSUserDefaults.standardUserDefaults();
if let badgeIds = defaults.arrayForKey(newBadgeIdArrayKey){
return badgeIds.count;
}
return 0;
}
static func getNewAwardArray() -> [Int]{
let defaults = NSUserDefaults.standardUserDefaults();
if let storedArray = defaults.arrayForKey(newBadgeIdArrayKey) as? [Int]{
return storedArray;
}
return [Int]();
}
}
| mit | 2d9d3e4adf5cc334486555d2ffc16c41 | 28.55 | 93 | 0.608009 | 4.817935 | false | false | false | false |
manavgabhawala/swift | test/SILGen/errors.swift | 1 | 47101 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s
import Swift
class Cat {}
enum HomeworkError : Error {
case TooHard
case TooMuch
case CatAteIt(Cat)
}
func someValidPointer<T>() -> UnsafePointer<T> { fatalError() }
func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() }
// CHECK: sil hidden @_TF6errors10make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: return [[T2]] : $Cat
func make_a_cat() throws -> Cat {
return Cat()
}
// CHECK: sil hidden @_TF6errors15dont_make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[BOX]]
func dont_make_a_cat() throws -> Cat {
throw HomeworkError.TooHard
}
// CHECK: sil hidden @_TF6errors11dont_return{{.*}} : $@convention(thin) <T> (@in T) -> (@out T, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: destroy_addr %1 : $*T
// CHECK-NEXT: throw [[BOX]]
func dont_return<T>(_ argument: T) throws -> T {
throw HomeworkError.TooMuch
}
// CHECK: sil hidden @_TF6errors16all_together_nowFSbCS_3Cat : $@convention(thin) (Bool) -> @owned Cat {
// CHECK: bb0(%0 : $Bool):
// CHECK: [[DR_FN:%.*]] = function_ref @_TF6errors11dont_returnur{{.*}} :
// CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat
// Branch on the flag.
// CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]]
// In the true case, call make_a_cat().
// CHECK: [[FLAG_TRUE]]:
// CHECK: [[MAC_FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]]
// CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat)
// In the false case, call dont_make_a_cat().
// CHECK: [[FLAG_FALSE]]:
// CHECK: [[DMAC_FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]]
// CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat)
// Merge point for the ternary operator. Call dont_return with the result.
// CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat
// CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]]
// CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]]
// CHECK: [[DR_NORMAL]]({{%.*}} : $()):
// CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat
// CHECK-NEXT: dealloc_stack [[ARG_TEMP]]
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat)
// Return block.
// CHECK: [[RETURN]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: return [[T0]] : $Cat
// Catch dispatch block.
// CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error
// CHECK-NEXT: store [[ERROR]] to [init] [[SRC_TEMP]]
// CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError
// CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]]
// Catch HomeworkError.
// CHECK: [[IS_HWE]]:
// CHECK-NEXT: [[T0:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError
// CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]]
// Catch HomeworkError.CatAteIt.
// CHECK: [[MATCH]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: destroy_addr [[SRC_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat)
// Catch other HomeworkErrors.
// CHECK: [[NO_MATCH]]:
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch other types.
// CHECK: [[NOT_HWE]]:
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch all.
// CHECK: [[CATCHALL]]:
// CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: destroy_value [[ERROR]] : $Error
// CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat)
// Landing pad.
// CHECK: [[MAC_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DR_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
func all_together_now(_ flag: Bool) -> Cat {
do {
return try dont_return(flag ? make_a_cat() : dont_make_a_cat())
} catch HomeworkError.CatAteIt(let cat) {
return cat
} catch _ {
return Cat()
}
}
// Catch in non-throwing context.
// CHECK-LABEL: sil hidden @_TF6errors11catch_a_catFT_CS_3Cat : $@convention(thin) () -> @owned Cat
// CHECK-NEXT: bb0:
// CHECK: [[F:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]])
// CHECK-NEXT: return [[V]] : $Cat
func catch_a_cat() -> Cat {
do {
return Cat()
} catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
}
// Initializers.
class HasThrowingInit {
var field: Int
init(value: Int) throws {
field = value
}
}
// CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) {
// CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[BORROWED_T0]] : $HasThrowingInit
// CHECK-NEXT: assign %0 to [[T1]] : $*Int
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit
// CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitC{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error)
// CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit
// CHECK: [[T0:%.*]] = function_ref @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2
// CHECK: bb1([[SELF:%.*]] : $HasThrowingInit):
// CHECK-NEXT: return [[SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[ERROR]]
enum ColorError : Error {
case Red, Green, Blue
}
//CHECK-LABEL: sil hidden @_TF6errors6IThrowFzT_Vs5Int32
//CHECK: builtin "willThrow"
//CHECK-NEXT: throw
func IThrow() throws -> Int32 {
throw ColorError.Red
return 0 // expected-warning {{will never be executed}}
}
// Make sure that we are not emitting calls to 'willThrow' on rethrow sites.
//CHECK-LABEL: sil hidden @_TF6errors12DoesNotThrowFzT_Vs5Int32
//CHECK-NOT: builtin "willThrow"
//CHECK: return
func DoesNotThrow() throws -> Int32 {
_ = try IThrow()
return 2
}
// rdar://20782111
protocol Doomed {
func check() throws
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors12DoomedStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*DoomedStruct
// CHECK: [[T0:%.*]] = function_ref @_TFV6errors12DoomedStruct5check{{.*}} : $@convention(method) (DoomedStruct) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[SELF]])
// CHECK: bb1([[T0:%.*]] : $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: dealloc_stack [[TEMP]]
// CHECK: throw [[T0]] : $Error
struct DoomedStruct : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors11DoomedClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error Error {
// CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*DoomedClass
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> (), $@convention(method) (@guaranteed DoomedClass) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[BORROWED_SELF]])
// CHECK: bb1([[T0:%.*]] : $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK: destroy_value [[SELF]] : $DoomedClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK: destroy_value [[SELF]] : $DoomedClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: throw [[T0]] : $Error
class DoomedClass : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors11HappyStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*HappyStruct
// CHECK: [[T0:%.*]] = function_ref @_TFV6errors11HappyStruct5check{{.*}} : $@convention(method) (HappyStruct) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T1]] : $()
struct HappyStruct : Doomed {
func check() {}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors10HappyClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*HappyClass
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> (), $@convention(method) (@guaranteed HappyClass) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF]])
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK: destroy_value [[SELF]] : $HappyClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T1]] : $()
class HappyClass : Doomed {
func check() {}
}
func create<T>(_ fn: () throws -> T) throws -> T {
return try fn()
}
func testThunk(_ fn: () throws -> Int) throws -> Int {
return try create(fn)
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSizoPs5Error__XFo__iSizoPS___ : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error)
// CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error Error)):
// CHECK: try_apply %1()
// CHECK: bb1([[T0:%.*]] : $Int):
// CHECK: store [[T0]] to [trivial] %0 : $*Int
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: return [[T0]]
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: throw [[T0]] : $Error
func createInt(_ fn: () -> Int) throws {}
func testForceTry(_ fn: () -> Int) {
try! createInt(fn)
}
// CHECK-LABEL: sil hidden @_TF6errors12testForceTryFFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> ()
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> Int):
// CHECK: [[FUNC:%.*]] = function_ref @_TF6errors9createIntFzFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @error Error
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: try_apply [[FUNC]]([[ARG_COPY]])
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return
// CHECK: builtin "unexpectedError"
// CHECK: unreachable
func testForceTryMultiple() {
_ = try! (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_TF6errors20testForceTryMultipleFT_T_
// CHECK-NEXT: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat)
// CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error)
// CHECK-NEXT: unreachable
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors20testForceTryMultipleFT_T_'
// Make sure we balance scopes correctly inside a switch.
// <rdar://problem/20923654>
enum CatFood {
case Canned
case Dry
}
// Something we can switch on that throws.
func preferredFood() throws -> CatFood {
return CatFood.Canned
}
func feedCat() throws -> Int {
switch try preferredFood() {
case .Canned:
return 0
case .Dry:
return 1
}
}
// CHECK-LABEL: sil hidden @_TF6errors7feedCatFzT_Si : $@convention(thin) () -> (Int, @error Error)
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: %1 = function_ref @_TF6errors13preferredFoodFzT_OS_7CatFood : $@convention(thin) () -> (CatFood, @error Error)
// CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5
// CHECK: bb1([[VAL:%.*]] : $CatFood):
// CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3
// CHECK: bb5([[ERROR:%.*]] : $Error)
// CHECK: throw [[ERROR]] : $Error
// Throwing statements inside cases.
func getHungryCat(_ food: CatFood) throws -> Cat {
switch food {
case .Canned:
return try make_a_cat()
case .Dry:
return try dont_make_a_cat()
}
}
// errors.getHungryCat throws (errors.CatFood) -> errors.Cat
// CHECK-LABEL: sil hidden @_TF6errors12getHungryCatFzOS_7CatFoodCS_3Cat : $@convention(thin) (CatFood) -> (@owned Cat, @error Error)
// CHECK: bb0(%0 : $CatFood):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3
// CHECK: bb1:
// CHECK: [[FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6
// CHECK: bb3:
// CHECK: [[FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7
// CHECK: bb6([[ERROR:%.*]] : $Error):
// CHECK: br bb8([[ERROR:%.*]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : $Error):
// CHECK: br bb8([[ERROR]] : $Error)
// CHECK: bb8([[ERROR:%.*]] : $Error):
// CHECK: throw [[ERROR]] : $Error
func take_many_cats(_ cats: Cat...) throws {}
func test_variadic(_ cat: Cat) throws {
try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_TF6errors13test_variadicFzCS_3CatT_ : $@convention(thin) (@owned Cat) -> @error Error {
// CHECK: bb0([[ARG:%.*]] : $Cat):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: [[TAKE_FN:%.*]] = function_ref @_TF6errors14take_many_catsFztGSaCS_3Cat__T_ : $@convention(thin) (@owned Array<Cat>) -> @error Error
// CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4
// CHECK: [[T0:%.*]] = function_ref @_TFs27_allocateUninitializedArray
// CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]])
// CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]]
// CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 0
// CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]]
// CHECK: [[T2:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 1
// CHECK: end_borrow [[BORROWED_T1]] from [[T1]]
// CHECK: destroy_value [[T1]]
// CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat
// Element 0.
// CHECK: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]]
// CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]]
// Element 1.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1
// CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]]
// Element 2.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2
// CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]]
// CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]]
// Element 3.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3
// CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]]
// CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]]
// Complete the call and return.
// CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]]
// CHECK: [[NORM_CALL]]([[T0:%.*]] : $()):
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: destroy_value [[ARG]] : $Cat
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return
// Failure from element 0.
// CHECK: [[ERR_0]]([[ERROR:%.*]] : $Error):
// CHECK-NOT: end_borrow
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error)
// Failure from element 2.
// CHECK: [[ERR_2]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from element 3.
// CHECK: [[ERR_3]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_addr [[ELT2]]
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from call.
// CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Rethrow.
// CHECK: [[RETHROW]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ARG]] : $Cat
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors13test_variadicFzCS_3CatT_'
// rdar://20861374
// Clear out the self box before delegating.
class BaseThrowingInit : HasThrowingInit {
var subField: Int
init(value: Int, subField: Int) throws {
self.subField = subField
try super.init(value: value)
}
}
// CHECK: sil hidden @_TFC6errors16BaseThrowingInitc{{.*}} : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error)
// CHECK: [[BOX:%.*]] = alloc_box ${ var BaseThrowingInit }
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[PB]]
// Initialize subField.
// CHECK: [[T0:%.*]] = load_borrow [[MARKED_BOX]]
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField
// CHECK-NEXT: assign %1 to [[T1]]
// CHECK-NEXT: end_borrow [[T0]] from [[MARKED_BOX]]
// Super delegation.
// CHECK-NEXT: [[T0:%.*]] = load [take] [[MARKED_BOX]]
// CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit
// CHECK: [[T3:%[0-9]+]] = function_ref @_TFC6errors15HasThrowingInitcfzT5valueSi_S0_ : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: apply [[T3]](%0, [[T2]])
// Cleanups for writebacks.
protocol Supportable {
mutating func support() throws
}
protocol Buildable {
associatedtype Structure : Supportable
var firstStructure: Structure { get set }
subscript(name: String) -> Structure { get set }
}
func supportFirstStructure<B: Buildable>(_ b: inout B) throws {
try b.firstStructure.support()
}
// CHECK-LABEL: sil hidden @_TF6errors21supportFirstStructure{{.*}} : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error {
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]])
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: throw [[ERROR]]
func supportStructure<B: Buildable>(_ b: inout B, name: String) throws {
try b[name].support()
}
// CHECK-LABEL: sil hidden @_TF6errors16supportStructure
// CHECK: bb0({{.*}}, [[INDEX:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: [[BORROWED_INDEX:%.*]] = begin_borrow [[INDEX]]
// CHECK: [[INDEX_COPY:%.*]] = copy_value [[BORROWED_INDEX]] : $String
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[INDEX_COPY]], [[BASE:%[0-9]*]])
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: end_borrow [[BORROWED_INDEX]] from [[INDEX]]
// CHECK: destroy_value [[INDEX]] : $String
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: destroy_value [[INDEX]] : $String
// CHECK: throw [[ERROR]]
struct Pylon {
var name: String
mutating func support() throws {}
}
struct Bridge {
var mainPylon : Pylon
subscript(name: String) -> Pylon {
get {
return mainPylon
}
set {}
}
}
func supportStructure(_ b: inout Bridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_ : $@convention(thin) (@inout Bridge, @owned String) -> @error Error {
// CHECK: bb0([[ARG1:%.*]] : $*Bridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support
// CHECK-NEXT: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
// CHECK-NEXT: [[INDEX_COPY_1:%.*]] = copy_value [[BORROWED_ARG2]] : $String
// CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon
// CHECK-NEXT: [[BASE:%.*]] = load_borrow [[ARG1]] : $*Bridge
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFV6errors6Bridgeg9subscriptFSSVS_5Pylon :
// CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]])
// CHECK-NEXT: store [[T0]] to [init] [[TEMP]]
// CHECK-NEXT: end_borrow [[BASE]] from [[ARG1]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[ARG1]])
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: end_borrow [[BORROWED_INDEX]] from [[INDEX]]
// CHECK-NEXT: destroy_value [[INDEX]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// We end up with ugly redundancy here because we don't want to
// consume things during cleanup emission. It's questionable.
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]]
// CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[ARG1]])
// CHECK-NEXT: destroy_addr [[TEMP]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
// ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY
// CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String
// CHECK-NEXT: end_borrow [[BORROWED_INDEX]] from [[INDEX]]
// CHECK-NEXT: destroy_value [[INDEX]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_'
struct OwnedBridge {
var owner : Builtin.UnknownObject
subscript(name: String) -> Pylon {
addressWithOwner { return (someValidPointer(), owner) }
mutableAddressWithOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout OwnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_ :
// CHECK: bb0([[ARG1:%.*]] : $*OwnedBridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support
// CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors11OwnedBridgeaO9subscriptFSSVS_5Pylon :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]])
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
// CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1
// CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_'
struct PinnedBridge {
var owner : Builtin.NativeObject
subscript(name: String) -> Pylon {
addressWithPinnedNativeOwner { return (someValidPointer(), owner) }
mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout PinnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_ :
// CHECK: bb0([[ARG1:%.*]] : $*PinnedBridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support
// CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors12PinnedBridgeap9subscriptFSSVS_5Pylon :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]])
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
// CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1
// CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]]
// CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: destroy_value [[OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_'
// ! peepholes its argument with getSemanticsProvidingExpr().
// Test that that doesn't look through try!.
// rdar://21515402
func testForcePeephole(_ f: () throws -> Int?) -> Int {
let x = (try! f())!
return x
}
// CHECK-LABEL: sil hidden @_TF6errors15testOptionalTryFT_T_
// CHECK-NEXT: bb0:
// CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>)
// CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>)
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors15testOptionalTryFT_T_'
func testOptionalTry() {
_ = try? make_a_cat()
}
// CHECK-LABEL: sil hidden @_TF6errors18testOptionalTryVarFT_T_
// CHECK-NEXT: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<Cat> }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat)
// CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<Cat> }
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors18testOptionalTryVarFT_T_'
func testOptionalTryVar() {
var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_TF6errors26testOptionalTryAddressOnly
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return
// CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : $()):
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors26testOptionalTryAddressOnlyurFxT_'
func testOptionalTryAddressOnly<T>(_ obj: T) {
_ = try? dont_return(obj)
}
// CHECK-LABEL: sil hidden @_TF6errors29testOptionalTryAddressOnlyVar
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return
// CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : $()):
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors29testOptionalTryAddressOnlyVarurFxT_'
func testOptionalTryAddressOnlyVar<T>(_ obj: T) {
var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_TF6errors23testOptionalTryMultipleFT_T_
// CHECK: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat)
// CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>)
// CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>)
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors23testOptionalTryMultipleFT_T_'
func testOptionalTryMultiple() {
_ = try? (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_TF6errors25testOptionalTryNeverFailsFT_T_
// CHECK: bb0:
// CHECK-NEXT: [[VALUE:%.+]] = tuple ()
// CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '_TF6errors25testOptionalTryNeverFailsFT_T_'
func testOptionalTryNeverFails() {
_ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @_TF6errors28testOptionalTryNeverFailsVarFT_T_
// CHECK: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<()> }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<()> }
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '_TF6errors28testOptionalTryNeverFailsVarFT_T_'
func testOptionalTryNeverFailsVar() {
var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_TF6errors36testOptionalTryNeverFailsAddressOnly
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '_TF6errors36testOptionalTryNeverFailsAddressOnlyurFxT_'
func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) {
_ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @_TF6errors39testOptionalTryNeverFailsAddressOnlyVar
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '_TFC6errors13OtherErrorSubCfT_S0_'
func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) {
var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
class SomeErrorClass : Error { }
// CHECK-LABEL: sil_vtable SomeErrorClass
// CHECK-NEXT: #SomeErrorClass.deinit!deallocator: _TFC6errors14SomeErrorClassD
// CHECK-NEXT: #SomeErrorClass.init!initializer.1: {{.*}} : _TFC6errors14SomeErrorClasscfT_S0_
// CHECK-NEXT: }
class OtherErrorSub : OtherError { }
// CHECK-LABEL: sil_vtable OtherErrorSub {
// CHECK-NEXT: #OtherError.init!initializer.1: {{.*}} : _TFC6errors13OtherErrorSubcfT_S0_ // OtherErrorSub.init() -> OtherErrorSub
// CHECK-NEXT: #OtherErrorSub.deinit!deallocator: _TFC6errors13OtherErrorSubD // OtherErrorSub.__deallocating_deinit
// CHECK-NEXT:}
| apache-2.0 | ee6dcb2827d5720f7daf40c14564bbf3 | 48.509989 | 234 | 0.601861 | 3.185441 | false | false | false | false |
mita4829/Iris | Iris/ViewController.swift | 1 | 6744 | //
// ViewController.swift
// Iris
//
// Created by Michael Tang on 4/22/17.
// Copyright (c) 2017 Michael Tang. All rights reserved.
// Tesseract OCR, Lyndsey Scott
import UIKit
import Foundation
class ViewController: UIViewController, UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var buttonGuardView: UIView!
@IBOutlet weak var firstLaunch: UIView!
var activityIndicator:UIActivityIndicatorView!
var messageToSendToBrailleController = String()
override func viewDidLoad() {
super.viewDidLoad()
checkFirstLaunch()
textView.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
//Helper func to dismiss welcome screen
@IBAction func dismissFirstLaunch(_ sender: UIButton) {
self.view.viewWithTag(1)?.removeFromSuperview()
}
//Dismiss first responder for keyboard
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if(text == "\n"){
textView.resignFirstResponder()
return false
}
return true
}
//Camera
@IBAction func analyzePhoto(_ sender: UIButton) {
view.endEditing(true)
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera;
//imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}else{
print("Mac cannot support camera")
}
}
//Photo Library
@IBAction func analyzeSavedPhoto(_ sender: UIButton) {
view.endEditing(true)
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
self.present(imagePicker,animated: true,completion: nil)
}
func scaleImage(image: UIImage, maxDimension: CGFloat) -> UIImage {
var scaledSize = CGSize(width: maxDimension, height: maxDimension)
var scaleFactor:CGFloat
if image.size.width > image.size.height {
scaleFactor = image.size.height / image.size.width
scaledSize.width = maxDimension
scaledSize.height = scaledSize.width * scaleFactor
} else {
scaleFactor = image.size.width / image.size.height
scaledSize.height = maxDimension
scaledSize.width = scaledSize.height * scaleFactor
}
UIGraphicsBeginImageContext(scaledSize)
image.draw(in: CGRect(x:0, y:0, width:scaledSize.width, height:scaledSize.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
// Activity Indicator methods
func addActivityIndicator() {
activityIndicator = UIActivityIndicatorView(frame: view.bounds)
activityIndicator.activityIndicatorViewStyle = .whiteLarge
activityIndicator.backgroundColor = UIColor(white: 0, alpha: 0.25)
activityIndicator.startAnimating()
view.addSubview(activityIndicator)
}
func removeActivityIndicator() {
activityIndicator.removeFromSuperview()
activityIndicator = nil
}
@IBAction func brailleTranslation(_ sender: UIButton) {
if(textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty){
let alertController = UIAlertController(title: "Braille Translation", message: "Cannot translate empty text to braille", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "continue", style: UIAlertActionStyle.default) {
(result : UIAlertAction) -> Void in
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
return
}
//remove newline, spaces, and non-alpnum char
let lower = textView.text.lowercased()
let noSpace = lower.replacingOccurrences(of: "\n", with: " ")
let regex = String(noSpace.characters.filter { "01234567890abcdefghijklmnopqrstuvwxyz ".characters.contains($0) })
//regex is the string containing no non-alphanum and no newlines
messageToSendToBrailleController = regex
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationController : BrailleController = segue.destination as! BrailleController
destinationController.messageFromViewController = messageToSendToBrailleController
}
func performImageRecognition(image: UIImage) {
// 1
let tesseract = G8Tesseract()
// 2
tesseract.language = "eng+fra"
// 3
tesseract.engineMode = .tesseractCubeCombined
// 4
tesseract.pageSegmentationMode = .auto
// 5
tesseract.maximumRecognitionTime = 60.0
// 6
tesseract.image = image.g8_blackAndWhite()
tesseract.recognize()
// 7
textView.text = tesseract.recognizedText
textView.isEditable = true
// 8
removeActivityIndicator()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let selectedPhoto = info[UIImagePickerControllerOriginalImage] as? UIImage{
//let selectedPhoto = info[UIImagePickerControllerOriginalImage] as? UIImage
let scaledImage = scaleImage(image: selectedPhoto, maxDimension: 640)
addActivityIndicator()
dismiss(animated: true, completion: {
self.performImageRecognition(image: scaledImage)
})
}
}
func checkFirstLaunch() -> Void {
//Check if it's the first launch, if so, show welcome message
if(!UserDefaults.standard.bool(forKey: "HasLaunchedOnce")){
//update device state
UserDefaults.standard.set(true, forKey: "HasLaunchedOnce")
UserDefaults.standard.synchronize()
//UI effects
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
visualEffectView.frame = UIScreen.main.bounds
firstLaunch.insertSubview(visualEffectView, at: 0)
firstLaunch.isHidden = false
return
}
}
}
| apache-2.0 | 61a2609447b3a3380c1302590e4d35fe | 35.064171 | 178 | 0.645907 | 5.546053 | false | false | false | false |
material-motion/apidiff | apple/diffreport/Sources/diffreportlib/diffreport.swift | 1 | 12177 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
public typealias JSONObject = Any
typealias SourceKittenNode = [String: Any]
typealias APINode = [String: Any]
typealias ApiNameNodeMap = [String: APINode]
/** A type of API change. */
public enum ApiChange {
case addition(apiType: String, name: String)
case deletion(apiType: String, name: String)
case modification(apiType: String, name: String, modificationType: String, from: String, to: String)
}
/** Generates an API diff report from two SourceKitten JSON outputs. */
public func diffreport(oldApi: JSONObject, newApi: JSONObject) throws -> [String: [ApiChange]] {
let oldApiNameNodeMap = extractAPINodeMap(from: oldApi as! [SourceKittenNode])
let newApiNameNodeMap = extractAPINodeMap(from: newApi as! [SourceKittenNode])
let oldApiNames = Set(oldApiNameNodeMap.keys)
let newApiNames = Set(newApiNameNodeMap.keys)
let addedApiNames = newApiNames.subtracting(oldApiNames)
let deletedApiNames = oldApiNames.subtracting(newApiNames)
let persistedApiNames = oldApiNames.intersection(newApiNames)
var changes: [String: [ApiChange]] = [:]
// Additions
for usr in (addedApiNames.map { usr in newApiNameNodeMap[usr]! }.sorted(by: apiNodeIsOrderedBefore)) {
let apiType = prettyString(forKind: usr["key.kind"] as! String)
let name = prettyName(forApi: usr, apis: newApiNameNodeMap)
let root = rootName(forApi: usr, apis: newApiNameNodeMap)
changes[root, withDefault: []].append(.addition(apiType: apiType, name: name))
}
// Deletions
for usr in (deletedApiNames.map { usr in oldApiNameNodeMap[usr]! }.sorted(by: apiNodeIsOrderedBefore)) {
let apiType = prettyString(forKind: usr["key.kind"] as! String)
let name = prettyName(forApi: usr, apis: oldApiNameNodeMap)
let root = rootName(forApi: usr, apis: oldApiNameNodeMap)
changes[root, withDefault: []].append(.deletion(apiType: apiType, name: name))
}
// Modifications
let ignoredKeys = Set(arrayLiteral: "key.doc.line", "key.parsed_scope.end", "key.parsed_scope.start", "key.doc.column", "key.doc.comment", "key.bodyoffset", "key.nameoffset", "key.doc.full_as_xml", "key.offset", "key.fully_annotated_decl", "key.length", "key.bodylength", "key.namelength", "key.annotated_decl", "key.doc.parameters", "key.elements", "key.related_decls")
for usr in persistedApiNames {
let oldApi = oldApiNameNodeMap[usr]!
let newApi = newApiNameNodeMap[usr]!
let root = rootName(forApi: newApi, apis: newApiNameNodeMap)
let allKeys = Set(oldApi.keys).union(Set(newApi.keys))
for key in allKeys {
if ignoredKeys.contains(key) {
continue
}
if let oldValue = oldApi[key] as? String, let newValue = newApi[key] as? String, oldValue != newValue {
let apiType = prettyString(forKind: newApi["key.kind"] as! String)
let name = prettyName(forApi: newApi, apis: newApiNameNodeMap)
let modificationType = prettyString(forModificationKind: key)
if apiType == "class" && key == "key.parsed_declaration" {
// Ignore declarations for classes because it's a complete representation of the class's
// code, which is not helpful diff information.
continue
}
changes[root, withDefault: []].append(.modification(apiType: apiType,
name: name,
modificationType: modificationType,
from: oldValue,
to: newValue))
}
}
}
return changes
}
extension ApiChange {
public func toMarkdown() -> String {
switch self {
case .addition(let apiType, let name):
return "*new* \(apiType): \(name)"
case .deletion(let apiType, let name):
return "*removed* \(apiType): \(name)"
case .modification(let apiType, let name, let modificationType, let from, let to):
return [
"*modified* \(apiType): \(name)",
"",
"| Type of change: | \(modificationType) |",
"|---|---|",
"| From: | `\(from.replacingOccurrences(of: "\n", with: " "))` |",
"| To: | `\(to.replacingOccurrences(of: "\n", with: " "))` |"
].joined(separator: "\n")
}
}
}
extension ApiChange: Equatable {}
public func == (left: ApiChange, right: ApiChange) -> Bool {
switch (left, right) {
case (let .addition(apiType, name), let .addition(apiType2, name2)):
return apiType == apiType2 && name == name2
case (let .deletion(apiType, name), let .deletion(apiType2, name2)):
return apiType == apiType2 && name == name2
case (let .modification(apiType, name, modificationType, from, to),
let .modification(apiType2, name2, modificationType2, from2, to2)):
return apiType == apiType2 && name == name2 && modificationType == modificationType2 && from == from2 && to == to2
default:
return false
}
}
/**
get-with-default API for Dictionary
Example usage: dict[key, withDefault: []]
*/
extension Dictionary {
subscript(key: Key, withDefault value: @autoclosure () -> Value) -> Value {
mutating get {
if self[key] == nil {
self[key] = value()
}
return self[key]!
}
set {
self[key] = newValue
}
}
}
/**
Sorting function for APINode instances.
Sorts by filename.
Example usage: sorted(by: apiNodeIsOrderedBefore)
*/
func apiNodeIsOrderedBefore(prev: APINode, next: APINode) -> Bool {
if let prevFile = prev["key.doc.file"] as? String, let nextFile = next["key.doc.file"] as? String {
return prevFile < nextFile
}
return false
}
/** Union two dictionaries, preferring existing values if they possess a parent.usr key. */
func += (left: inout ApiNameNodeMap, right: ApiNameNodeMap) {
for (k, v) in right {
if left[k] == nil {
left.updateValue(v, forKey: k)
} else if let object = left[k], object["parent.usr"] == nil {
left.updateValue(v, forKey: k)
}
}
}
func prettyString(forKind kind: String) -> String {
if let pretty = [
// Objective-C
"sourcekitten.source.lang.objc.decl.protocol": "protocol",
"sourcekitten.source.lang.objc.decl.typedef": "typedef",
"sourcekitten.source.lang.objc.decl.method.instance": "method",
"sourcekitten.source.lang.objc.decl.property": "property",
"sourcekitten.source.lang.objc.decl.class": "class",
"sourcekitten.source.lang.objc.decl.constant": "constant",
"sourcekitten.source.lang.objc.decl.enum": "enum",
"sourcekitten.source.lang.objc.decl.enumcase": "enum value",
"sourcekitten.source.lang.objc.decl.category": "category",
"sourcekitten.source.lang.objc.decl.method.class": "class method",
"sourcekitten.source.lang.objc.decl.struct": "struct",
"sourcekitten.source.lang.objc.decl.field": "field",
// Swift
"source.lang.swift.decl.function.method.static": "static method",
"source.lang.swift.decl.function.method.instance": "method",
"source.lang.swift.decl.var.instance": "var",
"source.lang.swift.decl.class": "class",
"source.lang.swift.decl.var.static": "static var",
"source.lang.swift.decl.enum": "enum",
"source.lang.swift.decl.function.free": "function",
"source.lang.swift.decl.var.global": "global var",
"source.lang.swift.decl.protocol": "protocol",
"source.lang.swift.decl.enumelement": "enum value"
][kind] {
return pretty
}
return kind
}
func prettyString(forModificationKind kind: String) -> String {
switch kind {
case "key.swift_declaration": return "Swift declaration"
case "key.parsed_declaration": return "Declaration"
case "key.doc.declaration": return "Declaration"
case "key.typename": return "Declaration"
case "key.always_deprecated": return "Deprecation"
case "key.deprecation_message": return "Deprecation message"
default: return kind
}
}
/** Walk the APINode to the root node. */
func rootName(forApi api: APINode, apis: ApiNameNodeMap) -> String {
let name = api["key.name"] as! String
if let parentUsr = api["parent.usr"] as? String, let parentApi = apis[parentUsr] {
return rootName(forApi: parentApi, apis: apis)
}
return name
}
func prettyName(forApi api: APINode, apis: ApiNameNodeMap) -> String {
let name = api["key.name"] as! String
if let parentUsr = api["parent.usr"] as? String, let parentApi = apis[parentUsr] {
return "`\(name)` in \(prettyName(forApi: parentApi, apis: apis))"
}
return "`\(name)`"
}
/** Normalize data contained in an API node json dictionary. */
func apiNode(from sourceKittenNode: SourceKittenNode) -> APINode {
var data = sourceKittenNode
data.removeValue(forKey: "key.substructure")
for (key, value) in data {
data[key] = String(describing: value)
}
return data
}
/**
Recursively iterate over each sourcekitten node and extract a flattened map of USR identifier to
APINode instance.
*/
func extractAPINodeMap(from sourceKittenNodes: [SourceKittenNode]) -> ApiNameNodeMap {
var map: ApiNameNodeMap = [:]
for file in sourceKittenNodes {
for (_, information) in file {
let substructure = (information as! SourceKittenNode)["key.substructure"] as! [SourceKittenNode]
for jsonNode in substructure {
map += extractAPINodeMap(from: jsonNode)
}
}
}
return map
}
/**
Recursively iterate over a sourcekitten node and extract a flattened map of USR identifier to
APINode instance.
*/
func extractAPINodeMap(from sourceKittenNode: SourceKittenNode, parentUsr: String? = nil) -> ApiNameNodeMap {
var map: ApiNameNodeMap = [:]
for (key, value) in sourceKittenNode {
switch key {
case "key.usr":
if let accessibility = sourceKittenNode["key.accessibility"] {
if accessibility as! String != "source.lang.swift.accessibility.public" {
continue
}
} else if let kind = sourceKittenNode["key.kind"] as? String, kind == "source.lang.swift.decl.extension" {
continue
}
var node = apiNode(from: sourceKittenNode)
// Create a reference to the parent node
node["parent.usr"] = parentUsr
// Store the API node in the map
map[value as! String] = node
case "key.substructure":
let substructure = value as! [SourceKittenNode]
for subSourceKittenNode in substructure {
map += extractAPINodeMap(from: subSourceKittenNode, parentUsr: sourceKittenNode["key.usr"] as? String)
}
default:
continue
}
}
return map
}
/**
Execute sourcekitten with a given umbrella header.
Only meant to be used in unit test builds.
@param header Absolute path to an umbrella header.
*/
func runSourceKitten(withHeader header: String) throws -> JSONObject {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = [
"/usr/local/bin/sourcekitten",
"doc",
"--objc",
header,
"--",
"-x",
"objective-c",
]
let standardOutput = Pipe()
task.standardOutput = standardOutput
task.launch()
task.waitUntilExit()
var data = standardOutput.fileHandleForReading.readDataToEndOfFile()
let tmpDir = ProcessInfo.processInfo.environment["TMPDIR"]!.replacingOccurrences(of: "/", with: "\\/")
let string = String(data: data, encoding: String.Encoding.utf8)!
.replacingOccurrences(of: tmpDir + "old\\/", with: "")
.replacingOccurrences(of: tmpDir + "new\\/", with: "")
data = string.data(using: String.Encoding.utf8)!
return try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0))
}
| apache-2.0 | 2ab833f3339aab447b5899b8b1b55990 | 35.458084 | 372 | 0.671922 | 3.778157 | false | false | false | false |
danthorpe/Examples | TaylorSource/Gallery/Gallery/Model.swift | 1 | 6879 | //
// Model.swift
// Gallery
//
// Created by Daniel Thorpe on 07/07/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
import MapKit
import FlickrKit
import YapDatabase
import ValueCoding
import YapDatabaseExtensions
import TaylorSource
class Photo: NSObject, NSCoding, Identifiable, Persistable {
struct Location {
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
var region: MKCoordinateRegion {
return MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
}
}
static let collection = "Photos"
static var photoSize: FKPhotoSize = {
switch UIScreen.mainScreen().scale {
case 0...1:
return FKPhotoSizeMedium800
case 1...2:
return FKPhotoSizeLarge1600
default:
return FKPhotoSizeLarge2048
}
}()
static var dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
return formatter
}()
static var flickrDateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
let identifier: Identifier
let date: NSDate
let url: NSURL
let title: String
let location: Location?
let info: String?
let tags: String?
private init(id: Identifier, date: NSDate, url: NSURL, title: String, location: Location? = .None, info: String? = .None, tags: String? = .None) {
self.identifier = id
self.date = date
self.url = url
self.title = title
self.location = location
self.info = info
self.tags = tags
}
required init(coder aDecoder: NSCoder) {
identifier = aDecoder.decodeObjectForKey("identifier") as! String
date = aDecoder.decodeObjectForKey("date") as! NSDate
url = aDecoder.decodeObjectForKey("url") as! NSURL
title = aDecoder.decodeObjectForKey("title") as! String
location = Photo.Location.decode(aDecoder.decodeObjectForKey("location"))
info = aDecoder.decodeObjectForKey("info") as? String
tags = aDecoder.decodeObjectForKey("tags") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(identifier, forKey: "identifier")
aCoder.encodeObject(date, forKey: "date")
aCoder.encodeObject(url, forKey: "url")
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(location?.encoded, forKey: "location")
aCoder.encodeObject(info, forKey: "info")
aCoder.encodeObject(tags, forKey: "tags")
}
}
extension Photo.Location: ValueCoding {
typealias Coder = PhotoLocationCoder
}
class PhotoLocationCoder: NSObject, NSCoding, CodingType {
let value: Photo.Location
required init(_ v: Photo.Location) {
value = v
}
required init(coder aDecoder: NSCoder) {
let latitude = aDecoder.decodeDoubleForKey("latitude")
let longitude = aDecoder.decodeDoubleForKey("longitude")
value = Photo.Location(latitude: latitude, longitude: longitude)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeDouble(value.latitude, forKey: "latitude")
aCoder.encodeDouble(value.longitude, forKey: "longitude")
}
}
// MARK: - Database Views
func photosForDate(date: NSDate) -> YapDB.Fetch {
let grouping: YapDB.View.Grouping = .ByObject({ (_, collection, key, object) -> String! in
if collection == Photo.collection {
if let photo = object as? Photo {
return Photo.dateFormatter.stringFromDate(photo.date)
}
}
return .None
})
let sorting: YapDB.View.Sorting = .ByKey({ (_, group, collection1, key1, collection2, key2) -> NSComparisonResult in
return .OrderedSame
})
let view = YapDB.View(name: Photo.collection, grouping: grouping, sorting: sorting, collections: [Photo.collection])
return .View(view)
}
func photosForDate(date: NSDate, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> YapDB.FetchConfiguration {
return YapDB.FetchConfiguration(fetch: photosForDate(date), block: mappingBlock)
}
func photosForDate(date: NSDate, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> Configuration<Photo> {
return Configuration(fetch: photosForDate(date, mappingBlock: mappingBlock)) { $0 as? Photo }
}
// MARK: - API
func loadPhotos(forDate date: NSDate = NSDate(), completion: (photos: [Photo]?, error: NSError?) -> Void) {
let flickr = FlickrKit.sharedFlickrKit()
let interesting = FKFlickrInterestingnessGetList()
interesting.extras = "description,geo,tags"
interesting.date = Photo.flickrDateFormatter.stringFromDate(date)
flickr.call(interesting) { (response, error) in
if let error = error {
completion(photos: .None, error: error)
}
else if let data = (response as NSDictionary).valueForKeyPath("photos.photo") as? [[NSObject : AnyObject]] {
let photos = data.reduce([Photo]()) { (var acc, data) -> [Photo] in
if let photo = Photo.createFromDictionary(data, withDate: date, usingFlickr: flickr) {
acc.append(photo)
}
return acc
}
completion(photos: photos, error: nil)
}
}
}
extension Photo {
static func createFromDictionary(data: [NSObject : AnyObject], withDate date: NSDate, usingFlickr flickr: FlickrKit = FlickrKit.sharedFlickrKit()) -> Photo? {
let url = flickr.photoURLForSize(Photo.photoSize, fromPhotoDictionary: data)
if let identifier = data["id"] as? Identifier,
let title = data["title"] as? String {
let location = Photo.Location.createFromDictionary(data)
let info = (data as NSDictionary).valueForKeyPath("description._content") as? String
let tags = data["tags"] as? String
return Photo(id: identifier, date: date, url: url, title: title, location: location, info: info, tags: tags)
}
return .None
}
}
extension Photo.Location {
static func createFromDictionary(data: [NSObject : AnyObject]) -> Photo.Location? {
if let latitude = data["latitude"] as? NSNumber,
let longitude = data["longitude"] as? NSNumber {
if latitude.doubleValue != 0.000 && longitude.doubleValue != 0.000 {
return Photo.Location(latitude: latitude.doubleValue, longitude: longitude.doubleValue)
}
}
return .None
}
}
| mit | 2aebcfdf56e559d6e8a0eb37c6b970dc | 31.295775 | 162 | 0.647187 | 4.546596 | false | false | false | false |
wangxin20111/WXWeiBo | WXWeibo/WXWeibo/Classes/Home/View/WXSingleImgCell.swift | 1 | 1406 | //
// WXSingleImgCell.swift
// WXWeibo
//
// Created by 王鑫 on 16/7/26.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
import SDWebImage
let WXSingleImgCellIdentify = "WXSingleImgCellIdentify"
class WXSingleImgCell: UICollectionViewCell {
/// 背景照片
private lazy var imgView : UIImageView = {
let iv = UIImageView()
iv.backgroundColor = UIColor.greenColor()
return iv
}()
/// 对外的照片接口
var imgURL : NSURL?{
didSet{
imgView.sd_setImageWithURL(imgURL)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imgView)
setNeedsUpdateConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//类方法,用来快速创建对象用的
class func cellWithCollectionView(collectionView:UICollectionView,indexPath:NSIndexPath) -> UICollectionViewCell
{
collectionView.registerClass(WXSingleImgCell.self, forCellWithReuseIdentifier:WXSingleImgCellIdentify)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WXSingleImgCellIdentify, forIndexPath: indexPath)
return cell
}
override func updateConstraints() {
super.updateConstraints()
imgView.autoPinEdgesToSuperviewEdges()
}
}
| mit | 6948346106e36630018dfde792f75c73 | 27.617021 | 123 | 0.675836 | 4.92674 | false | false | false | false |
nickswalker/ASCIIfy | Example/ASCIIfyPlayground.playground/Contents.swift | 1 | 704 | import ASCIIfy
let flowerImage = #imageLiteral(resourceName: "flower.jpg")
let font = ASCIIConverter.defaultFont.withSize(24.0)
let result = flowerImage.fy_asciiImage(font)
let converter = ASCIIConverter(lut: LuminanceLookupTable())
converter.font = ASCIIConverter.defaultFont.withSize(96.0)
converter.backgroundColor = .black
converter.colorMode = .color
converter.columns = 40
let converterResult = converter.convertImage(flowerImage)
let colorConverter = ASCIIConverter(lut: ColorLookupTable())
colorConverter.font = ASCIIConverter.defaultFont.withSize(30.0)
colorConverter.backgroundColor = .black
colorConverter.columns = 30
let colorConverterResult = colorConverter.convertImage(flowerImage)
| mit | 8813149e694ff0859f4f78f03f02c625 | 32.52381 | 67 | 0.821023 | 3.955056 | false | false | false | false |
learning/colliery | TrackMix/TrackMix/AppDelegate.swift | 1 | 1154 | //
// AppDelegate.swift
// TrackMix
//
// Created by Learning on 14/11/19.
// Copyright (c) 2014年 Learning. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var textField: NSTextField!
@IBOutlet weak var slider: NSSlider!
var track: Track? = nil
@IBAction func mute(sender: AnyObject) {
self.track!.setVolume(0)
self.updateUserInterface()
}
@IBAction func takeFloatValueForVolumeFrom(sender: AnyObject) {
self.track!.setVolume(sender.floatValue)
self.updateUserInterface()
}
func updateUserInterface() {
var volume = self.track!.getVloume()
self.textField.floatValue = volume
self.slider.floatValue = volume
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
track = Track(volume: 5.0)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| gpl-2.0 | e0c57a8d4518d81ccb7bf8d65dc6e0ab | 23 | 71 | 0.671007 | 4.626506 | false | false | false | false |
jverkoey/FigmaKit | Sources/FigmaKit/LayoutConstraint.swift | 1 | 1453 | /// A Figma layout constraint.
///
/// "Layout constraint relative to containing Frame."
/// https://www.figma.com/developers/api#layoutconstraint-type
public struct LayoutConstraint: Codable {
/// The type of constraint to apply.
public let vertical: Vertical
/// See `ConstraintType` for effect of this field.
public let horizontal: Horizontal
public enum Vertical: String, Codable {
/// Node is laid out relative to top of the containing frame.
case top = "TOP"
/// Node is laid out relative to bottom of the containing frame.
case bottom = "BOTTOM"
/// Node is vertically centered relative to containing frame.
case center = "CENTER"
/// Both top and bottom of node are constrained relative to containing frame (node stretches with frame).
case topBottom = "TOP_BOTTOM"
/// Node scales vertically with containing frame.
case scale = "SCALE"
}
public enum Horizontal: String, Codable {
/// Node is laid out relative to left of the containing frame.
case left = "LEFT"
/// Node is laid out relative to right of the containing frame
case right = "RIGHT"
/// Node is horizontally centered relative to containing frame.
case center = "CENTER"
/// Both left and right of node are constrained relative to containing frame (node stretches with frame).
case leftRight = "LEFT_RIGHT"
/// Node scales horizontally with containing frame
case scale = "SCALE"
}
}
| apache-2.0 | 43d8a74086c1a5d98081a116846b5ab1 | 38.27027 | 109 | 0.701996 | 4.598101 | false | false | false | false |
volatilegg/FlyingNimbus | FlyingNimbus/Scenes/Home/HomeViewController.swift | 1 | 3805 | //
// HomeViewController.swift
// FlyingNimbus
//
// Created by Do Duc on 21/05/16.
// Copyright © 2016 Do Duc. All rights reserved.
//
import UIKit
import MapKit
import Bond
let centerHelsinki = CLLocationCoordinate2D(latitude: 60.1699, longitude: 24.9384)
class HomeViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
let mapView: MKMapView = MKMapView(frame: CGRect(x: 0, y: 0, width: CGSize.screenWidth(), height: CGSize.screenHeight()))
var listObserve: Observable<StationList> = Observable(StationList())
var currentLocation: Observable<CLLocationCoordinate2D> = Observable(centerHelsinki)
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = false
self.mapView.delegate = self
self.locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
mapView.showsUserLocation = true
setMapCenter(centerHelsinki)
self.view.addSubview(mapView)
listObserve.observeNext(with: { stationList in
self.addingAnnotation(stationList)
})
let locationButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
locationButton.setImage(UIImage(named: "location"), for: UIControlState())
locationButton.addTarget(self, action: #selector(HomeViewController.setMapCenterToCurrentLocation), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: locationButton)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshList()
}
func setMapCenter(_ location: CLLocationCoordinate2D) {
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
mapView.setRegion(region, animated: true)
}
func setMapCenterToCurrentLocation() {
setMapCenter(self.currentLocation.value)
}
func refreshList() {
WebServices.sharedInstance.fetchStationData().then { (lists) in
self.listObserve.next(lists)
}
}
func addingAnnotation(_ list: StationList) {
for station in list.lists {
let annotation = DDAnnotation(station: station)
mapView.addAnnotation(annotation)
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? DDAnnotation {
let reuseId = "bikePin"
var view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if view == nil {
view = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
view!.canShowCallout = true
view!.calloutOffset = CGPoint(x: -5, y: 5)
} else {
view!.annotation = annotation
}
view?.backgroundColor = UIColor.clear
view!.image = annotation.image
return view
}
return nil
}
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for view in views {
if (view.annotation?.isKind(of: MKUserLocation.self) == true) {
self.mapView.bringSubview(toFront: view)
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.currentLocation.next((manager.location?.coordinate)!)
}
}
| mit | 0dfb3f08fd966473dd496f931a999ff8 | 36.294118 | 128 | 0.662198 | 5.126685 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Vendor/MDCacheImage/MDCacheImage.swift | 1 | 6754 | //
// MDCacheImage.swift
//
// Created by midoks on 15/12/26.
// Copyright © 2015年 midoks. All rights reserved.
//
import UIKit
import SwiftyJSON
//MARK: - 扩展UIImageView方法 -
extension UIImageView{
//异步执行
public func asynTask(callback:@escaping ()->Void){
DispatchQueue.global().async {
callback()
}
}
//异步更新UI
public func asynTaskUI(callback:@escaping ()->Void){
DispatchQueue.global().async {
callback()
}
}
//图片设置
func MDCacheImage(url:String?, defaultImage:String?, isCache:Bool = true) {
if defaultImage != nil {
self.image = UIImage(named: defaultImage!)
}
//self.asynTask{
MDTask.shareInstance.asynTaskBack{
if isCache {
let data:NSData? = MDCacheImageCenter.readCacheFromUrl(url: url!)
if data != nil {
self.image = UIImage(data: data! as Data)
}else{
if defaultImage != nil {
self.image = UIImage(named: defaultImage!)
}
let URL:NSURL = NSURL(string: url!)!
let data:NSData? = NSData(contentsOf: URL as URL)
if data != nil {
//写缓存
MDCacheImageCenter.writeCacheToUrl(url: url!, data: data!)
MDTask.shareInstance.asynTaskFront(callback: {
self.image = UIImage(data: data! as Data)
})
}
}
} else {
let URL:NSURL = NSURL(string: url!)!
let data:NSData? = NSData(contentsOf: URL as URL)
if data != nil {
MDTask.shareInstance.asynTaskFront(callback: {
self.image = UIImage(data: data! as Data)
})
}
}
}
}
}
//图片缓存控制中心
class MDCacheImageCenter: NSObject {
private static var cacheDirName = "MDCache"
private static var fm = FileManager.default
//设置缓存文件
static func setCacheDir(dirName:String){
self.cacheDirName = dirName
}
//读取缓存文件
static func readCacheFromUrl(url:String) -> NSData?{
var data:NSData?
let path:String = MDCacheImageCenter.getFullCachePathFromUrl(url: url)
if FileManager.default.fileExists(atPath: path) {
data = NSData(contentsOfFile: path)
}
return data
}
//写到缓存文件中去
static func writeCacheToUrl(url:String, data:NSData){
let path:String = MDCacheImageCenter.getFullCachePathFromUrl(url: url)
data.write(toFile: path, atomically: true)
}
//设置缓存路径
static func getFullCachePathFromUrl(url:String)->String{
let dirName = self.cacheDirName
var cachePath = NSHomeDirectory() + "/Library/Caches/" + dirName
let fm:FileManager=FileManager.default
fm.fileExists(atPath: cachePath)
if !(fm.fileExists(atPath: cachePath)) {
try! fm.createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil)
}
//进行字符串处理
let newURL = MDCacheImageCenter.stringToMDString(str: url as NSString)
cachePath = cachePath.appendingFormat("/%@", newURL)
//print(cachePath)
return cachePath
}
//删除所有缓存文件
static func removeAllCache(){
let dirName = self.cacheDirName
let cachePath = NSHomeDirectory() + "/Library/Caches/" + dirName
if fm.fileExists(atPath: cachePath) {
try! fm.removeItem(atPath: cachePath)
}
}
//字节大小类型
enum MDCacheImageType{
case B
case KB
case MB
case GB
case TB
case PB
case EB
case ZB
case YB
case BB
case NB
case DB
}
//统计缓存文件的大小
static func cacheSize() -> Float {
let dirName = self.cacheDirName
let cachePath = NSHomeDirectory() + "/Library/Caches/" + dirName
let size = self.calcCacheSize(path: cachePath)
return size
// switch(type){
// case .B: return size
// case .KB: return size/(pow(1024,1))
// case .MB: return size/(pow(1024,2))
// case .GB: return size/(pow(1024,3))
// case .TB: return size/(pow(1024,4))
// case .PB: return size/(pow(1024,5))
// case .EB: return size/(pow(1024,6))
// case .ZB: return size/(pow(1024,7))
// case .YB: return size/(pow(1024,8))
// case .BB: return size/(pow(1024,9))
// case .NB: return size/(pow(1024,10))
// case .DB: return size/(pow(1024,11))
// }
}
//获取合适的数据
static func getCacheSize() -> Float {
return self.cacheSize()
}
//计算路径下所有文件的大小
static func calcCacheSize(path:String) -> Float {
let list = try? fm.contentsOfDirectory(atPath: path)
if list == nil {
return 0.0
}
var size:Float = 0.0
let tmpDir = path + "/"
for i in list! {
let fpath = tmpDir + i
let isDir = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
fm.fileExists(atPath: fpath, isDirectory: isDir)
if(isDir.pointee.boolValue){
size += self.calcCacheSize(path: fpath)
} else {
//let attr = try! fm.attributesOfItem(atPath: fpath)
size += 0
}
}
return size
}
//移除特殊字符
static func stringToMDString(str:NSString)-> String{
let mdStr = str.components(separatedBy: "?")
let str:NSString = mdStr[0] as NSString
let newStr:NSMutableString = NSMutableString()
for i:NSInteger in 0 ..< str.length {
let c:unichar = str.character(at: i)
if (c>=48&&c<=57)||(c>=65&&c<=90)||(c>=97&&c<=122){
newStr.appendFormat("%c", c)
}
}
return (newStr.copy() as! String) + ".png"
}
}
| apache-2.0 | 492706dd4aa4ca89b871143429151b7b | 27.788546 | 106 | 0.501454 | 4.535045 | false | false | false | false |
wujianguo/YouPlay-iOS | YouPlay-iOS/Util.swift | 1 | 4216 | //
// Util.swift
// YouPlay-iOS
//
// Created by 吴建国 on 16/1/5.
// Copyright © 2016年 wujianguo. All rights reserved.
//
import UIKit
class Util {
static let imageCache = NSCache()
}
extension UIColor {
class func themeColor() -> UIColor { return UIColor.whiteColor().colorWithAlphaComponent(0.5) }
/**
* Initializes and returns a color object for the given RGB hex integer.
*/
public convenience init(rgb: Int) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat((rgb & 0x0000FF) >> 0) / 255.0,
alpha: 1)
}
public convenience init(colorString: String) {
var colorInt: UInt32 = 0
NSScanner(string: colorString).scanHexInt(&colorInt)
self.init(rgb: (Int) (colorInt ?? 0xaaaaaa))
}
}
import Alamofire
extension UIImageView {
class func requestImageWithUrlString(str: String?, complete: ((UIImage)->Void)? = nil) {
if let url = NSURL(string: str ?? "") {
requestImageWithUrl(url, complete: complete)
}
}
class func requestImageWithUrl(url: NSURL, complete: ((UIImage)->Void)? = nil) {
if let image = Util.imageCache.objectForKey(url) as? UIImage {
complete?(image)
return
}
Alamofire.request(.GET, url.absoluteString)
.responseData { response in
guard response.data != nil else { return }
if let img = UIImage(data: response.data!) {
Util.imageCache.setObject(img, forKey: url)
complete?(img)
}
}
}
func setImageWithUrlString(str: String?, complete: ((UIImage)->Void)? = nil) {
UIImageView.requestImageWithUrlString(str) { (image) -> Void in
self.image = image
complete?(image)
}
}
func setImageWithURL(url: NSURL, complete: ((UIImage)->Void)? = nil) {
UIImageView.requestImageWithUrl(url) { (image) -> Void in
self.image = image
complete?(image)
}
}
}
extension UIImage {
func lightEffectImage(bounds: CGRect) -> UIImage {
var img = self.applyLightEffectAtFrame(CGRectMake(0, 0, self.size.width, self.size.height))
UIGraphicsBeginImageContext(bounds.size);
img.drawInRect(bounds)
img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
func darkEffectImage(bounds: CGRect) -> UIImage {
var img = self.applyDarkEffectAtFrame(CGRectMake(0, 0, self.size.width, self.size.height))
UIGraphicsBeginImageContext(bounds.size);
img.drawInRect(bounds)
img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
func lightEffectColor(bounds: CGRect) -> UIColor {
let img = lightEffectImage(bounds)
return UIColor(patternImage: img)
}
func darkEffectColor(bounds: CGRect) -> UIColor {
let img = darkEffectImage(bounds)
return UIColor(patternImage: img)
}
}
extension UIView {
func setBackgroundLightEffect(url: String) {
let b = bounds
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { () -> Void in
UIImageView.requestImageWithUrlString(url) { (image) -> Void in
let color = image.lightEffectColor(b)
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.backgroundColor = color
}
}
}
}
func setBackgroundDarkEffect(url: String) {
let b = bounds
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { () -> Void in
UIImageView.requestImageWithUrlString(url) { (image) -> Void in
let color = image.darkEffectColor(b)
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.backgroundColor = color
}
}
}
}
}
| gpl-2.0 | 40703d868a467d07c13ce318c3b5f517 | 29.708029 | 104 | 0.584027 | 4.414481 | false | false | false | false |
DanielCech/Vapor-Catalogue | Sources/App/Controllers/AuthController.swift | 1 | 6418 | import Auth
import Core
import Foundation
import HTTP
import Punctual
import TurnstileCrypto
import Vapor
import VaporJWT
public final class AuthController {
typealias CreateUser = (Valid<Email>, Valid<Username>, User.Salt, User.Secret) -> User
typealias SaveUser = (inout User) throws -> Void
private let hash: HashProtocol
private let jwtKey: Bytes
private let createUser: CreateUser
private let saveUser: SaveUser
// used for testing
private let issueDate: Date?
private let passwordUpdate: Date?
public convenience init(jwtKey: Bytes, hash: HashProtocol) {
self.init(jwtKey: jwtKey,
hash: hash,
createUser: User.init(email:username:salt:secret:),
saveUser: { try $0.save() })
}
init(jwtKey: Bytes,
hash: HashProtocol,
issueDate: Date? = nil,
passwordUpdate: Date? = nil,
createUser: @escaping CreateUser,
saveUser: @escaping SaveUser) {
self.hash = hash
self.jwtKey = jwtKey
self.issueDate = issueDate
self.passwordUpdate = passwordUpdate
self.createUser = createUser
self.saveUser = saveUser
}
private func extractValues(_ data: Content) throws ->
(email: Email, username: Username?, password: Password, newPassword: Password?) {
guard let email = data["email"]?.string.map(Email.init) else {
throw Abort.custom(status: .badRequest, message: "Email is missing")
}
guard let password = data["password"]?.string.map(Password.init) else {
throw Abort.custom(status: .badRequest, message: "Password is missing")
}
let username = data["username"]?.string.map(Username.init)
let newPassword = data["new_password"]?.string.map(Password.init)
return (email, username, password, newPassword)
}
public func logIn(_ request: Request) throws -> ResponseRepresentable {
let values = try extractValues(request.data)
let credentials = UserCredentials(email: values.email,
password: values.password,
hash: hash)
try request.auth.login(credentials, persist: false)
let user = try request.user()
return try JSON(node: ["token": token(user: user)])
}
public func signUp(_ request: Request) throws -> ResponseRepresentable {
let values = try extractValues(request.data)
guard let username: Valid<Username> = try values.username?.validated() else {
throw Abort.custom(status: .badRequest, message: "Username is missing")
}
let email: Valid<Email> = try values.email.validated()
let password: Valid<Password> = try values.password.validated()
guard let userExists = try? User.find(byEmail: email.value) != nil,
userExists == false else {
throw Abort.custom(status: .badRequest, message: "User exists")
}
let credentials = UserCredentials(email: email.value,
password: password.value,
hash: hash)
let hashedPassword = try credentials.hashPassword()
var user = createUser(email, username, hashedPassword.salt, hashedPassword.secret)
try user.save()
let newToken = try token(user: user)
// user.token = storedToken
return try JSON(node: ["token": newToken])
}
public func updatePassword(_ request: Request) throws -> ResponseRepresentable {
let values = try extractValues(request.data)
guard let newPassword: Valid<Password> = try values.newPassword?.validated() else {
throw Abort.badRequest
}
guard newPassword.value != values.password else {
throw Abort.custom(status: .badRequest, message: "New password must be different")
}
let credentials = UserCredentials(email: values.email,
password: values.password,
hash: hash)
try request.auth.login(credentials, persist: false)
var user = try request.user()
let hashedPassword = try credentials.hashPassword(newPassword)
user.update(hashedPassword: hashedPassword, now: passwordUpdate ?? Date())
// try saveUser(&user)
try user.save()
return try JSON(node: ["token": token(user: user)])
}
private func token(user: User) throws -> String {
let now = issueDate ?? Date()
guard let expirationDate = 10.minutes.from(now) else {
throw Abort.serverError
}
if let userID = user.id?.int {
var payload = Node(ExpirationTimeClaim(expirationDate))
payload["userId"] = Node(userID)
let jwt = try JWT(payload: payload,
signer: HS256(key: jwtKey))
return try jwt.createToken()
}
else {
throw Abort.serverError
}
}
}
struct Password: Validatable, ValidationSuite, Equatable {
let value: String
public static func validate(input value: Password) throws {
try Count.min(8).validate(input: value.value)
}
static func == (lhs: Password, rhs: Password) -> Bool {
return lhs.value == rhs.value
}
}
typealias HashedPassword = (secret: User.Secret, salt: User.Salt)
struct UserCredentials: Credentials {
let email: Email
private let hash: HashProtocol
private let password: Password
init(email: Email, password: Password, hash: HashProtocol) {
self.email = email
self.hash = hash
self.password = password
}
/// Hashes password using salt
///
/// - parameter providedPassword: password to hash or nil to use existing password
/// - parameter salt: salt to use while hashing or nil to create new random salt
///
/// - throws: when hashing fails
///
/// - returns: salt and hashed password
func hashPassword(_ providedPassword: Valid<Password>? = nil,
using salt: User.Salt = BCryptSalt().string) throws -> HashedPassword {
return (try hash.make((providedPassword?.value.value ?? password.value) + salt), salt)
}
}
| mit | cd72c23ae118d0b52d09c756ebfb5759 | 34.854749 | 96 | 0.60564 | 4.712188 | false | false | false | false |
Samiabo/Weibo | Weibo/Weibo/Classes/Main/UserAccount.swift | 1 | 1600 | //
// UserAccount.swift
// Weibo
//
// Created by han xuelong on 2017/1/3.
// Copyright © 2017年 han xuelong. All rights reserved.
//
import UIKit
class UserAccount: NSObject, NSCoding {
var access_token: String?
var expires_in: TimeInterval = 0.0 {
didSet {
expire_date = NSDate(timeIntervalSinceNow: expires_in)
}
}
var uid: String?
var expire_date: NSDate?
var screen_name: String?
var avatar_large: String?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
override var description: String {
return dictionaryWithValues(forKeys: ["access_token","expire_date","uid","screen_name","avatar_large"]).description
}
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObject(forKey: "access_token") as? String
uid = aDecoder.decodeObject(forKey: "uid") as! String?
expire_date = aDecoder.decodeObject(forKey: "expire_date") as? NSDate
avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(access_token, forKey: "access_token")
aCoder.encode(uid, forKey: "uid")
aCoder.encode(expire_date, forKey: "expire_date")
aCoder.encode(avatar_large, forKey: "avatar_large")
aCoder.encode(screen_name, forKey: "screen_name")
}
}
| mit | 9803293e1a19b0cc13ec201617a2713c | 31.591837 | 123 | 0.638071 | 3.9925 | false | false | false | false |
vmalakhovskiy/thisisstonemasonsmusicapp | Sources/App/Controllers/BandController.swift | 1 | 7801 | import Vapor
import HTTP
import Fluent
import Foundation
import Multipart
/// Here we have a controller that helps facilitate
/// RESTful interactions with our Users table
final class BandController {
func registerRoutes(with routeBuilder: RouteBuilder) {
routeBuilder.get("bands", handler: get)
routeBuilder.post("bands", handler: create)
routeBuilder.get("bands", Int.parameter, handler: getConcrete)
routeBuilder.delete("bands", handler: delete)
let bandToken = routeBuilder.grouped([BandMiddleware()])
let bandAndUserToken = bandToken.grouped([UserMiddleware()])
bandAndUserToken.post("bands", Int.parameter, "user", Int.parameter, handler: connect)
bandAndUserToken.delete("bands", Int.parameter, "user", Int.parameter, handler: disconnect)
bandToken.post("bands", Int.parameter, "upload", handler: upload)
bandToken.get("bands", Int.parameter, "audio", Int.parameter, handler: getAudio)
bandToken.delete("bands", Int.parameter, "audio", Int.parameter, handler: deleteAudio)
}
func get(request: Request) throws -> ResponseRepresentable {
let user = try request.user()
let bands = try user.bands().all()
return try bands.makeJSON()
}
/// When consumers call 'POST' on '/users' with valid JSON
/// create and save the user
func create(request: Request) throws -> ResponseRepresentable {
guard let json = request.json else {
throw Abort(.badRequest)
}
let user = try request.user()
let band = try Band(json: json)
guard try Band.makeQuery().filter("name", band.name).first() == nil else {
throw Abort(.badRequest, reason: "A band with that name already exists.")
}
try band.save()
let pivot = try Pivot<User, Band>(user, band)
try pivot.save()
return band
}
func getConcrete(request: Request) throws -> ResponseRepresentable {
return try request.band()
}
/// When the consumer calls 'DELETE' on a specific resource, ie:
/// 'users/l2jd9' we should remove that resource from the database
func delete(request: Request) throws -> ResponseRepresentable {
try request.band().delete()
return JSON([:])
}
/// When the user calls 'PATCH' on a specific resource, we should
/// update that resource to the new values.
func update(request: Request) throws -> ResponseRepresentable {
let band = try request.band()
try band.update(for: request)
// Save an return the updated user.
try band.save()
return band
}
func connect(request: Request) throws -> ResponseRepresentable {
let passedUser = try request.passedUser()
let band = try request.band()
guard try passedUser.bands().makeQuery().filter(Band.idKey, band.id).first() == nil else {
throw Abort(.badRequest, reason: "User already in that band")
}
let pivot = try Pivot<User, Band>(passedUser, band)
try pivot.save()
return band
}
func disconnect(request: Request) throws -> ResponseRepresentable {
let passedUser = try request.passedUser()
let band = try request.band()
guard try passedUser.bands().makeQuery().filter(Band.idKey, band.id).first() != nil else {
throw Abort(.badRequest, reason: "User is not in that band")
}
try Pivot<User, Band>.makeQuery()
.filter(UserBand.userIdKey, passedUser.id)
.filter(UserBand.bandIdKey, band.id)
.delete()
return band
}
func upload(request: Request) throws -> ResponseRepresentable {
guard
let field = request.formData?["audio"],
let filename = request.formData?["name"]?.string,
!field.part.body.isEmpty
else {
throw Abort(.badRequest, reason: "No file in request")
}
let bytes = field.part.body
let band = try request.band()
let fileManager = FileManager.default
let imageDirUrl = URL(fileURLWithPath: workingDirectory())
.appendingPathComponent("Public/Uploads/\(band.name)/Audio", isDirectory: true)
try fileManager.createDirectory(at: imageDirUrl, withIntermediateDirectories: true, attributes: nil)
let systemName = UUID().uuidString + ".m4a"
let saveURL = imageDirUrl.appendingPathComponent(systemName, isDirectory: false)
do {
let data = Data(bytes: bytes)
try data.write(to: saveURL)
} catch {
throw Abort(.internalServerError, reason: "Unable to write multipart form data to file. Underlying error \(error)")
}
let audio = try Audio(name: filename, systemName: systemName, band: band)
try audio.save()
return audio
}
func getAudio(request: Request) throws -> ResponseRepresentable {
let band = try request.band()
guard let audioId = request.parameters[Int.uniqueSlug]?.array?.last?.int else {
throw Abort.badRequest
}
guard let audio = try band.audios().makeQuery().filter(Audio.idKey, audioId).first() else {
throw Abort(.badRequest, reason: "No audios found with that id")
}
let url = try audio.audioUrl()
let file = try Data(contentsOf: url)
let response = Response(status: .ok)
response.multipart = [
Part(headers: [:], body: try audio.makeJSON().makeBody().bytes!),
Part(headers: [HeaderKey.contentType: "audio/x-m4a"], body: file.makeBytes())
]
return response
}
func deleteAudio(request: Request) throws -> ResponseRepresentable {
let band = try request.band()
guard let audioId = request.parameters[Int.uniqueSlug]?.array?.last?.int else {
throw Abort.badRequest
}
guard let audio = try band.audios().makeQuery().filter(Audio.idKey, audioId).first() else {
throw Abort(.badRequest, reason: "No audios found with that id")
}
let url = try audio.audioUrl()
try audio.delete()
try FileManager.default.removeItem(at: url)
return JSON([:])
}
}
public final class BandMiddleware: Middleware {
public func respond(to req: Request, chainingTo next: Responder) throws -> Response {
guard let bandId = req.parameters[Int.uniqueSlug]?.int ?? req.parameters[Int.uniqueSlug]?.array?.first?.int else {
throw Abort.badRequest
}
guard let band = try Band.makeQuery().filter(Band.idKey, bandId).first() else {
throw Abort(.badRequest, reason: "No bands found with that id")
}
req.storage["band"] = band
return try next.respond(to: req)
}
}
public final class UserMiddleware: Middleware {
public func respond(to req: Request, chainingTo next: Responder) throws -> Response {
guard let userId = req.parameters[Int.uniqueSlug]?.array?.last?.int else {
throw Abort.badRequest
}
guard let user = try User.makeQuery().filter(User.idKey, userId).first() else {
throw Abort(.badRequest, reason: "No user found with that id")
}
req.storage["passed_user"] = user
return try next.respond(to: req)
}
}
extension Request {
func band() throws -> Band {
guard let band = storage["band"] as? Band else {
throw EntityError.doesntExist(Band.self)
}
return band
}
func passedUser() throws -> User {
guard let user = storage["passed_user"] as? User else {
throw EntityError.doesntExist(User.self)
}
return user
}
}
| mit | ef7c7624b29a9a450feb7559c8806dd0 | 33.517699 | 128 | 0.623382 | 4.506644 | false | false | false | false |
cismet/belis-app | belis-app/Standort.swift | 1 | 15814 | //
// Standort.swift
// Experiments
//
// Created by Thorsten Hell on 10/12/14.
// Copyright (c) 2014 cismet. All rights reserved.
//
import Foundation
import ObjectMapper
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class Standort: GeoBaseEntity , CellInformationProviderProtocol, CellDataProvider,ActionProvider, DocumentContainer, ObjectActionProvider{
var plz : String?
var strasse : Strasse?
var bezirk : Stadtbezirk?
var mastart : Mastart?
var klassifizierung: Mastklassifizierung?
var mastanstrich: Date?
var mastschutz: Date?
var unterhaltspflicht: MastUnterhaltspflicht?
var typ: Masttyp?
var inbetriebnahme: Date?
var verrechnungseinheit: Bool?
var letzteAenderung: Date?
var istVirtuellerStandort: Bool?
var bemerkung: String?
var montagefirma: String?
var standortangabe: String?
var kennziffer: MastKennziffer?
var lfdNummer: Int?
var hausnummer: String?
var dokumente: [DMSUrl] = []
var gruendung: String?
var elektrischePruefung: Date?
var erdung: Bool?
var monteur: String?
var standsicherheitspruefung: Date?
var verfahrenSHP: String?
var foto: DMSUrl?
var naechstesPruefdatum: Date?
var anstrichfrabe: String?
var revision: Date?
var anlagengruppe: MastAnlagengruppe?
var anbauten: String?
// MARK: - required init because of ObjectMapper
required init?(map: Map) {
super.init(map: map)
}
// MARK: - essential overrides BaseEntity
override func getType() -> Entity {
return Entity.MASTEN
}
override func mapping(map: Map) {
super.id <- map["id"];
plz <- map["plz"]
strasse <- map["fk_strassenschluessel"]
bezirk <- map["fk_stadtbezirk"]
mastart <- map["fk_mastart"]
klassifizierung <- map["fk_klassifizierung"]
mastanstrich <- (map["mastanstrich"], DateTransformFromMillisecondsTimestamp())
mastschutz <- (map["mastschutz"], DateTransformFromMillisecondsTimestamp())
unterhaltspflicht <- map["fk_unterhaltspflicht_mast"]
typ <- map["fk_masttyp"]
inbetriebnahme <- (map["inbetriebnahme_mast"], DateTransformFromMillisecondsTimestamp())
verrechnungseinheit <- map["verrechnungseinheit"]
letzteAenderung <- (map["letzte_aenderung"], DateTransformFromMillisecondsTimestamp())
istVirtuellerStandort <- map["ist_virtueller_standort"]
bemerkung <- map["bemerkungen"]
montagefirma <- map["montagefirma"]
standortangabe <- map["standortangabe"]
kennziffer <- map["fk_kennziffer"]
lfdNummer <- map["lfd_nummer"]
hausnummer <- map["haus_nr"]
dokumente <- map["dokumente"]
gruendung <- map["gruendung"]
elektrischePruefung <- (map["elek_pruefung"], DateTransformFromMillisecondsTimestamp())
erdung <- map["erdung"]
monteur <- map["monteur"]
standsicherheitspruefung <- (map["standsicherheitspruefung"], DateTransformFromMillisecondsTimestamp())
verfahrenSHP <- map["verfahren"]
foto <- map["foto"]
naechstesPruefdatum <- (map["naechstes_pruefdatum"], DateTransformFromMillisecondsTimestamp())
anstrichfrabe <- map["anstrichfarbe"]
revision <- (map["revision"], DateTransformFromMillisecondsTimestamp())
anlagengruppe <- map["anlagengruppe"]
anbauten <- map["anbauten"]
//Muss an den Schluss wegen by Value übergabe des mapObjects -.-
wgs84WKT <- map["fk_geom.wgs84_wkt"]
}
// MARK: - essential overrides GeoBaseEntity
override func getAnnotationImage(_ status: String?) -> UIImage{
if let s=status {
if let color=Arbeitsprotokoll.statusColors[s] {
return GlyphTools.sharedInstance().getGlyphedAnnotationImage("icon-circlerecord",color: color);
}
}
return GlyphTools.sharedInstance().getGlyphedAnnotationImage("icon-circlerecord");
}
override func getAnnotationTitle() -> String{
return getMainTitle();
}
override func canShowCallout() -> Bool{
return true
}
override func getAnnotationCalloutGlyphIconName() -> String {
return "icon-horizontalexpand"
}
// MARK: - CellInformationProviderProtocol Impl
func getMainTitle() -> String{
var standortPart:String
if let snrInt = lfdNummer {
standortPart="\(snrInt)"
}
else {
standortPart=""
}
return "Mast - \(standortPart)"
}
func getSubTitle() -> String{
if let artBez = mastart?.name {
return artBez
}
else {
return "-ohne Mastart-"
}
}
func getTertiaryInfo() -> String{
if let str = strasse?.name {
return str
}
return "-"
}
func getQuaternaryInfo() -> String{
return ""
}
// MARK: - CallOutInformationProviderProtocol Impl
func getCallOutTitle() -> String {
return getAnnotationTitle()
}
func getGlyphIconName() -> String {
return "icon-horizontalexpand"
}
func getDetailViewID() -> String{
return "StandortDetails"
}
func canShowDetailInformation() -> Bool{
return true
}
// MARK: - CellDataProvider Impl
@objc func getTitle() -> String {
return "Mast"
}
@objc func getDetailGlyphIconString() -> String {
return "icon-horizontalexpand"
}
@objc func getAllData() -> [String: [CellData]] {
var mastDetails: [String: [CellData]] = ["main":[]]
if let ueberschrift=mastart?.name {
mastDetails["main"]?.append(SimpleInfoCellData(data: ueberschrift))
}
if let typChecked=typ?.typ {
var mastTypDetails: [String: [CellData]] = ["main":[]]
mastTypDetails["main"]?.append(SimpleInfoCellData(data: typChecked))
if let bezeichnung=typ?.bezeichnung {
mastTypDetails["main"]?.append(SimpleInfoCellData(data: bezeichnung))
}
if let hersteller=typ?.hersteller {
mastTypDetails["main"]?.append(SingleTitledInfoCellData(title: "Hersteller", data: hersteller))
}
if let lph=typ?.lph {
mastTypDetails["main"]?.append(SingleTitledInfoCellData(title: "Lph", data: "\(lph)"))
}
if let wandstaerke=typ?.wandstaerke {
mastTypDetails["main"]?.append(SingleTitledInfoCellData(title: "Wandstärke", data: "\(wandstaerke)"))
}
var docCount=0
if let foto=typ?.foto {
mastTypDetails["Dokumente"]=[]
mastTypDetails["Dokumente"]?.append(SimpleUrlPreviewInfoCellData(title: "Foto", url: foto.getUrl()))
docCount=1
}
// zuerst die Dokumente des Typs
if typ?.dokumente.count>0 {
if docCount==0 {
mastDetails["Dokumente"]=[]
}
if let urls=typ?.dokumente {
for url in urls {
mastTypDetails["Dokumente"]?.append(SimpleUrlPreviewInfoCellData(title: url.description ?? "Dokument", url: url.getUrl()))
docCount += 1
}
}
}
if mastDetails["main"]?.count>1 {
mastDetails["main"]?.append(SingleTitledInfoCellDataWithDetails(title: "Masttyp", data: typChecked ,details:mastTypDetails, sections: ["main","DeveloperInfo"]))
}
else {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Masttyp", data: typChecked))
}
}
if let klassifizierung=klassifizierung?.name {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Klassifizierung", data: klassifizierung))
}
if let anlagengruppe=anlagengruppe?.bezeichnung {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Anlagengruppe", data: anlagengruppe))
}
if let unterhalt=unterhaltspflicht?.name {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Unterhalt", data: unterhalt))
}
if let mastschutzChecked=mastschutz {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Mastschutz erneuert am", data: "\(mastschutzChecked.toDateString())"))
}
if let inbetriebnahmeChecked=inbetriebnahme {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Inbetriebnahme am", data: "\(inbetriebnahmeChecked.toDateString())"))
}
if let lae=letzteAenderung {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Letzte Änderung am", data: "\(lae.toDateString())"))
}
if let rev=revision {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Letzte Revision am", data: "\(rev.toDateString())"))
}
if let ma=mastanstrich {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Letzter Mastanstrich am", data: "\(ma.toDateString())"))
}
if let farbe=anstrichfrabe {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Anstrichfarbe", data: "\(farbe)"))
}
if let fa=montagefirma {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Montagefirma", data: "\(fa)"))
}
if let ve=verrechnungseinheit {
if ve {
mastDetails["main"]?.append(SimpleInfoCellData(data: "Verrechnungseinheit"))
}
}
if let gruendung=gruendung {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Gründung", data: gruendung))
}
//Prüfungen
var pruefDetails: [String: [CellData]] = ["main":[]]
if let eP=elektrischePruefung {
var erdStr="nein"
if let erdung=erdung {
if erdung {
erdStr="ja"
}
}
pruefDetails["main"]?.append(DoubleTitledInfoCellData(titleLeft: "Elektrische Pruefung", dataLeft: "\(eP.toDateString())", titleRight: "Erdung", dataRight: erdStr))
}
if let pruefer=monteur {
pruefDetails["main"]?.append(SingleTitledInfoCellData(title: "Elektrische Pruefung durchgeführt von", data: pruefer))
}
if let ssp=standsicherheitspruefung {
if let np=naechstesPruefdatum {
pruefDetails["main"]?.append(DoubleTitledInfoCellData(titleLeft: "Standsicherheitsprüfung", dataLeft: "\(ssp.toDateString())", titleRight: "Nächster Prüftermin", dataRight: "\(np.toDateString())"))
}
else {
pruefDetails["main"]?.append(SingleTitledInfoCellData(title: "Standsicherheitsprüfung", data: "\(ssp.toDateString())"))
}
}
else if let np=naechstesPruefdatum {
pruefDetails["main"]?.append(SingleTitledInfoCellData(title: "Nächster Prüftermin", data: "\(np.toDateString())"))
}
if let vf=verfahrenSHP {
pruefDetails["main"]?.append(SingleTitledInfoCellData(title: "Verfahren", data: vf))
}
if pruefDetails["main"]?.count>0 {
mastDetails["main"]?.append(SimpleInfoCellDataWithDetails(data: "Prüfungen",details: pruefDetails, sections: ["main","DeveloperInfo"]))
}
//------------------------(PR)
if let anbauten=anbauten {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Anbauten", data: anbauten))
}
if let bem=bemerkung {
mastDetails["main"]?.append(SingleTitledInfoCellData(title: "Bemerkung", data: bem))
}
let docCount=0
if let fotoChecked=foto {
mastDetails["Dokumente"]=[]
mastDetails["Dokumente"]?.append(SimpleUrlPreviewInfoCellData(title: "Foto", url: fotoChecked.getUrl()))
}
if docCount==0 && dokumente.count>0 {
mastDetails["Dokumente"]=[]
}
for url in dokumente {
mastDetails["Dokumente"]?.append(SimpleUrlPreviewInfoCellData(title: url.description ?? "Dokument", url: url.getUrl()))
}
mastDetails["DeveloperInfo"]=[]
mastDetails["DeveloperInfo"]?.append(SingleTitledInfoCellData(title: "Key", data: "\(getType().tableName())/\(id)"))
return mastDetails
}
@objc func getDataSectionKeys() -> [String] {
return ["main","Dokumente","DeveloperInfo"]
}
// MARK: - ActionProvider Impl
@objc func getAllActions() -> [BaseEntityAction] {
var actions:[BaseEntityAction]=[]
actions.append(AddIncidentAction(yourself: self))
actions.append(TakeFotoAction(yourself: self))
actions.append(ChooseFotoAction(yourself: self))
return actions
}
// MARK: - DocumentContainer Impl
func addDocument(_ document: DMSUrl) {
dokumente.append(document)
}
// MARK: - ObjectActionProvider Impl
@objc func getAllObjectActions() -> [ObjectAction]{
return [AnstricharbeitenAction(),ElektrischePruefungAction(),MasterneuerungAction(), MastRevisionAction(),StandsicherheitspruefungAction(), SonstigesAction()]
}
}
class Stadtbezirk : BaseEntity{
var name: String?
override func mapping(map: Map) {
super.id <- map["id"]
name <- map["bezirk"]
}
}
class Mastart : BaseEntity{
var pk: String?
var name: String?
override func mapping(map: Map) {
super.id <- map["id"]
pk <- map["pk"]
name <- map["mastart"]
}
}
class Mastklassifizierung : BaseEntity{
var pk: String?
var name: String?
override func mapping(map: Map) {
super.id <- map["id"]
pk <- map["pk"]
name <- map["klassifizierung"]
}
}
class MastUnterhaltspflicht : BaseEntity{
var pk: String?
var name: String?
override func mapping(map: Map) {
super.id <- map["id"]
pk <- map["pk"]
name <- map["unterhalt_mast"]
}
}
class Masttyp : BaseEntity{
var typ: String?
var bezeichnung: String?
var lph: Double?
var hersteller: String?
var wandstaerke: Int?
var dokumente: [DMSUrl] = []
var foto: DMSUrl?
override func mapping(map: Map) {
super.id <- map["id"]
typ <- map["masttyp"]
bezeichnung <- map["bezeichnung"]
lph <- map["lph"]
hersteller <- map["hersteller"]
wandstaerke <- map["wandstaerke"]
dokumente <- map["dokumente"]
foto <- map["foto"]
}
}
class MastKennziffer : BaseEntity{
var kennziffer: Int?
var beschreibung: String?
override func mapping(map: Map) {
super.id <- map["id"]
kennziffer <- map["kennziffer"]
beschreibung <- map["beschreibung"]
}
}
class MastAnlagengruppe : BaseEntity{
var nummer: Int?
var bezeichnung: String?
override func mapping(map: Map) {
super.id <- map["id"]
nummer <- map["nummer"]
bezeichnung <- map["bezeichnung"]
}
}
| mit | f609fa9cb3e843edaa015be08ce53348 | 34.507865 | 213 | 0.593697 | 3.704807 | false | false | false | false |
jawwad/swift-algorithm-club | Heap/Heap.swift | 1 | 6624 | //
// Heap.swift
// Written for the Swift Algorithm Club by Kevin Randrup and Matthijs Hollemans
//
public struct Heap<T> {
/** The array that stores the heap's nodes. */
var nodes = [T]()
/**
* Determines how to compare two nodes in the heap.
* Use '>' for a max-heap or '<' for a min-heap,
* or provide a comparing method if the heap is made
* of custom elements, for example tuples.
*/
private var orderCriteria: (T, T) -> Bool
/**
* Creates an empty heap.
* The sort function determines whether this is a min-heap or max-heap.
* For comparable data types, > makes a max-heap, < makes a min-heap.
*/
public init(sort: @escaping (T, T) -> Bool) {
self.orderCriteria = sort
}
/**
* Creates a heap from an array. The order of the array does not matter;
* the elements are inserted into the heap in the order determined by the
* sort function. For comparable data types, '>' makes a max-heap,
* '<' makes a min-heap.
*/
public init(array: [T], sort: @escaping (T, T) -> Bool) {
self.orderCriteria = sort
configureHeap(from: array)
}
/**
* Configures the max-heap or min-heap from an array, in a bottom-up manner.
* Performance: This runs pretty much in O(n).
*/
private mutating func configureHeap(from array: [T]) {
nodes = array
for i in stride(from: (nodes.count/2-1), through: 0, by: -1) {
shiftDown(i)
}
}
public var isEmpty: Bool {
return nodes.isEmpty
}
public var count: Int {
return nodes.count
}
/**
* Returns the index of the parent of the element at index i.
* The element at index 0 is the root of the tree and has no parent.
*/
@inline(__always) internal func parentIndex(ofIndex i: Int) -> Int {
return (i - 1) / 2
}
/**
* Returns the index of the left child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no left child.
*/
@inline(__always) internal func leftChildIndex(ofIndex i: Int) -> Int {
return 2*i + 1
}
/**
* Returns the index of the right child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no right child.
*/
@inline(__always) internal func rightChildIndex(ofIndex i: Int) -> Int {
return 2*i + 2
}
/**
* Returns the maximum value in the heap (for a max-heap) or the minimum
* value (for a min-heap).
*/
public func peek() -> T? {
return nodes.first
}
/**
* Adds a new value to the heap. This reorders the heap so that the max-heap
* or min-heap property still holds. Performance: O(log n).
*/
public mutating func insert(_ value: T) {
nodes.append(value)
shiftUp(nodes.count - 1)
}
/**
* Adds a sequence of values to the heap. This reorders the heap so that
* the max-heap or min-heap property still holds. Performance: O(log n).
*/
public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T {
for value in sequence {
insert(value)
}
}
/**
* Allows you to change an element. This reorders the heap so that
* the max-heap or min-heap property still holds.
*/
public mutating func replace(index i: Int, value: T) {
guard i < nodes.count else { return }
remove(at: i)
insert(value)
}
/**
* Removes the root node from the heap. For a max-heap, this is the maximum
* value; for a min-heap it is the minimum value. Performance: O(log n).
*/
@discardableResult public mutating func remove() -> T? {
guard !nodes.isEmpty else { return nil }
if nodes.count == 1 {
return nodes.removeLast()
} else {
// Use the last node to replace the first one, then fix the heap by
// shifting this new first node into its proper position.
let value = nodes[0]
nodes[0] = nodes.removeLast()
shiftDown(0)
return value
}
}
/**
* Removes an arbitrary node from the heap. Performance: O(log n).
* Note that you need to know the node's index.
*/
@discardableResult public mutating func remove(at index: Int) -> T? {
guard index < nodes.count else { return nil }
let size = nodes.count - 1
if index != size {
nodes.swapAt(index, size)
shiftDown(from: index, until: size)
shiftUp(index)
}
return nodes.removeLast()
}
/**
* Takes a child node and looks at its parents; if a parent is not larger
* (max-heap) or not smaller (min-heap) than the child, we exchange them.
*/
internal mutating func shiftUp(_ index: Int) {
var childIndex = index
let child = nodes[childIndex]
var parentIndex = self.parentIndex(ofIndex: childIndex)
while childIndex > 0 && orderCriteria(child, nodes[parentIndex]) {
nodes[childIndex] = nodes[parentIndex]
childIndex = parentIndex
parentIndex = self.parentIndex(ofIndex: childIndex)
}
nodes[childIndex] = child
}
/**
* Looks at a parent node and makes sure it is still larger (max-heap) or
* smaller (min-heap) than its childeren.
*/
internal mutating func shiftDown(from index: Int, until endIndex: Int) {
let leftChildIndex = self.leftChildIndex(ofIndex: index)
let rightChildIndex = leftChildIndex + 1
// Figure out which comes first if we order them by the sort function:
// the parent, the left child, or the right child. If the parent comes
// first, we're done. If not, that element is out-of-place and we make
// it "float down" the tree until the heap property is restored.
var first = index
if leftChildIndex < endIndex && orderCriteria(nodes[leftChildIndex], nodes[first]) {
first = leftChildIndex
}
if rightChildIndex < endIndex && orderCriteria(nodes[rightChildIndex], nodes[first]) {
first = rightChildIndex
}
if first == index { return }
nodes.swapAt(index, first)
shiftDown(from: first, until: endIndex)
}
internal mutating func shiftDown(_ index: Int) {
shiftDown(from: index, until: nodes.count)
}
}
// MARK: - Searching
extension Heap where T: Equatable {
/** Get the index of a node in the heap. Performance: O(n). */
public func index(of node: T) -> Int? {
return nodes.index(where: { $0 == node })
}
/** Removes the first occurrence of a node from the heap. Performance: O(n log n). */
@discardableResult public mutating func remove(node: T) -> T? {
if let index = index(of: node) {
return remove(at: index)
}
return nil
}
}
| mit | 54cd676a8a40932136f38d619fa1fe17 | 28.704036 | 90 | 0.637077 | 3.848925 | false | false | false | false |
lemonkey/iOS | WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/Common/IncompleteListItemsPresenter.swift | 1 | 12398 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The implementation for the `IncompleteListItemsPresenter` type. This class is responsible for managing how a list is presented in the iOS and OS X app Today widgets, as well as the Lister WatchKit application.
*/
import Foundation
/**
The `IncompleteListItemsPresenter` list presenter is responsible for managing the how a list's incomplete
list items are displayed in the iOS and OS X Today widgets as well as the Lister WatchKit app. The
`IncompleteListItemsPresenter` class conforms to `ListPresenterType` so consumers of this class can work
with the presenter using a common interface.
When a list is initially presented with an `IncompleteListItemsPresenter`, only the incomplete list items
are presented. That can change, however, if a user toggles list items (changing the list item's completion
state). An `IncompleteListItemsPresenter` always shows the list items that are initially presented (unless
they are removed from the list from another device). If an `IncompleteListItemsPresenter` stops presenting
a list that has some presented list items that are complete (after toggling them) and another
`IncompleteListItemsPresenter` presents the same list, the presenter displays *only* the incomplete list
items.
The `IncompleteListItemsPresenter` can be interacted with in a two ways. `ListItem` instances can be
toggled individually or using a batch update, and the color of the list presenter can be changed. All of
these methods trigger calls to the delegate to be notified about inserted list items, removed list items,
updated list items, etc.
*/
final public class IncompleteListItemsPresenter: NSObject, ListPresenterType {
// MARK: Properties
/// The internal storage for the list that we're presenting. By default, it's an empty list.
private var list = List()
/// Flag to see whether or not the first `setList(_:)` call should trigger a batch reload.
private var isInitialList = true
/**
A cached array of the list items that should be presented. When the presenter initially has its
underlying `list` set, the `_presentedListItems` is set to all of the incomplete list items. As list
items are toggled, `_presentedListItems` may contain incomplete list items as well as complete items
that were incomplete when the presenter's list was set. Note that we've named the property
`_presentedListItems` since there's already a readonly `presentedListItems` property (which returns the
value of `_presentedListItems`).
*/
private var _presentedListItems = [ListItem]()
// MARK: ListPresenterType
public weak var delegate: ListPresenterDelegate?
public var color: List.Color {
get {
return list.color
}
set {
updateListColorForListPresenterIfDifferent(self, &list.color, newValue, isForInitialLayout: false)
}
}
public var archiveableList: List {
return list
}
public var presentedListItems: [ListItem] {
return _presentedListItems
}
/**
This methods determines the changes betwen the current list and the new list provided, and it notifies
the delegate accordingly. The delegate is notified of all changes except for reordering list items (an
implementation detail). If the list is the initial list to be presented, we just reload all of the
data.
*/
public func setList(newList: List) {
// If this is the initial list that's being presented, just tell the delegate to reload all of the data.
if isInitialList {
isInitialList = false
list = newList
_presentedListItems = list.items.filter { !$0.isComplete }
delegate?.listPresenterDidRefreshCompleteLayout(self)
return
}
/**
First find all the differences between the lists that we want to reflect in the presentation of
the list: list items that were removed, inserted list items that are incomplete, presented list
items that are toggled, and presented list items whose text has changed. Note that although we'll
gradually update `_presentedListItems` to reflect the changes we find, we also want to save the
latest state of the list (i.e. the `newList` parameter) as the underlying storage of the list.
Since we'll be presenting the same list either way, it's better not to change the underlying list
representation unless we need to. Keep in mind, however, that all of the list items in
`_presentedListItems` should also be in `list.items`. In short, once we modify `_presentedListItems`
with all of the changes, we need to also update `list.items` to contain all of the list items that
were unchanged (this can be done by replacing the new list item representation by the old
representation of the list item). Once that happens, all of the presentation logic carries on as
normal.
*/
let oldList = list
let newRemovedPresentedListItems = findRemovedListItems(initialListItems: _presentedListItems, changedListItems: newList.items)
let newInsertedIncompleteListItems = findInsertedListItems(initialListItems: _presentedListItems, changedListItems: newList.items) { listItem in
return !listItem.isComplete
}
let newPresentedToggledListItems = findToggledListItems(initialListItems: _presentedListItems, changedListItems: newList.items)
let newPresentedListItemsWithUpdatedText = findListItemsWithUpdatedText(initialListItems: _presentedListItems, changedListItems: newList.items)
let listItemsBatchChangeKind = listItemsBatchChangeKindForChanges(removedListItems: newRemovedPresentedListItems, insertedListItems: newInsertedIncompleteListItems, toggledListItems: newPresentedToggledListItems, listItemsWithUpdatedText: newPresentedListItemsWithUpdatedText)
// If no changes occured we'll ignore the update.
if listItemsBatchChangeKind == nil && oldList.color == newList.color {
return
}
// Start performing changes to the presentation of the list.
delegate?.listPresenterWillChangeListLayout(self, isInitialLayout: true)
// Remove the list items from the presented list items that were removed somewhere else.
if !newRemovedPresentedListItems.isEmpty {
removeListItemsFromListItemsWithListPresenter(self, initialListItems: &_presentedListItems, listItemsToRemove: newRemovedPresentedListItems)
}
// Insert the incomplete list items into the presented list items that were inserted elsewhere.
if !newInsertedIncompleteListItems.isEmpty {
insertListItemsIntoListItemsWithListPresenter(self, initialListItems: &_presentedListItems, listItemsToInsert: newInsertedIncompleteListItems)
}
/**
For all of the list items whose content has changed elsewhere, we need to update the list items in
place. Since the `IncompleteListItemsPresenter` keeps toggled list items in place, we only need
to perform one update for list items that have a different completion state and text. We'll batch
both of these changes into a single update.
*/
if !newPresentedToggledListItems.isEmpty || !newPresentedListItemsWithUpdatedText.isEmpty {
// Find the unique list of list items that are updated.
let uniqueUpdatedListItems = Set(newPresentedToggledListItems).union(newPresentedListItemsWithUpdatedText)
updateListItemsWithListItemsForListPresenter(self, presentedListItems: &_presentedListItems, newUpdatedListItems: Array(uniqueUpdatedListItems))
}
/**
At this point, the presented list items have been updated. As mentioned before, to ensure that
we're consistent about how we persist the updated list, we'll just use new the new list as the
underlying model. To do that, we'll need to update the new list's unchanged list items with the
list items that are stored in the visual list items. Specifically, we need to make sure that any
references to list items in `_presentedListItems` are reflected in the new list's items.
*/
list = newList
// Obtain the presented list items that were unchanged. We need to update the new list to reference the old list items.
let unchangedPresentedListItems = _presentedListItems.filter { oldListItem in
return !contains(newRemovedPresentedListItems, oldListItem) && !contains(newInsertedIncompleteListItems, oldListItem) && !contains(newPresentedToggledListItems, oldListItem) && !contains(newPresentedListItemsWithUpdatedText, oldListItem)
}
replaceAnyEqualUnchangedNewListItemsWithPreviousUnchangedListItems(replaceableNewListItems: &list.items, previousUnchangedListItems: unchangedPresentedListItems)
/**
Even though the old list's color will change if there's a difference between the old list's color
and the new list's color, the delegate only cares about this change in reference to what it
already knows. Because the delegate hasn't seen a color change yet, the update (if it happens) is
ok.
*/
updateListColorForListPresenterIfDifferent(self, &oldList.color, newList.color)
delegate?.listPresenterDidChangeListLayout(self, isInitialLayout: true)
}
public var count: Int {
return presentedListItems.count
}
public var isEmpty: Bool {
return presentedListItems.isEmpty
}
// MARK: Methods
/**
Toggles `listItem` within the list. This method keeps the list item in the same place, but it toggles
the completion state of the list item. Toggling a list item calls the delegate's
`listPresenter(_:didUpdateListItem:atIndex:)` method.
:param: listItem The list item to toggle.
*/
public func toggleListItem(listItem: ListItem) {
precondition(contains(presentedListItems, listItem), "The list item must already be in the presented list items.")
delegate?.listPresenterWillChangeListLayout(self, isInitialLayout: false)
listItem.isComplete = !listItem.isComplete
let currentIndex = find(presentedListItems, listItem)!
delegate?.listPresenter(self, didUpdateListItem: listItem, atIndex: currentIndex)
delegate?.listPresenterDidChangeListLayout(self, isInitialLayout: false)
}
/**
Sets all of the presented list item's completion states to `completionState`. This method does not move
the list items around in any way. Changing the completion state on all of the list items calls the
delegate's `listPresenter(_:didUpdateListItem:atIndex:)` method for each list item that has been
updated.
:param: completionState The value that all presented list item instances should have as their `isComplete` property.
*/
public func updatePresentedListItemsToCompletionState(completionState: Bool) {
var presentedListItemsNotMatchingCompletionState = presentedListItems.filter { $0.isComplete != completionState }
// If there are no list items that match the completion state, it's a no op.
if presentedListItemsNotMatchingCompletionState.isEmpty { return }
delegate?.listPresenterWillChangeListLayout(self, isInitialLayout: false)
for listItem in presentedListItemsNotMatchingCompletionState {
listItem.isComplete = !listItem.isComplete
let indexOfListItem = find(presentedListItems, listItem)!
delegate?.listPresenter(self, didUpdateListItem: listItem, atIndex: indexOfListItem)
}
delegate?.listPresenterDidChangeListLayout(self, isInitialLayout: false)
}
}
| mit | 0cea8a317b42b6d42b357d833cb50cc8 | 53.131004 | 284 | 0.708454 | 5.333907 | false | false | false | false |
protoman92/SwiftUtilities | SwiftUtilities/string/Strings.swift | 1 | 4157 | //
// Strings.swift
// Sellfie
//
// Created by Hai Pham on 3/12/16.
// Copyright © 2016 Swiften. All rights reserved.
//
extension String: IsInstanceType {}
public extension Character {
/// Create a random Character. This is useful for creating random Strings.
///
/// - Returns: A Character.
public static func random() -> Character {
let startingValue = Int(("a" as UnicodeScalar).value)
let count = Int.randomBetween(0, 51)
return Character(UnicodeScalar(count + startingValue)!)
}
}
public extension String {
/// Create a random String.
///
/// - Parameter length: The length of the String to be created.
/// - Returns: A String value.
public static func random(withLength length: Int) -> String {
return String((0..<length).map({_ in Character.random()}))
}
}
public extension String {
/// Replace occurrences of a String with a set of character types.
///
/// - Parameters:
/// - characters: The character set to be replaced.
/// - string: The String to replace.
/// - Returns: A String value.
public func replacingOccurrences(of characters: CharacterSet,
with string: String) -> String {
return components(separatedBy: characters).joined(separator: string)
}
}
public extension String {
/// Localize a String based a a bundle and some table names. We sequentially
/// check the localization from each table until a localized String that is
/// different from the current String is generated.
///
/// - Parameters:
/// - bundle: A Bundle instance.
/// - tables: Sequence of String.
/// - Returns: A String value.
public func localize<S>(_ bundle: Bundle, _ tables: S) -> String where
S: Sequence, S.Element == String
{
for table in tables {
let localized = NSLocalizedString(self,
tableName: table,
bundle: bundle,
value: "",
comment: "")
if localized != self {
return localized
}
}
return NSLocalizedString(self, comment: "")
}
/// Localize with the default Bundle.
///
/// - Parameter tables: Varargs of String.
/// - Returns: A String value.
public func localize<S>(_ tables: S) -> String where S: Sequence, S.Element == String {
return localize(Bundle.main, tables)
}
/// Localize a String based a a bundle and some table names.
///
/// - Parameters:
/// - bundle: A Bundle instance.
/// - tables: Sequence of String.
/// - Returns: A String value.
public func localize(_ bundle: Bundle, _ tables: String...) -> String {
return localize(bundle, tables)
}
/// Localize with the default Bundle.
///
/// - Parameter tables: Varargs of String.
/// - Returns: A String value.
public func localize(_ tables: String...) -> String {
return localize(tables)
}
}
public extension String {
public init?(hexadecimalString hex: String) {
guard let data = NSMutableData(hexadecimalString: hex) else {
return nil
}
self.init(data: data as Data, encoding: .utf8)
}
public var hexadecimalString: String? {
return data(using: .utf8)?.hexadecimalString
}
}
public extension NSMutableData {
public convenience init?(hexadecimalString hex: String) {
let count = hex.count
self.init(capacity: count / 2)
do {
let regex = try NSRegularExpression(pattern: "[0-9a-f]{1,2}",
options: .caseInsensitive)
let range = NSMakeRange(0, count)
regex.enumerateMatches(in: hex, options: [], range: range) {
match, flags, stop in
guard let match = match else {
return
}
let nsString = NSString(string: hex)
let byteString = nsString.substring(with: match.range)
var num = UInt8(byteString, radix: 16)
self.append(&num, length: 1)
}
} catch {
return nil
}
}
}
public extension Data {
public var hexadecimalString: String {
return map{String(format: "%02x", $0)}.joined()
}
}
| apache-2.0 | 1132924c42717b230379a7ba68cde6e8 | 26.892617 | 89 | 0.608518 | 4.342738 | false | false | false | false |
dashboardearth/rewardsplatform | src/Halo-iOS-App/Halo/Data Model/Challenge.swift | 1 | 2436 | //
// Challenge.swift
// Halo
//
// Created by Sattawat Suppalertporn on 24/7/17.
// Copyright © 2017 dashboardearth. All rights reserved.
//
import Foundation
class Challenge {
public var name:String = ""
public var details:String = ""
public var points:Int = 0
public var isCompleted:Bool = false
public var imageUrl:URL?
public var latitude:Double = 0.0
public var longitude:Double = 0.0
init(name:String, points:Int, isCompleted:Bool) {
self.name = name
self.points = points
self.isCompleted = isCompleted
}
}
// List of Challenge extension
extension Challenge {
private static var s_challenges:[Challenge] = []
class func GetList() -> [Challenge] {
var challenges = Challenge.s_challenges
if challenges.count == 0 {
challenges.append(Challenge(name:"Create Dashboard Earth Account", points:10, isCompleted: true))
challenges[0].latitude = 47.642
challenges[0].longitude = -122.128
challenges.append(Challenge(name:"Volunteer event", points:10, isCompleted: false))
challenges[1].latitude = 47.641750
challenges[1].longitude = -122.129363
challenges.append(Challenge(name:"Plant trees", points:50, isCompleted: false))
challenges[2].latitude = 47.142
challenges[2].longitude = -122.028
challenges.append(Challenge(name:"Bike to work", points:50, isCompleted: true))
challenges[3].latitude = 47.442
challenges[3].longitude = -122.028
challenges.append(Challenge(name:"Write to senator", points:100, isCompleted: false))
challenges[4].latitude = 47.942
challenges[4].longitude = -122.728
}
return challenges
}
class func GetActiveList() -> [Challenge] {
let challenges = GetList()
var results:[Challenge] = []
for c in challenges {
if !c.isCompleted {
results.append(c)
}
}
return results
}
class func GetCompletedList() -> [Challenge] {
let challenges = GetList()
var results:[Challenge] = []
for c in challenges {
if c.isCompleted {
results.append(c)
}
}
return results
}
}
| apache-2.0 | 56bc2a4b0b639d190767c07842854a8d | 29.4375 | 109 | 0.576181 | 4.484346 | false | false | false | false |
s4cha/Stevia | Tests/SteviaTests/BaselineTests.swift | 3 | 1168 | //
// BaselineTests.swift
// SteviaTests
//
// Created by Sacha on 09/09/2018.
// Copyright © 2018 Sacha Durand Saint Omer. All rights reserved.
//
import XCTest
import Stevia
class BaselineTests: XCTestCase {
var win: UIWindow!
var ctrler: UIViewController!
var label1 = UILabel()
var label2 = UILabel()
override func setUp() {
win = UIWindow(frame: UIScreen.main.bounds)
ctrler = UIViewController()
win.rootViewController = ctrler
label1 = UILabel()
label2 = UILabel()
ctrler.view.subviews {
label1
label2
}
}
func testAlignLastBaselines() {
label1.top(100)
align(lastBaselines: label1, label2)
ctrler.view.layoutIfNeeded()
XCTAssertEqual(label1.forLastBaselineLayout.frame.minY, label2.forLastBaselineLayout.frame.minY)
}
func testAlignFirstBaselines() {
label1.top(100)
align(firstBaselines: label1, label2)
ctrler.view.layoutIfNeeded()
XCTAssertEqual(label1.forLastBaselineLayout.frame.minY, label2.forLastBaselineLayout.frame.minY)
}
}
| mit | 5f4cbe935847dc9e291f2542ba78491e | 24.369565 | 104 | 0.634105 | 4.094737 | false | true | false | false |
Mindera/Alicerce | Tests/AlicerceTests/Utils/AssertDumpsEqualTestCase.swift | 1 | 1207 | import XCTest
@testable import Alicerce
class AssertDumpsEqualTestCase: XCTestCase {
func test_WithEqualString_ShouldSucceed() {
let s1 = "test"
let s2 = "test"
assertDumpsEqual(s1, s2)
}
func test_WithEqualInt_ShouldSucceed() {
let i1 = 1337
let i2 = 1337
assertDumpsEqual(i1, i2)
}
func test_WithEqualDate_ShouldSucceed() {
let d = Date()
let d1 = d
let d2 = d
assertDumpsEqual(d1, d2)
}
func test_WithEqualRange_ShouldSucceed() {
let r1 = 0..<1337
let r2 = 0..<1337
assertDumpsEqual(r1, r2)
}
func test_WithEqualStringArray_ShouldSucceed() {
let a1 = ["a", "b", "c"]
let a2 = ["a", "b", "c"]
assertDumpsEqual(a1, a2)
}
func test_WithEqualIntArray_ShouldSucceed() {
let a1 = [1, 2, 3]
let a2 = [1, 2, 3]
assertDumpsEqual(a1, a2)
}
func test_WithEqualDict_ShouldSucceed() {
// NOTE: Only works with `SWIFT_DETERMINISTIC_HASHING` env var set
let d1 = ["a" : 1, "b" : 2, "c" : 3]
let d2 = ["a" : 1, "b" : 2, "c" : 3]
assertDumpsEqual(d1, d2)
}
}
| mit | 03b9e1f504799a49830bca2c7216454c | 19.457627 | 74 | 0.534383 | 3.126943 | false | true | false | false |
wangjianquan/wjq-weibo | weibo_wjq/Home/View/HomeCell.swift | 1 | 4005 | //
// HomeCell.swift
// weibo_wjq
//
// Created by landixing on 2017/6/1.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
import SDWebImage
private let edgeMargin : CGFloat = 10
private let itemMargin : CGFloat = 12
class HomeCell: UITableViewCell {
@IBOutlet var picCollectionView: PicCollectionView!
@IBOutlet var flowLayout: UICollectionViewFlowLayout!
/// 头像
@IBOutlet weak var iconImageView: UIImageView!
/// 认证图标
@IBOutlet weak var verifiedImageView: UIImageView!
/// 昵称
@IBOutlet weak var nameLabel: UILabel!
/// 会员图标
@IBOutlet weak var vipImageView: UIImageView!
/// 时间
@IBOutlet weak var timeLabel: UILabel!
/// 来源
@IBOutlet weak var sourceLabel: UILabel!
/// 正文
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet var footerview: UIView!
@IBOutlet var retweetBgView: UIView!
//转发微博正文
@IBOutlet var retweetedContentLabel: UILabel!
@IBOutlet var retweetedContentLabelTopCons: NSLayoutConstraint!
var viewModel : StatusViewModel?
{
didSet {
// 1.nil值校验
guard let viewModel = viewModel else {
return
}
//头像
iconImageView.layer.cornerRadius = 30
iconImageView.layer.masksToBounds = true
iconImageView.sd_setImage(with: viewModel.icon_URL)
//认证图标
verifiedImageView.image = viewModel.verified_image
//会员图标
/// 会员等级 ,取值范围 1~6
vipImageView.image = viewModel.mbrankImage
//昵称
if let nameStr = viewModel.status.user?.screen_name {
nameLabel.text = nameStr
}
nameLabel.textColor = viewModel.mbrankImage == nil ? UIColor.black : UIColor.orange
//时间
timeLabel.text = viewModel.created_Time
//微博来源
sourceLabel.text = viewModel.source_Text
//内容
contentLabel.text = viewModel.status.text
//注册重用标示符
let nib = UINib(nibName: "PicCollectionViewCell", bundle: nil)
picCollectionView.register(nib, forCellWithReuseIdentifier: "PicCollectionViewCell")
picCollectionView.reloadData()
picCollectionView.picURLs = viewModel.thumbnail_pic
//设置转发正文
if viewModel.status.retweeted_status != nil {
//设置正文
if let nickName = viewModel.status.retweeted_status?.user?.screen_name, let retweetText = viewModel.status.retweeted_status?.text {
retweetedContentLabel.text = "@" + "\(nickName): " + retweetText
retweetedContentLabelTopCons.constant = 15
}
//2. 设置背景显示
retweetBgView.isHidden = false
} else {
// 1.设置转发微博的正文
retweetedContentLabel.text = nil
// 2.设置背景显示
retweetBgView.isHidden = true
// 3.设置转发正文距离顶部的约束
retweetedContentLabelTopCons.constant = 0
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
extension HomeCell {
func calculateRowHeight(_ viewModel: StatusViewModel) -> CGFloat {
self.viewModel = viewModel
self.layoutIfNeeded()
return footerview.frame.maxY
}
}
| apache-2.0 | 4f932f4e31a6b1582e95ab80cda2c4ba | 25.319444 | 147 | 0.556992 | 5.375887 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Laundry/Cells/LaundryMachineCell.swift | 1 | 3098 | //
// LaundryMachineCell.swift
// PennMobile
//
// Created by Dominic Holmes on 10/28/17.
// Copyright © 2017 PennLabs. All rights reserved.
//
import UIKit
class LaundryMachineCell: UICollectionViewCell {
static let identifier = "laundryMachineCell"
var machine: LaundryMachine! {
didSet {
if let machine = machine {
updateCell(with: machine)
}
}
}
private let bgImageView: UIImageView = {
let bg = UIImageView()
bg.backgroundColor = .clear
bg.layer.cornerRadius = 25
return bg
}()
private let bellView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "bell")?.withTintColor(.baseYellow)
iv.isHidden = true
return iv
}()
private let timerLabel: UILabel = {
let label = UILabel()
label.text = ""
label.font = .primaryInformationFont
label.textColor = .labelSecondary
label.layer.cornerRadius = 4
label.layer.masksToBounds = true
label.textAlignment = .center
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
setupViews()
}
func setupViews() {
self.addSubview(bgImageView)
_ = bgImageView.anchor(topAnchor, left: leftAnchor,
bottom: bottomAnchor, right: rightAnchor,
topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0,
widthConstant: 0, heightConstant: 0)
self.addSubview(timerLabel)
_ = timerLabel.anchor(topAnchor, left: leftAnchor,
bottom: bottomAnchor, right: rightAnchor,
topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0,
widthConstant: 0, heightConstant: 0)
self.addSubview(bellView)
bellView.centerYAnchor.constraint(equalTo: topAnchor).isActive = true
_ = bellView.anchor(nil, left: nil, bottom: nil, right: rightAnchor, topConstant: -8, leftConstant: 0, bottomConstant: 0, rightConstant: -8, widthConstant: 20, heightConstant: 20)
}
func updateCell(with machine: LaundryMachine) {
let typeStr = machine.isWasher ? "washer" : "dryer"
let statusStr: String
switch machine.status {
case .open:
statusStr = "open"
case .running:
statusStr = "busy"
case .offline,
.outOfOrder:
statusStr = "broken"
}
bgImageView.image = UIImage(named: "\(typeStr)_\(statusStr)")
if machine.status == .running && machine.timeRemaining > 0 {
timerLabel.text = "\(machine.timeRemaining)"
} else {
timerLabel.text = ""
}
bellView.isHidden = !machine.isUnderNotification()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | c958d5a638ea05b9043b2a96e8274437 | 30.602041 | 187 | 0.576364 | 4.80155 | false | false | false | false |
practicalswift/swift | test/Interpreter/SDK/objc_extensions.swift | 35 | 1150 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
extension NSObject {
@objc func frob() {
print("I've been frobbed!")
}
@objc var asHerself : NSObject {
return self
}
@objc var blackHoleWithHawkingRadiation : NSObject? {
get {
print("e+")
return nil
}
set {
print("e-")
}
}
}
var o = NSObject()
func drop(_ x: NSObject?) {}
// CHECK: true
print(o.responds(to: "frob"))
// CHECK: true
print(o.responds(to: "asHerself"))
// CHECK: false
print(o.responds(to: "setAsHerself:"))
// CHECK: true
print(o.responds(to: "blackHoleWithHawkingRadiation"))
// CHECK: true
print(o.responds(to: "setBlackHoleWithHawkingRadiation:"))
// Test #selector for referring to methods.
// CHECK: true
print(o.responds(to: #selector(NSObject.frob)))
// CHECK: I've been frobbed!
o.frob()
// CHECK: true
print(o === o.asHerself)
// CHECK: e+
drop(o.blackHoleWithHawkingRadiation)
// CHECK: e-
o.blackHoleWithHawkingRadiation = NSObject()
// Use of extensions via bridging
let str = "Hello, world"
// CHECK: I've been frobbed!
str.frob()
| apache-2.0 | a214390f01e967deba0d54b412f4df74 | 18.491525 | 58 | 0.663478 | 3.203343 | false | false | false | false |
qwang216/Pokedex | PokeDex/Pokemon.swift | 1 | 1096 | //
// Pokemon.swift
// PokeDex
//
// Created by Jason Wang on 10/15/16.
// Copyright © 2016 Jason Wang. All rights reserved.
//
import Foundation
class Pokemon: NSObject {
@objc let name: String
let pkDexID: Int
let imageUrlString: String
let descriptionString: String
@objc let types: [String]
init(name: String, pkDexID: Int, imageUrl: String, description: String, types: [String]) {
self.name = name
self.pkDexID = pkDexID
self.imageUrlString = imageUrl
self.descriptionString = description
self.types = types
}
convenience init?(withDict pkDict: [String: Any]) {
if let name = pkDict["name"] as? String,
let id = pkDict["pkdx_id"] as? Int,
let urlString = pkDict["art_url"] as? String,
let pkDescription = pkDict["description"] as? String,
let pkTypes = pkDict["types"] as? [String] {
self.init(name: name, pkDexID: id, imageUrl: urlString, description: pkDescription, types: pkTypes)
} else {
return nil
}
}
}
| mit | 7c51b3698bb898eb21a874606a05a5d0 | 28.594595 | 111 | 0.607306 | 3.869258 | false | false | false | false |
AlesTsurko/AudioKit | Examples/OSX/Swift/AudioKitDemo/AudioKitDemo/FMSynthesizer.swift | 1 | 1725 | //
// FMSynthesizer.swift
// AudioKitDemo
//
// Created by Nicholas Arner on 3/1/15.
// Copyright (c) 2015 AudioKit. All rights reserved.
//
class FMSynthesizer: AKInstrument{
override init() {
super.init()
// Note Properties
var note = FMSynthesizerNote()
addNoteProperty(note.frequency)
addNoteProperty(note.color)
let envelope = AKADSREnvelope(
attackDuration: 0.1.ak,
decayDuration: 0.1.ak,
sustainLevel: 0.5.ak,
releaseDuration: 0.3.ak,
delay: 0.ak
)
connect(envelope)
var oscillator = AKFMOscillator()
oscillator.baseFrequency = note.frequency
oscillator.carrierMultiplier = note.color.scaledBy(2.ak)
oscillator.modulatingMultiplier = note.color.scaledBy(3.ak)
oscillator.modulationIndex = note.color.scaledBy(10.ak)
oscillator.amplitude = envelope.scaledBy(0.25.ak)
connect(oscillator)
let out = AKAudioOutput(input: oscillator)
connect(out)
}
}
class FMSynthesizerNote: AKNote {
// Note Properties
var frequency = AKNoteProperty(value: 440, minimum: 100, maximum: 20000)
var color = AKNoteProperty(value: 0, minimum: 0, maximum: 1)
override init() {
super.init()
addProperty(frequency)
addProperty(color)
// Optionally set a default note duration
duration.setValue(1.0)
}
convenience init(frequency:Float, color:Float){
self.init()
self.frequency.setValue(frequency)
self.color.setValue(color)
}
} | lgpl-3.0 | 6b45857d11f89855fe91aa83a1b56a59 | 25.151515 | 76 | 0.586667 | 4.434447 | false | false | false | false |
5calls/ios | FiveCalls/FiveCalls/MyImpactViewController.swift | 1 | 5694 | //
// MyImpactViewController.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/6/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import Rswift
class MyImpactViewController : UITableViewController {
private var viewModel: ImpactViewModel!
private var userStats: UserStats?
private var totalCalls: Int?
@IBOutlet weak var streakLabel: UILabel!
@IBOutlet weak var impactLabel: UILabel!
@IBOutlet weak var subheadLabel: UILabel!
enum Sections: Int {
case stats
case contacts
case count
var cellIdentifier: Rswift.ReuseIdentifier<UIKit.UITableViewCell>? {
switch self {
case .stats: return R.reuseIdentifier.statCell
case .contacts: return R.reuseIdentifier.contactStatCell
default: return nil
}
}
}
enum StatRow: Int {
case madeContact
case voicemail
case unavailable
case count
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.font: UIFont.fvc_header,
NSAttributedString.Key.foregroundColor: UIColor.white
]
displayStats()
fetchServerStats()
sizeHeaderToFit()
let totalCallsOp = FetchStatsOperation()
totalCallsOp.completionBlock = {
self.totalCalls = totalCallsOp.numberOfCalls
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
OperationQueue.main.addOperation(totalCallsOp)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func sizeHeaderToFit() {
let headerView = tableView.tableHeaderView!
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
tableView.tableHeaderView = headerView
}
func displayStats() {
viewModel = ImpactViewModel(logs: ContactLogs.load(), stats: userStats)
streakLabel.text = viewModel.weeklyStreakMessage
impactLabel.text = viewModel.impactMessage
if viewModel.numberOfCalls == 0 {
subheadLabel.isHidden = true
subheadLabel.addConstraint(NSLayoutConstraint(item: subheadLabel as Any, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0))
}
tableView.reloadData()
}
private func fetchServerStats() {
// Fetch the user's call stats
let userStatsOp = FetchUserStatsOperation()
userStatsOp.completionBlock = {
if let error = userStatsOp.error {
AnalyticsManager.shared.trackError(error: error)
}
self.userStats = userStatsOp.userStats
DispatchQueue.main.async {
self.displayStats()
}
}
OperationQueue.main.addOperation(userStatsOp)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return Sections.count.rawValue
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Sections(rawValue: section)! {
case .stats:
return StatRow.count.rawValue
case .contacts:
return 0
default: return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = Sections(rawValue: indexPath.section)!
let identifier = section.cellIdentifier
let cell = tableView.dequeueReusableCell(withIdentifier: identifier!, for: indexPath)!
switch section {
case .stats:
configureStatRow(cell: cell, stat: StatRow(rawValue: indexPath.row)!)
default: break
}
return cell
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard let total = totalCalls, section == Sections.stats.rawValue else { return nil }
let statsVm = StatsViewModel(numberOfCalls: total)
return R.string.localizable.communityCalls(statsVm.formattedNumberOfCalls)
}
private func configureStatRow(cell: UITableViewCell, stat: StatRow) {
switch stat {
case .madeContact:
cell.textLabel?.text = R.string.localizable.madeContact()
cell.detailTextLabel?.text = timesString(count: viewModel.madeContactCount)
case .unavailable:
cell.textLabel?.text = R.string.localizable.unavailable()
cell.detailTextLabel?.text = timesString(count: viewModel.unavailableCount)
case .voicemail:
cell.textLabel?.text = R.string.localizable.leftVoicemail()
cell.detailTextLabel?.text = timesString(count: viewModel.voicemailCount)
default: break
}
}
@IBAction func done(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
private func timesString(count: Int) -> String {
guard count != 1 else { return R.string.localizable.calledSingle(count) }
return R.string.localizable.calledMultiple(count)
}
}
| mit | 731d2f9061be56ebad598e1b4c389b1f | 31.346591 | 193 | 0.629896 | 5.21337 | false | false | false | false |
Tatoeba/tatoeba-ios | Tatoeba/Common/Networking/SentencesRequest.swift | 1 | 1445 | //
// SentencesRequest.swift
// Tatoeba
//
// Created by Jack Cook on 8/6/17.
// Copyright © 2017 Tatoeba. All rights reserved.
//
import Alamofire
import SwiftyJSON
/// Returns sentences using the specified parameters.
final class SentencesRequest: TatoebaRequest {
typealias ResponseData = JSON
typealias Value = [Sentence]
var endpoint: String {
return "/sentences"
}
var parameters: Parameters {
var params: Parameters = ["q": query, "offset": offset]
if let fromLanguage = fromLanguage {
params["from"] = fromLanguage
}
return params
}
var responseType: TatoebaResponseType {
return .json
}
let query: String
let offset: Int
let fromLanguage: String?
init(query: String, offset: Int = 0, fromLanguage: String? = nil) {
self.query = query
self.offset = offset
self.fromLanguage = fromLanguage
}
func handleRequest(_ json: JSON?, _ completion: @escaping ([Sentence]?) -> Void) {
guard let sentencesData = json?.array else {
completion(nil)
return
}
var sentences = [Sentence]()
for sentenceDatum in sentencesData {
let sentence = Sentence(json: sentenceDatum)
sentences.append(sentence)
}
completion(sentences)
}
}
| mit | ce6952628fc31839c07156330d9a3782 | 22.672131 | 86 | 0.578947 | 4.781457 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Extensions/UIImageExtension.swift | 1 | 1368 | //
// UIImageExtension.swift
// Inbbbox
//
// Created by Lukasz Wolanczyk on 2/10/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
import GPUImage
extension UIImage {
// MARK: Initializers
/// Initializes the image with color and size.
/// By default width and height are set to 1.
///
/// - Parameters:
/// - color: `UIColor` the image will be filled with.
/// - size: Size of the image.
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else {
return nil
}
self.init(cgImage: cgImage)
}
/// Blurred image.
///
/// - parameter blur: float value of blur added to image
///
/// - returns: blurred image
func imageByBlurringImageWithBlur(_ blur: CGFloat) -> UIImage {
let maxBlurRadius = CGFloat(1)
let blurFilter = GPUImageGaussianBlurFilter()
blurFilter.blurRadiusInPixels = blur * maxBlurRadius
return blurFilter.image(byFilteringImage: self)
}
}
| gpl-3.0 | 94d54c429129ab15f3f67eb5da938234 | 27.479167 | 83 | 0.630578 | 4.38141 | false | false | false | false |
alexzatsepin/omim | iphone/Maps/Bookmarks/Categories/Sharing/GuideNameViewController.swift | 4 | 1638 | protocol GuideNameViewControllerDelegate {
func viewController(_ viewController: GuideNameViewController, didFinishEditing text: String)
}
class GuideNameViewController: MWMTableViewController {
@IBOutlet weak var nextBarButton: UIBarButtonItem!
@IBOutlet weak var nameTextField: UITextField!
var guideName: String?
var delegate: GuideNameViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
title = L("name")
nameTextField.placeholder = L("name_placeholder")
nameTextField.text = guideName
nameTextField.becomeFirstResponder()
nextBarButton.isEnabled = (nameTextField.text?.count ?? 0) > 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return L("name_title")
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return L("name_comment1") + "\n\n" + L("name_comment2")
}
@IBAction func onEditName(_ sender: UITextField) {
let length = sender.text?.count ?? 0
nextBarButton.isEnabled = length > 0
}
@IBAction func onNext(_ sender: UIBarButtonItem) {
delegate?.viewController(self, didFinishEditing: nameTextField.text ?? "")
}
}
extension GuideNameViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let text = textField.text as NSString? else { return true }
let resultText = text.replacingCharacters(in: range, with: string)
return resultText.count <= 42
}
}
| apache-2.0 | df59b3969601c4f9a2867b6fe18d3139 | 33.851064 | 102 | 0.723443 | 4.94864 | false | false | false | false |
makhiye/flagMatching | flag Matching/GameViewController.swift | 1 | 3722 | //
// GameViewController.swift
// flag Matching
//
// Created by ishmael on 7/17/17.
// Copyright © 2017 ishmael.mthombeni. All rights reserved.
//
import UIKit
import LTMorphingLabel
import MZTimerLabel
class GameViewController: UIViewController, MatchingGameDelegate {
var game = Game()
var gameNumber = 1
var stopWatch: MZTimerLabel!
@IBOutlet weak var gameLabel: LTMorphingLabel!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var cardButton: UIButton!
var counter = 0
@IBAction func cardTapped(_ sender: UIButton) {
let tagNum = sender.tag
if game.flipCard(atIndexNumber: tagNum-1){
let thisImage = UIImage(named: game.deckOfCards.dealtCards[tagNum - 1])
UIView.transition(with: sender, duration: 0.5, options: .transitionCurlDown, animations: {sender.setImage(thisImage, for: .normal)}, completion: nil)
if game.unMatchedCards.isEmpty {
displayGameOver()
}
}
}
@IBAction func newGame(_ sender: UIButton) {
counter += 1
for tagNum in 1...12 {
if let thisButton = self.view.viewWithTag(tagNum) as? UIButton{
UIView.transition(with: thisButton, duration: 0.5, options: .transitionCurlDown, animations: {
thisButton.setImage(#imageLiteral(resourceName: "AACard"), for: .normal)
}, completion: nil)
stopWatch.reset()
}
}
gameNumber += 1
gameLabel.text = " Game #\(gameNumber) "
game.newGame()
stopWatch.reset()
stopWatch.start()
}
func game(_ game: Game, hideCards cards: [Int]) {
let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime){
for cardIndex in cards {
if let thisButton = self.view.viewWithTag(cardIndex+1) as? UIButton{
UIView.transition(with: thisButton, duration: 0.5, options: .transitionCurlDown, animations: {
thisButton.setImage(#imageLiteral(resourceName: "AACard"), for: .normal)
}, completion: nil)
}
}
self.game.waitingForHidingCards = false // All unmatched are hidden
}
}
func displayGameOver() {
gameLabel.text = "GAME OVER!"
}
override func viewDidLoad() {
super.viewDidLoad()
game.gameDelegate = self // setting gameDelegate to game
gameLabel.morphingEffect = .burn
stopWatch = MZTimerLabel.init(label: timerLabel)
stopWatch.timeFormat = "mm:ss"
stopWatch?.start()
gameLabel.layer.masksToBounds = true
gameLabel.layer.cornerRadius = 5
timerLabel.layer.masksToBounds = true
timerLabel.layer.cornerRadius = 5
gameLabel.text = " Game #\(gameNumber) "
// 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.
}
}
| mit | c61adf968fef3b1c2e1a32ece85e2502 | 25.204225 | 161 | 0.529965 | 5.175243 | false | false | false | false |
exyte/Macaw | Source/model/geom2d/Transform.swift | 1 | 4995 | import Foundation
public final class Transform {
public let m11: Double
public let m12: Double
public let m21: Double
public let m22: Double
public let dx: Double
public let dy: Double
public static let identity = Transform()
public init(_ m11: Double, _ m12: Double, _ m21: Double, _ m22: Double, _ dx: Double, _ dy: Double) {
self.m11 = m11
self.m12 = m12
self.m21 = m21
self.m22 = m22
self.dx = dx
self.dy = dy
}
public init(m11: Double = 1, m12: Double = 0, m21: Double = 0, m22: Double = 1, dx: Double = 0, dy: Double = 0) {
self.m11 = m11
self.m12 = m12
self.m21 = m21
self.m22 = m22
self.dx = dx
self.dy = dy
}
public func move(_ dx: Double, _ dy: Double) -> Transform {
return move(dx: dx, dy: dy)
}
public func move(dx: Double = 0, dy: Double = 0) -> Transform {
return Transform(m11: m11, m12: m12, m21: m21, m22: m22,
dx: dx * m11 + dy * m21 + self.dx,
dy: dx * m12 + dy * m22 + self.dy)
}
public func scale(sx: Double = 0, sy: Double = 0) -> Transform {
return Transform(m11: m11 * sx, m12: m12 * sx, m21: m21 * sy, m22: m22 * sy, dx: dx, dy: dy)
}
public func scale(_ sx: Double, _ sy: Double) -> Transform {
return scale(sx: sx, sy: sy)
}
public func shear(shx: Double = 0, shy: Double = 0) -> Transform {
return Transform(m11: m11 + m21 * shy, m12: m12 + m22 * shy,
m21: m11 * shx + m21, m22: m12 * shx + m22, dx: dx, dy: dy)
}
public func shear(_ shx: Double, _ shy: Double) -> Transform {
return shear(shx: shx, shy: shy)
}
public func rotate(angle: Double) -> Transform {
let asin = sin(angle)
let acos = cos(angle)
return Transform(m11: acos * m11 + asin * m21, m12: acos * m12 + asin * m22,
m21: -asin * m11 + acos * m21, m22: -asin * m12 + acos * m22,
dx: dx, dy: dy)
}
public func rotate(_ angle: Double) -> Transform {
return rotate(angle: angle)
}
public func rotate(angle: Double, x: Double = 0, y: Double = 0) -> Transform {
return move(dx: x, dy: y).rotate(angle: angle).move(dx: -x, dy: -y)
}
public func rotate(_ angle: Double, _ x: Double, _ y: Double) -> Transform {
return rotate(angle: angle, x: x, y: y)
}
public class func move(dx: Double = 0, dy: Double = 0) -> Transform {
return Transform(dx: dx, dy: dy)
}
public class func move(_ dx: Double, _ dy: Double) -> Transform {
return Transform(dx: dx, dy: dy)
}
public class func scale(sx: Double = 0, sy: Double = 0) -> Transform {
return Transform(m11: sx, m22: sy)
}
public class func scale(_ sx: Double, _ sy: Double) -> Transform {
return Transform(m11: sx, m22: sy)
}
public class func shear(shx: Double = 0, shy: Double = 0) -> Transform {
return Transform(m12: shy, m21: shx)
}
public class func shear(_ shx: Double, _ shy: Double) -> Transform {
return Transform(m12: shy, m21: shx)
}
public class func rotate(angle: Double) -> Transform {
let asin = sin(angle); let acos = cos(angle)
return Transform(m11: acos, m12: asin, m21: -asin, m22: acos)
}
public class func rotate(_ angle: Double) -> Transform {
return rotate(angle: angle)
}
public class func rotate(angle: Double, x: Double = 0, y: Double = 0) -> Transform {
return Transform.move(dx: x, dy: y).rotate(angle: angle).move(dx: -x, dy: -y)
}
public class func rotate(_ angle: Double, _ x: Double, _ y: Double) -> Transform {
return rotate(angle: angle, x: x, y: y)
}
public func concat(with: Transform) -> Transform {
let nm11 = with.m11 * m11 + with.m12 * m21
let nm21 = with.m21 * m11 + with.m22 * m21
let ndx = with.dx * m11 + with.dy * m21 + dx
let nm12 = with.m11 * m12 + with.m12 * m22
let nm22 = with.m21 * m12 + with.m22 * m22
let ndy = with.dx * m12 + with.dy * m22 + dy
return Transform(m11: nm11, m12: nm12, m21: nm21, m22: nm22, dx: ndx, dy: ndy)
}
public func apply(to: Point) -> Point {
let x = m11 * to.x + m12 * to.y + dx
let y = m21 * to.x + m22 * to.y + dy
return Point(x: x, y: y)
}
public func invert() -> Transform? {
if m11 == 1 && m12 == 0 && m21 == 0 && m22 == 1 {
return .move(dx: -dx, dy: -dy)
}
let det = self.m11 * self.m22 - self.m12 * self.m21
if det == 0 {
return nil
}
return Transform(m11: m22 / det, m12: -m12 / det,
m21: -m21 / det, m22: m11 / det,
dx: (m21 * dy - m22 * dx) / det,
dy: (m12 * dx - m11 * dy) / det)
}
}
| mit | 8795573520bbefb3b1839e8b2549b2bb | 32.3 | 117 | 0.526326 | 3.185587 | false | false | false | false |
Diederia/project | Diederick-Calkoen-Project/SettingsViewController.swift | 1 | 8604 | //
// SettingsViewController.swift
// Diederick-Calkoen-Project
//
// Created by Diederick Calkoen on 20/01/17.
// Copyright © 2017 Diederick Calkoen. All rights reserved.
//
// In this view it is possible to see and change settings of there own account. You could change your password, id and mobile number.
import UIKit
import Firebase
class SettingsViewController: UIViewController, UITextFieldDelegate {
// MARK: - Outlets
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var settingsLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var firstAndSurenameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var emailAddressLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var idTextField: UITextField!
@IBOutlet weak var idButton: UIButton!
@IBOutlet weak var mobileButton: UIButton!
@IBOutlet weak var mobileLabel: UILabel!
@IBOutlet weak var mobileTextField: UITextField!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var oldPasswordTextField: UITextField!
@IBOutlet weak var newPasswordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
// MARK: - Variables
var userData = [String:AnyObject]()
var ref = FIRDatabase.database().reference()
// MARK: - Override functions
override func viewDidLoad() {
super.viewDidLoad()
setupText()
setupRoundCorners()
setupBorders()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Functions
// Setup the text in the labels and texfields.
func setupText() {
userData = UserDefaults.standard.value(forKey: "userData") as! [String : AnyObject]
firstAndSurenameLabel.text = (userData["firstName"] as! String?)! + " " + (userData["surename"] as! String?)!
emailAddressLabel.text = userData["email"] as! String?
idTextField.text = userData["id"] as! String?
mobileTextField.text = userData["mobile"] as! String?
if userData["userStatus"] as! Int? == 0 {
userLabel.text = "Leerling"
} else if userData["userStatus"] as! Int? == 1 {
userLabel.text = "Docent"
} else if userData["userStatus"] as! Int? == 2 {
userLabel.text = "Admin"
}
}
// Give the corners a radius of 5.
func setupRoundCorners() {
nameLabel.roundCorners(corners: [.topLeft, .bottomLeft], radius: 5)
firstAndSurenameLabel.roundCorners(corners: [.topRight, .bottomRight], radius: 5)
emailLabel.roundCorners(corners: [.topLeft, .bottomLeft], radius: 5)
emailAddressLabel.roundCorners(corners: [.topRight, .bottomRight], radius: 5)
statusLabel.roundCorners(corners: [.topLeft, .bottomLeft], radius: 5)
userLabel.roundCorners(corners: [.topRight, .bottomRight], radius: 5)
idLabel.roundCorners(corners: [.topLeft, .bottomLeft], radius: 5)
idButton.roundCorners(corners: [.topRight, .bottomRight], radius: 5)
mobileLabel.roundCorners(corners: [.topLeft, .bottomLeft], radius: 5)
mobileButton.roundCorners(corners: [.topRight, .bottomRight], radius: 5)
}
// Give the borders a width, radius and color
func setupBorders(){
settingsLabel.layer.cornerRadius = 5
settingsLabel.layer.borderWidth = 2
settingsLabel.layer.borderColor = UIColor.white.cgColor
passwordLabel.layer.cornerRadius = 5
passwordLabel.layer.borderWidth = 2
passwordLabel.layer.borderColor = UIColor.white.cgColor
firstAndSurenameLabel.layer.borderWidth = 2
firstAndSurenameLabel.layer.borderColor = UIColor.white.cgColor
emailAddressLabel.layer.borderWidth = 2
emailAddressLabel.layer.borderColor = UIColor.white.cgColor
userLabel.layer.borderWidth = 2
userLabel.layer.borderColor = UIColor.white.cgColor
}
// Hide keyboard when user touches return.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Scroll the view up, so you users sees the textfield.
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == idTextField || textField == mobileTextField || textField == oldPasswordTextField || textField == newPasswordTextField || textField == confirmPasswordTextField {
scrollView.setContentOffset(CGPoint(x:0, y:175), animated: true)
} else {
scrollView.setContentOffset(CGPoint(x:0, y:75), animated: true)
}
}
// Scroll the view down when the ends editing.
func textFieldDidEndEditing(_ textField: UITextField) {
scrollView.setContentOffset(CGPoint(x:0, y:0), animated: true)
}
// Function to make an alert.
func alert(title: String, message: String, actionTitle: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: actionTitle, style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
// Function to check the provided input for the new password.
func checkInput() {
guard newPasswordTextField.text! != "" && confirmPasswordTextField.text! != "" else {
self.alert(title: "Fountmelding met registreren", message: "Type een geldig emailadres, wachtwoord en bevestigings wachtwoord.\n Het wachtwoord moet minimaal 6 karakters lang zijn.", actionTitle: "Terug")
return
}
guard newPasswordTextField.text!.characters.count >= 6 else {
self.alert(title: "Fountmelding met registreren", message: "Het wachtwoord moet minimaal 6 karakters lang zijn.", actionTitle: "Terug")
return
}
guard newPasswordTextField.text! == confirmPasswordTextField.text! else {
self.alert(title: "Fountmelding met registreren", message: "De wachtwoorden komen niet overeen.", actionTitle: "Terug")
return
}
}
// Function to reauthenticate and update password.
func updatePassword(email: String, oldPassword: String, newPassword: String) {
let credential = FIREmailPasswordAuthProvider.credential(withEmail: email, password: oldPassword)
let firUser = FIRAuth.auth()?.currentUser
FIRAuth.auth()?.currentUser?.reauthenticate(with: credential) { error in
if error != nil {
self.alert(title: "Foudmelding" , message: "Het wachtwoord kan niet aangepast worden.", actionTitle: "Terug")
} else {
firUser?.updatePassword(newPassword) { error in
if error != nil {
self.alert(title: "Foudmelding" , message: "Het wachtwoord kan niet aangepast worden.", actionTitle: "Terug")
} else {
self.alert(title: "Gereed" , message: "Het wachtwoord is aangepast.", actionTitle: "Terug")
}
}
}
}
}
// MARK: - Actions
@IBAction func updateIdButton(_ sender: Any) {
let uid = FIRAuth.auth()?.currentUser?.uid
let ref = self.ref.child("users").child(uid!)
ref.updateChildValues(["id": idTextField.text!])
print(ref.updateChildValues(["id": idTextField.text!]))
self.alert(title: "Gereed" , message: "Het id is aangepast.", actionTitle: "Terug")
}
@IBAction func updateMobileButton(_ sender: Any) {
let uid = FIRAuth.auth()?.currentUser?.uid
let ref = self.ref.child("users").child(uid!)
ref.updateChildValues(["mobile": mobileTextField.text!])
self.alert(title: "Gereed" , message: "Het nummer is aangepast.", actionTitle: "Terug")
}
@IBAction func updatePasswordButton(_ sender: Any) {
checkInput()
let email = User.FirebaseEmail
let oldPassword = oldPasswordTextField.text!
let newPassword = newPasswordTextField.text!
updatePassword(email: email!, oldPassword: oldPassword, newPassword: newPassword)
}
}
| mit | 84f401c93124f30b03be0b50a3fe72ba | 41.171569 | 216 | 0.651866 | 4.590715 | false | false | false | false |
milseman/swift | stdlib/public/core/CharacterUnicodeScalars.swift | 5 | 4532 | //===--- CharacterUnicodeScalars.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
//
//===----------------------------------------------------------------------===//
extension Character {
public struct UnicodeScalarView {
internal let _base: Character
}
public var unicodeScalars : UnicodeScalarView {
return UnicodeScalarView(_base: self)
}
}
extension Character.UnicodeScalarView {
public struct Iterator {
internal var _base: IndexingIterator<Character.UnicodeScalarView>
}
}
extension Character.UnicodeScalarView.Iterator : IteratorProtocol {
public mutating func next() -> UnicodeScalar? {
return _base.next()
}
}
extension Character.UnicodeScalarView : Sequence {
public func makeIterator() -> Iterator {
return Iterator(_base: IndexingIterator(_elements: self))
}
}
extension Character.UnicodeScalarView {
public struct Index {
internal let _encodedOffset: Int
internal let _scalar: Unicode.UTF16.EncodedScalar
internal let _stride: UInt8
}
}
extension Character.UnicodeScalarView.Index : Equatable {
public static func == (
lhs: Character.UnicodeScalarView.Index,
rhs: Character.UnicodeScalarView.Index
) -> Bool {
return lhs._encodedOffset == rhs._encodedOffset
}
}
extension Character.UnicodeScalarView.Index : Comparable {
public static func < (
lhs: Character.UnicodeScalarView.Index,
rhs: Character.UnicodeScalarView.Index
) -> Bool {
return lhs._encodedOffset < rhs._encodedOffset
}
}
extension Character.UnicodeScalarView : Collection {
public var startIndex: Index {
return index(
after: Index(
_encodedOffset: 0,
_scalar: Unicode.UTF16.EncodedScalar(),
_stride: 0
))
}
public var endIndex: Index {
return Index(
_encodedOffset: _base._smallUTF16?.count ?? _base._largeUTF16!.count,
_scalar: Unicode.UTF16.EncodedScalar(),
_stride: 0
)
}
public func index(after i: Index) -> Index {
var parser = Unicode.UTF16.ForwardParser()
let startOfNextScalar = i._encodedOffset + numericCast(i._stride)
let r: Unicode.ParseResult<Unicode.UTF16.EncodedScalar>
let small_ = _base._smallUTF16
if _fastPath(small_ != nil), let u16 = small_ {
var i = u16[u16.index(u16.startIndex, offsetBy: startOfNextScalar)...]
.makeIterator()
r = parser.parseScalar(from: &i)
}
else {
var i = _base._largeUTF16![startOfNextScalar...].makeIterator()
r = parser.parseScalar(from: &i)
}
switch r {
case .valid(let s):
return Index(
_encodedOffset: startOfNextScalar, _scalar: s,
_stride: UInt8(truncatingIfNeeded: s.count))
case .error:
return Index(
_encodedOffset: startOfNextScalar,
_scalar: Unicode.UTF16.encodedReplacementCharacter,
_stride: 1)
case .emptyInput:
if i._stride != 0 { return endIndex }
fatalError("no position after end of Character's last Unicode.Scalar")
}
}
public subscript(_ i: Index) -> UnicodeScalar {
return Unicode.UTF16.decode(i._scalar)
}
}
extension Character.UnicodeScalarView : BidirectionalCollection {
public func index(before i: Index) -> Index {
var parser = Unicode.UTF16.ReverseParser()
let r: Unicode.ParseResult<Unicode.UTF16.EncodedScalar>
let small_ = _base._smallUTF16
if _fastPath(small_ != nil), let u16 = small_ {
var i = u16[..<u16.index(u16.startIndex, offsetBy: i._encodedOffset)]
.reversed().makeIterator()
r = parser.parseScalar(from: &i)
}
else {
var i = _base._largeUTF16![..<i._encodedOffset].reversed().makeIterator()
r = parser.parseScalar(from: &i)
}
switch r {
case .valid(let s):
return Index(
_encodedOffset: i._encodedOffset - s.count, _scalar: s,
_stride: UInt8(truncatingIfNeeded: s.count))
case .error:
return Index(
_encodedOffset: i._encodedOffset - 1,
_scalar: Unicode.UTF16.encodedReplacementCharacter,
_stride: 1)
case .emptyInput:
fatalError("no position before Character's last Unicode.Scalar")
}
}
}
| apache-2.0 | 193087b9e780284cadc43798e5b851ef | 28.815789 | 80 | 0.649162 | 4.349328 | false | false | false | false |
milseman/swift | test/stdlib/NewStringAppending.swift | 12 | 3860 | // RUN: %target-run-stdlib-swift | %FileCheck %s
// REQUIRES: executable_test
//
// Parts of this test depend on memory allocator specifics. The test
// should be rewritten soon so it doesn't expose legacy components
// like OpaqueString anyway, so we can just disable the failing
// configuration
//
// Memory allocator specifics also vary across platforms.
// REQUIRES: CPU=x86_64, OS=macosx
import Foundation
import Swift
func hexAddrVal<T>(_ x: T) -> String {
return "@0x" + String(UInt64(unsafeBitCast(x, to: Int.self)), radix: 16)
}
func hexAddr(_ x: AnyObject?) -> String {
if let owner = x {
if let y = owner as? _HeapBufferStorage<_StringBufferIVars, UInt16> {
return ".native\(hexAddrVal(y))"
}
if let y = owner as? NSString {
return ".cocoa\(hexAddrVal(y))"
}
else {
return "?Uknown?\(hexAddrVal(owner))"
}
}
return "nil"
}
func repr(_ x: NSString) -> String {
return "\(NSStringFromClass(object_getClass(x)))\(hexAddr(x)) = \"\(x)\""
}
func repr(_ x: _StringCore) -> String {
if x.hasContiguousStorage {
if let b = x.nativeBuffer {
let offset = x.elementWidth == 2
? b.start - UnsafeMutableRawPointer(x.startUTF16)
: b.start - UnsafeMutableRawPointer(x.startASCII)
return "Contiguous(owner: "
+ "\(hexAddr(x._owner))[\(offset)...\(x.count + offset)]"
+ ", capacity = \(b.capacity))"
}
return "Contiguous(owner: \(hexAddr(x._owner)), count: \(x.count))"
}
else if let b2 = x.cocoaBuffer {
return "Opaque(buffer: \(hexAddr(b2))[0...\(x.count)])"
}
return "?????"
}
func repr(_ x: String) -> String {
return "String(\(repr(x._core))) = \"\(x)\""
}
// ===------- Appending -------===
// CHECK: --- Appending ---
print("--- Appending ---")
var s = "⓪" // start non-empty
// To make this test independent of the memory allocator implementation,
// explicitly request initial capacity.
s.reserveCapacity(8)
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer0:[x0-9a-f]+]][0...2], capacity = 8)) = "⓪1"
s += "1"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer1:[x0-9a-f]+]][0...8], capacity = 8)) = "⓪1234567"
s += "234567"
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2:[x0-9a-f]+]][0...9], capacity = 16)) = "⓪12345678"
// CHECK-NOT: .native@[[buffer1]]
s += "8"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2]][0...16], capacity = 16)) = "⓪123456789012345"
s += "9012345"
print("\(repr(s))")
// -- expect a reallocation here
// Appending more than the next level of capacity only takes as much
// as required. I'm not sure whether this is a great idea, but the
// point is to prevent huge amounts of fragmentation when a long
// string is appended to a short one. The question, of course, is
// whether more appends are coming, in which case we should give it
// more capacity. It might be better to always grow to a multiple of
// the current capacity when the capacity is exceeded.
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer3:[x0-9a-f]+]][0...48], capacity = 48))
// CHECK-NOT: .native@[[buffer2]]
s += s + s
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4:[x0-9a-f]+]][0...49], capacity = 96))
// CHECK-NOT: .native@[[buffer3]]
s += "C"
print("\(repr(s))")
var s1 = s
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4]][0...49], capacity = 96))
print("\(repr(s1))")
/// The use of later buffer capacity by another string forces
/// reallocation
// CHECK-NEXT: String{{.*}} = {{.*}}X"
// CHECK-NOT: .native@[[buffer4]]
s1 += "X"
print("\(repr(s1))")
/// Appending to an empty string re-uses the RHS
// CHECK-NEXT: .native@[[buffer4]]
var s2 = String()
s2 += s
print("\(repr(s2))")
| apache-2.0 | bace248148b572920948a9664412aa6c | 28.389313 | 108 | 0.633247 | 3.293413 | false | false | false | false |
google-pay/flutter-plugin | pay_ios/ios/Classes/ApplePayButtonView.swift | 1 | 8174 | /**
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 Flutter
import UIKit
import PassKit
/// A factory class that creates the `FlutterPlatformView` that needs to render
/// and displayed on the Flutter end.
///
/// The constructor takes a messenger to communicate both ends and respond to
/// user interaction.
/// Example usage:
/// ```
/// let messenger = registrar.messenger()
/// let buttonFactory = ApplePayButtonViewFactory(messenger: messenger)
/// ```
class ApplePayButtonViewFactory: NSObject, FlutterPlatformViewFactory {
/// Holds the object needed to connect both the Flutter and native ends.
private var messenger: FlutterBinaryMessenger
/// Instantiates the class with the associated messenger.
///
/// - parameter messenger: An object to help the Flutter and native ends communicate.
init(messenger: FlutterBinaryMessenger) {
self.messenger = messenger
super.init()
}
/// Create a `FlutterPlatformView`.
///
/// Implemented by iOS code that expose a `UIView` for embedding in a Flutter app.
/// The implementation of this method should create a new `UIView` and return it.
///
/// - parameter frame: The rectangle for the newly created `UIView` measured in points.
/// - parameter viewId: A unique identifier for this `UIView`.
/// - parameter args: Parameters for creating the `UIView` sent from the Dart side of the Flutter app.
/// If `createArgsCodec` is not implemented, or if no creation arguments were sent from the Dart
/// code, this will be null. Otherwise this will be the value sent from the Dart code as decoded by
/// `createArgsCodec`.
func create(
withFrame frame: CGRect,
viewIdentifier viewId: Int64,
arguments args: Any?
) -> FlutterPlatformView {
return ApplePayButtonView(
frame: frame,
viewIdentifier: viewId,
arguments: args,
binaryMessenger: messenger)
}
/// Returns the `FlutterMessageCodec` for decoding the args parameter of `createWithFrame`.
///
/// Only needs to be implemented if `createWithFrame` needs an arguments parameter.
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}
/// A class to draw Apple Pay's `PKPaymentButton` natively.
///
/// This class constructs and draws a `PKPaymentButton` to send that back to the
/// Flutter end. At the moment, the assets are not available to use by Flutter, and hence,
/// it needs to be drawn natively.
class ApplePayButtonView: NSObject, FlutterPlatformView {
/// The name of the channel to use by the button to connect the native and Flutter ends
static let buttonMethodChannelName = "plugins.flutter.io/pay/apple_pay_button"
/// Holds the actual view with the contents to be send back to Flutter.
private var _view: UIView
/// The channel used to communicate with Flutter's end to exchange user interaction information.
private let channel: FlutterMethodChannel
/// Function to inform the Flutter channel about the tap event
@objc func handleApplePayButtonTapped() {
channel.invokeMethod("onPressed", arguments: nil)
}
/// Creates a `PKPaymentButton` based on the parameters received.
///
/// This constructor also initializes the objects necessary to communicate to and from the Flutter end.
///
/// - parameter frame: The bounds of the view.
/// - parameter viewIdentifier: The identifier for this view.
/// - parameter args: Additional arguments.
/// - parameter binaryMessenger: The messenger received from the platform view factory.
init(
frame: CGRect,
viewIdentifier viewId: Int64,
arguments args: Any?,
binaryMessenger messenger: FlutterBinaryMessenger
) {
_view = UIView()
let arguments = args as! Dictionary<String, AnyObject>
let buttonType = arguments["type"] as! String
let buttonStyle = arguments["style"] as! String
// Instantiate the channel to talk to the Flutter end.
channel = FlutterMethodChannel(name: "\(ApplePayButtonView.buttonMethodChannelName)/\(viewId)",
binaryMessenger: messenger)
super.init()
channel.setMethodCallHandler(handleFlutterCall)
createApplePayView(type: buttonType, style: buttonStyle)
}
/// No-op handler that resonds to calls received from Flutter.
///
/// - parameter call: The call received from Flutter.
/// - parameter result: The callback to respond back.
public func handleFlutterCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
default:
result(FlutterMethodNotImplemented)
}
}
func view() -> UIView {
return _view
}
/// Creates the actual `PKPaymentButton` with the defined styles and constraints.
func createApplePayView(type buttonTypeString: String, style buttonStyleString: String){
// Create the PK objects
let paymentButtonType = PKPaymentButtonType.fromString(buttonTypeString) ?? .plain
let paymentButtonStyle = PKPaymentButtonStyle.fromString(buttonStyleString) ?? .black
let applePayButton = PKPaymentButton(paymentButtonType: paymentButtonType, paymentButtonStyle: paymentButtonStyle)
// Configure the button
applePayButton.translatesAutoresizingMaskIntoConstraints = false
applePayButton.addTarget(self, action: #selector(handleApplePayButtonTapped), for: .touchUpInside)
_view.addSubview(applePayButton)
// Enable constraints
applePayButton.topAnchor.constraint(equalTo: _view.topAnchor).isActive = true
applePayButton.bottomAnchor.constraint(equalTo: _view.bottomAnchor).isActive = true
applePayButton.leftAnchor.constraint(equalTo: _view.leftAnchor).isActive = true
applePayButton.rightAnchor.constraint(equalTo: _view.rightAnchor).isActive = true
}
}
/// A set of utility methods associated to `PKPaymentButtonType`.
extension PKPaymentButtonType {
/// Creates a `PKPaymentButtonType` object from a network in string format.
public static func fromString(_ buttonType: String) -> PKPaymentButtonType? {
switch buttonType {
case "buy":
return .buy
case "setUp":
return .setUp
case "inStore":
return .inStore
case "donate":
return .donate
case "checkout":
guard #available(iOS 12.0, *) else { return nil }
return .checkout
case "book":
guard #available(iOS 12.0, *) else { return nil }
return .book
case "subscribe":
guard #available(iOS 12.0, *) else { return nil }
return .subscribe
default:
guard #available(iOS 14.0, *) else { return .plain }
switch buttonType {
case "reload":
return .reload
case "addMoney":
return .addMoney
case "topUp":
return .topUp
case "order":
return .order
case "rent":
return .rent
case "support":
return .support
case "contribute":
return .contribute
case "tip":
return .tip
default:
return nil
}
}
}
}
/// A set of utility methods associated to `PKPaymentButtonStyle`.
extension PKPaymentButtonStyle {
/// Creates a `PKPaymentButtonStyle` object from a network in string format.
public static func fromString(_ buttonStyle: String) -> PKPaymentButtonStyle? {
switch buttonStyle {
case "white":
return .white
case "whiteOutline":
return .whiteOutline
case "black":
return .black
case "automatic":
guard #available(iOS 14.0, *) else { return nil }
return .automatic
default:
return nil
}
}
}
| apache-2.0 | 2905a3f6ff6325a4801f2a39b05a3633 | 34.694323 | 118 | 0.70186 | 4.686927 | false | false | false | false |
danielsaidi/iExtra | iExtra/UI/Gestures/UIView+RepeatingAction.swift | 1 | 1090 | //
// UIView+RepeatingAction.swift
// iExtra
//
// Created by Daniel Saidi on 2019-05-30.
// Copyright © 2019 Daniel Saidi. All rights reserved.
//
// Reference: https://medium.com/@sdrzn/adding-gesture-recognizers-with-closures-instead-of-selectors-9fb3e09a8f0b
//
/*
This extension applies repeating gesture recognizers, using
action blocks instead of a target and a selector.
*/
import UIKit
public extension UIView {
typealias RepeatingAction = (() -> Void)
func addRepeatingAction(
initialDelay: TimeInterval = 0.8,
repeatInterval: TimeInterval = 0.1,
action: @escaping RepeatingAction) {
isUserInteractionEnabled = true
let recognizer = RepeatingGestureRecognizer(
initialDelay: initialDelay,
repeatInterval: repeatInterval,
action: action)
addGestureRecognizer(recognizer)
}
func removeRepeatingAction() {
gestureRecognizers?
.filter { $0 is RepeatingGestureRecognizer }
.forEach { removeGestureRecognizer($0) }
}
}
| mit | 82da95940c1662c13aeb5dbddc8a5575 | 25.560976 | 115 | 0.66483 | 4.653846 | false | false | false | false |
spronin/hse-swift-course | HSEToday/TodayViewController.swift | 1 | 1977 | //
// TodayViewController.swift
// HSEToday
//
// Created by Sergey Pronin on 4/21/15.
// Copyright (c) 2015 Sergey Pronin. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var tableFlights: UITableView!
let flights = Flight.allFlights()
override func viewDidLoad() {
super.viewDidLoad()
self.preferredContentSize = CGSize(width: 320,
height: 100)
tableFlights.delegate = self
tableFlights.dataSource = self
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
completionHandler(NCUpdateResult.NewData)
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return defaultMarginInsets
}
}
extension TodayViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return flights.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FlightCell") as! UITableViewCell
let label = cell.viewWithTag(1) as! UILabel
let flight = flights[indexPath.row]
label.text = "\(flight.airline.code) \(flight.number)"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let flight = flights[indexPath.row]
let url = NSURL(string: "hseproject://flight?number=\(flight.number)&airline=\(flight.airline.code)")!
self.extensionContext!.openURL(url,
completionHandler: nil)
}
}
| mit | f731841a9d6972e698f4b8da3ca96ee7 | 26.84507 | 110 | 0.647951 | 5.569014 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Login/Controller/GYZLoginVC.swift | 1 | 10642 | //
// GYZLoginVC.swift
// baking
// 登录 控制器
// Created by gouyz on 2016/12/1.
// Copyright © 2016年 gouyz. All rights reserved.
//
import UIKit
import SwiftyJSON
import MBProgressHUD
class GYZLoginVC: GYZBaseVC {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = kWhiteColor
self.title = "登 录"
setupUI()
// requestVersion()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 创建UI
fileprivate func setupUI(){
view.addSubview(phoneInputView)
view.addSubview(lineView)
view.addSubview(pwdInputView)
view.addSubview(lineView1)
view.addSubview(loginBtn)
view.addSubview(registerBtn)
view.addSubview(forgetPwdBtn)
phoneInputView.snp.makeConstraints { (make) in
make.top.equalTo(view).offset(30)
make.left.right.equalTo(view)
make.height.equalTo(kTitleHeight)
}
lineView.snp.makeConstraints { (make) in
make.left.right.equalTo(view)
make.top.equalTo(phoneInputView.snp.bottom)
make.height.equalTo(klineWidth)
}
pwdInputView.snp.makeConstraints { (make) in
make.top.equalTo(lineView.snp.bottom)
make.left.right.equalTo(phoneInputView)
make.height.equalTo(phoneInputView)
}
lineView1.snp.makeConstraints { (make) in
make.left.right.equalTo(lineView)
make.top.equalTo(pwdInputView.snp.bottom)
make.height.equalTo(lineView)
}
loginBtn.snp.makeConstraints { (make) in
make.top.equalTo(lineView1.snp.bottom).offset(30)
make.left.equalTo(view).offset(kStateHeight)
make.right.equalTo(view).offset(-kStateHeight)
make.height.equalTo(kUIButtonHeight)
}
registerBtn.snp.makeConstraints { (make) in
make.top.equalTo(loginBtn.snp.bottom).offset(kStateHeight)
make.left.right.equalTo(loginBtn)
make.height.equalTo(loginBtn)
}
forgetPwdBtn.snp.makeConstraints { (make) in
make.top.equalTo(registerBtn.snp.bottom).offset(kMargin)
make.right.equalTo(pwdInputView).offset(-kStateHeight)
make.size.equalTo(CGSize(width:70,height:kStateHeight))
}
registerBtn.set(image: UIImage.init(named: "icon_register_next"), title: "立即注册", titlePosition: .left, additionalSpacing: 5, state: .normal)
}
/// 手机号
fileprivate lazy var phoneInputView : GYZLoginInputView = GYZLoginInputView(iconName: "icon_login_phone", placeHolder: "请输入手机号码", isPhone: true)
/// 分割线
fileprivate lazy var lineView : UIView = {
let line = UIView()
line.backgroundColor = kGrayLineColor
return line
}()
/// 密码
fileprivate lazy var pwdInputView : GYZLoginInputView = GYZLoginInputView(iconName: "icon_login_pwd", placeHolder: "请输入密码", isPhone: false)
/// 分割线2
fileprivate lazy var lineView1 : UIView = {
let line = UIView()
line.backgroundColor = kGrayLineColor
return line
}()
/// 忘记密码按钮
fileprivate lazy var forgetPwdBtn : UIButton = {
let btn = UIButton.init(type: .custom)
btn.setTitle("忘记密码?", for: .normal)
btn.setTitleColor(kYellowFontColor, for: .normal)
btn.titleLabel?.font = k15Font
btn.titleLabel?.textAlignment = .right
btn.addTarget(self, action: #selector(clickedForgetPwdBtn(btn:)), for: .touchUpInside)
return btn
}()
/// 登录按钮
fileprivate lazy var loginBtn : UIButton = {
let btn = UIButton.init(type: .custom)
btn.backgroundColor = kBtnClickBGColor
btn.setTitle("登 录", for: .normal)
btn.setTitleColor(kWhiteColor, for: .normal)
btn.titleLabel?.font = k15Font
btn.addTarget(self, action: #selector(clickedLoginBtn(btn:)), for: .touchUpInside)
btn.cornerRadius = kCornerRadius
return btn
}()
/// 注册
fileprivate lazy var registerBtn : UIButton = {
let btn = UIButton.init(type: .custom)
btn.backgroundColor = kWhiteColor
btn.setTitleColor(kYellowFontColor, for: .normal)
btn.titleLabel?.font = k15Font
btn.addTarget(self, action: #selector(clickedRegisterBtn(btn:)), for: .touchUpInside)
btn.borderColor = kBtnClickBGColor
btn.borderWidth = klineWidth
btn.cornerRadius = kCornerRadius
return btn
}()
/// 注册
func clickedRegisterBtn(btn: UIButton){
let registerVC = GYZRegisterVC()
registerVC.isRegister = true
navigationController?.pushViewController(registerVC, animated: true)
}
/// 登录
func clickedLoginBtn(btn: UIButton) {
phoneInputView.textFiled.resignFirstResponder()
pwdInputView.textFiled.resignFirstResponder()
if !validPhoneNO() {
return
}
if pwdInputView.textFiled.text!.isEmpty {
MBProgressHUD.showAutoDismissHUD(message: "请输入密码")
return
}
requestLogin()
}
/// 忘记密码
func clickedForgetPwdBtn(btn: UIButton) {
let registerVC = GYZRegisterVC()
registerVC.isRegister = false
navigationController?.pushViewController(registerVC, animated: true)
}
/// 判断手机号是否有效
///
/// - Returns:
func validPhoneNO() -> Bool{
if phoneInputView.textFiled.text!.isEmpty {
MBProgressHUD.showAutoDismissHUD(message: "请输入手机号")
return false
}
if phoneInputView.textFiled.text!.isMobileNumber(){
return true
}else{
MBProgressHUD.showAutoDismissHUD(message: "请输入正确的手机号")
return false
}
}
/// 登录
func requestLogin(){
weak var weakSelf = self
createHUD(message: "登录中...")
GYZNetWork.requestNetwork("User/login", parameters: ["phone":phoneInputView.textFiled.text!,"password": pwdInputView.textFiled.text!.md5()], success: { (response) in
weakSelf?.hud?.hide(animated: true)
// GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
let info = data["info"]
userDefaults.set(true, forKey: kIsLoginTagKey)//是否登录标识
userDefaults.set(info["id"].stringValue, forKey: "userId")//用户ID
userDefaults.set(info["phone"].stringValue, forKey: "phone")//用户电话
userDefaults.set(info["username"].stringValue, forKey: "username")//用户名称
userDefaults.set(info["is_signing"].stringValue, forKey: "signing")//0没有签约 1签约
userDefaults.set(info["longitude"].stringValue, forKey: "longitude")//经度
userDefaults.set(info["latitude"].stringValue, forKey: "latitude")//纬度
userDefaults.set(info["head_img"].url, forKey: "headImg")//用户logo
userDefaults.set(info["balance"].stringValue, forKey: "balance")//余额
///极光推送设置别名
JPUSHService.setTags(nil, alias: info["phone"].stringValue, fetchCompletionHandle: { (code, tags, alias) in
NSLog("code:\(code)")
})
//KeyWindow.rootViewController = GYZMainTabBarVC()
_ = weakSelf?.navigationController?.popViewController(animated: true)
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
/// 请求服务器版本
func requestVersion(){
weak var weakSelf = self
GYZNetWork.requestNetwork("version/checkVersion.do",isToken:false, parameters: ["type":"A2"], method: .post, success:{ (response) in
// GYZLog(response)
if response["code"].intValue == kQuestSuccessTag{//请求成功
let data = response["data"]
let content = data["content"].stringValue
let version = data["code"].stringValue
weakSelf?.checkVersion(newVersion: version, content: content)
}
}, failture: { (error) in
GYZLog(error)
})
}
/// 检测APP更新
func checkVersion(newVersion: String,content: String){
let type: UpdateVersionType = GYZUpdateVersionTool.compareVersion(newVersion: newVersion)
switch type {
case .update:
updateVersion(version: newVersion, content: content)
case .updateNeed:
updateNeedVersion(version: newVersion, content: content)
default:
break
}
}
/**
* //不强制更新
* @param version 版本名称
* @param content 更新内容
*/
func updateVersion(version: String,content: String){
GYZAlertViewTools.alertViewTools.showAlert(title:"发现新版本\(version)", message: content, cancleTitle: "残忍拒绝", viewController: self, buttonTitles: "立即更新", alertActionBlock: { (index) in
if index == 0{//立即更新
GYZUpdateVersionTool.goAppStore()
}
})
}
/**
* 强制更新
* @param version 版本名称
* @param content 更新内容
*/
func updateNeedVersion(version: String,content: String){
weak var weakSelf = self
GYZAlertViewTools.alertViewTools.showAlert(title:"发现新版本\(version)", message: content, cancleTitle: nil, viewController: self, buttonTitles: "立即更新", alertActionBlock: { (index) in
if index == 0{//立即更新
GYZUpdateVersionTool.goAppStore()
///递归调用,重新设置弹出框
weakSelf?.updateNeedVersion(version: version, content: content)
}
})
}
}
| mit | 3d3d4ce23f40e64ccf6df5aa7ecda9c6 | 34.911972 | 189 | 0.592509 | 4.625397 | false | false | false | false |
yujinjcho/movie_recommendations | ios_ui/Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift | 38 | 2432 | import Foundation
internal class NotificationCollector {
private(set) var observedNotifications: [Notification]
private let notificationCenter: NotificationCenter
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
private var token: AnyObject?
#else
private var token: NSObjectProtocol?
#endif
required init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
self.observedNotifications = []
}
func startObserving() {
self.token = self.notificationCenter.addObserver(forName: nil, object: nil, queue: nil) { [weak self] n in
// linux-swift gets confused by .append(n)
self?.observedNotifications.append(n)
}
}
deinit {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
if let token = self.token {
self.notificationCenter.removeObserver(token)
}
#else
if let token = self.token as? AnyObject {
self.notificationCenter.removeObserver(token)
}
#endif
}
}
private let mainThread = pthread_self()
public func postNotifications<T>(
_ notificationsMatcher: T,
fromNotificationCenter center: NotificationCenter = .default)
-> Predicate<Any>
where T: Matcher, T.ValueType == [Notification]
{
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
let collectorNotificationsExpression = Expression(memoizedExpression: { _ in
return collector.observedNotifications
}, location: actualExpression.location, withoutCaching: true)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage)
if collector.observedNotifications.isEmpty {
failureMessage.actualValue = "no notifications"
} else {
failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>"
}
return match
}
}
| mit | ac9db71359022660fc07f6f254667cac | 34.764706 | 120 | 0.657072 | 5.241379 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Data/Implementations/Standard/BubbleChartDataSet.swift | 7 | 3209 | //
// BubbleChartDataSet.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class BubbleChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBubbleChartDataSet
{
// MARK: - Data functions and accessors
internal var _xMax = Double(0.0)
internal var _xMin = Double(0.0)
internal var _maxSize = CGFloat(0.0)
public var xMin: Double { return _xMin }
public var xMax: Double { return _xMax }
public var maxSize: CGFloat { return _maxSize }
public override func calcMinMax(start start: Int, end: Int)
{
let yValCount = self.entryCount
if yValCount == 0
{
return
}
let entries = yVals as! [BubbleChartDataEntry]
// need chart width to guess this properly
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = end
_yMin = yMin(entries[start])
_yMax = yMax(entries[start])
for i in start ... endValue
{
let entry = entries[i]
let ymin = yMin(entry)
let ymax = yMax(entry)
if (ymin < _yMin)
{
_yMin = ymin
}
if (ymax > _yMax)
{
_yMax = ymax
}
let xmin = xMin(entry)
let xmax = xMax(entry)
if (xmin < _xMin)
{
_xMin = xmin
}
if (xmax > _xMax)
{
_xMax = xmax
}
let size = largestSize(entry)
if (size > _maxSize)
{
_maxSize = size
}
}
}
private func yMin(entry: BubbleChartDataEntry) -> Double
{
return entry.value
}
private func yMax(entry: BubbleChartDataEntry) -> Double
{
return entry.value
}
private func xMin(entry: BubbleChartDataEntry) -> Double
{
return Double(entry.xIndex)
}
private func xMax(entry: BubbleChartDataEntry) -> Double
{
return Double(entry.xIndex)
}
private func largestSize(entry: BubbleChartDataEntry) -> CGFloat
{
return entry.size
}
// MARK: - Styling functions and accessors
/// Sets/gets the width of the circle that surrounds the bubble when highlighted
public var highlightCircleWidth: CGFloat = 2.5
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BubbleChartDataSet
copy._xMin = _xMin
copy._xMax = _xMax
copy._maxSize = _maxSize
copy.highlightCircleWidth = highlightCircleWidth
return copy
}
}
| apache-2.0 | f5102e7475274ad0b8c71635349b53d0 | 22.253623 | 92 | 0.511374 | 5.045597 | false | false | false | false |
See-Ku/SK4Toolkit | SK4Toolkit/gui/SK4ActionSheet.swift | 1 | 3147 | //
// SK4ActionSheet.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/24.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import UIKit
/// ActionSheetを表示するためのクラス
public class SK4ActionSheet: SK4AlertController {
// /////////////////////////////////////////////////////////////
// MARK: - プロパティ&初期化
/// popover表示で使うsourceItem
public var sourceItem: AnyObject?
/*
/// popover表示で使うsourceView
public var sourceView: UIView?
/// popover表示で使うsourceRect
public var sourceRect = CGRect()
/// popover表示で使うbarButtonItem
public var barButtonItem: UIBarButtonItem?
/// popover表示で使うpermittedArrowDirections
public var permittedArrowDirections = UIPopoverArrowDirection.Any
*/
/// 初期化
override public init() {
super.init()
style = .ActionSheet
}
/// 初期化
public convenience init(item: AnyObject, title: String? = nil, message: String? = nil) {
self.init()
self.title = title
self.message = message
setSourceItem(item)
}
// /////////////////////////////////////////////////////////////
// MARK: - 表示する位置を指定
/// ActionSheetを表示する位置を指定
public func setSourceItem(item: AnyObject) {
sourceItem = item
/*
// UIBarButtonItemか?
if let bar = item as? UIBarButtonItem {
barButtonItem = bar
return
}
// UIViewか?
if let view = item as? UIView {
setSourceView(view)
return
}
*/
}
/// ActionSheetを表示する位置を指定 ※矢印の向きは自動で判定
@available(*, deprecated=2.8.1, message="use UIPopoverPresentationController.sk4SetSourceView instead")
public func setSourceView(view: UIView) {
/*
sourceView = view
sourceRect.size = CGSize()
sourceRect.origin.x = view.bounds.midX
sourceRect.origin.y = view.bounds.midY
guard let sv = view.superview else { return }
let pos = view.center
let base = sv.bounds
if pos.y < base.height / 3 {
sourceRect.origin.y = view.bounds.maxY
permittedArrowDirections = .Up
} else if pos.y > (base.height * 2) / 3 {
sourceRect.origin.y = 0
permittedArrowDirections = .Down
} else if pos.x < base.width / 3 {
sourceRect.origin.x = view.bounds.maxX
permittedArrowDirections = .Left
} else if pos.x > (base.width * 2) / 3 {
sourceRect.origin.x = 0
permittedArrowDirections = .Right
} else {
sourceRect.origin.y = view.bounds.maxY
permittedArrowDirections = .Up
}
*/
}
// /////////////////////////////////////////////////////////////
// MARK: - その他
/// UIAlertControllerを生成
override public func getAlertController() -> UIAlertController {
let alert = super.getAlertController()
if let item = sourceItem {
alert.popoverPresentationController?.sk4SetSourceItem(item)
}
/*
alert.popoverPresentationController?.sourceView = sourceView
alert.popoverPresentationController?.sourceRect = sourceRect
alert.popoverPresentationController?.barButtonItem = barButtonItem
alert.popoverPresentationController?.permittedArrowDirections = permittedArrowDirections
*/
return alert
}
}
// eof
| mit | 11dd00c5a34f05c78b70a61198a183b0 | 21.280303 | 104 | 0.66678 | 3.736976 | false | false | false | false |
vector-im/vector-ios | RiotSwiftUI/Modules/Room/TimelinePoll/TimelinePollModels.swift | 1 | 2982 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import SwiftUI
typealias TimelinePollViewModelCallback = ((TimelinePollViewModelResult) -> Void)
enum TimelinePollViewAction {
case selectAnswerOptionWithIdentifier(String)
}
enum TimelinePollViewModelResult {
case selectedAnswerOptionsWithIdentifiers([String])
}
enum TimelinePollType {
case disclosed
case undisclosed
}
struct TimelinePollAnswerOption: Identifiable {
var id: String
var text: String
var count: UInt
var winner: Bool
var selected: Bool
init(id: String, text: String, count: UInt, winner: Bool, selected: Bool) {
self.id = id
self.text = text
self.count = count
self.winner = winner
self.selected = selected
}
}
extension MutableCollection where Element == TimelinePollAnswerOption {
mutating func updateEach(_ update: (inout Element) -> Void) {
for index in indices {
update(&self[index])
}
}
}
struct TimelinePollDetails {
var question: String
var answerOptions: [TimelinePollAnswerOption]
var closed: Bool
var totalAnswerCount: UInt
var type: TimelinePollType
var maxAllowedSelections: UInt
var hasBeenEdited: Bool = true
init(question: String, answerOptions: [TimelinePollAnswerOption],
closed: Bool,
totalAnswerCount: UInt,
type: TimelinePollType,
maxAllowedSelections: UInt,
hasBeenEdited: Bool) {
self.question = question
self.answerOptions = answerOptions
self.closed = closed
self.totalAnswerCount = totalAnswerCount
self.type = type
self.maxAllowedSelections = maxAllowedSelections
self.hasBeenEdited = hasBeenEdited
}
var hasCurrentUserVoted: Bool {
answerOptions.filter { $0.selected == true}.count > 0
}
var shouldDiscloseResults: Bool {
if closed {
return totalAnswerCount > 0
} else {
return type == .disclosed && totalAnswerCount > 0 && hasCurrentUserVoted
}
}
}
struct TimelinePollViewState: BindableState {
var poll: TimelinePollDetails
var bindings: TimelinePollViewStateBindings
}
struct TimelinePollViewStateBindings {
var alertInfo: AlertInfo<TimelinePollAlertType>?
}
enum TimelinePollAlertType {
case failedClosingPoll
case failedSubmittingAnswer
}
| apache-2.0 | e120d834a14111d45b469a017662b109 | 26.611111 | 84 | 0.691482 | 4.57362 | false | false | false | false |
lanjing99/RxSwiftDemo | 11-time-based-operators/final/RxSwiftPlayground/RxSwift.playground/Pages/replay.xcplaygroundpage/Contents.swift | 2 | 2485 | //: Please build the scheme 'RxSwiftPlayground' first
import UIKit
import RxSwift
import RxCocoa
let elementsPerSecond = 1
let maxElements = 5
let replayedElements = 1
let replayDelay: TimeInterval = 3
let sourceObservable = Observable<Int>
.interval(RxTimeInterval(elementsPerSecond), scheduler: MainScheduler.instance)
.replay(replayedElements)
let sourceTimeline = TimelineView<Int>.make()
let replayedTimeline = TimelineView<Int>.make()
let stack = UIStackView.makeVertical([
UILabel.makeTitle("replay"),
UILabel.make("Emit \(elementsPerSecond) per second:"),
sourceTimeline,
UILabel.make("Replay \(replayedElements) after \(replayDelay) sec:"),
replayedTimeline])
_ = sourceObservable.subscribe(sourceTimeline)
DispatchQueue.main.asyncAfter(deadline: .now() + replayDelay) {
_ = sourceObservable.subscribe(replayedTimeline)
}
_ = sourceObservable.connect()
let hostView = setupHostView()
hostView.addSubview(stack)
hostView
// Support code -- DO NOT REMOVE
class TimelineView<E>: TimelineViewBase, ObserverType where E: CustomStringConvertible {
static func make() -> TimelineView<E> {
return TimelineView(width: 400, height: 100)
}
public func on(_ event: Event<E>) {
switch event {
case .next(let value):
add(.Next(String(describing: value)))
case .completed:
add(.Completed())
case .error(_):
add(.Error())
}
}
}
/*:
Copyright (c) 2014-2016 Razeware LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
| mit | 0c00167d886b81a64007d4d164ba80fd | 32.581081 | 88 | 0.75493 | 4.406028 | false | false | false | false |
oxozle/OXPatternLock | Source/OXPatternLock.swift | 1 | 5454 | //
// OXPatternLock.swift
// OXPatternLock
//
// Created by Dmitriy Azarov on 11/01/2017.
// Copyright © 2017 http://oxozle.com. All rights reserved.
// https://github.com/oxozle/OXPatternLock
//
//
import Foundation
import UIKit
/// OXPatternLock Delegate
public protocol OXPatternLockDelegate: class {
/// Occurs when user ended to track pattern lock
///
/// - Parameters:
/// - patterLock: instance of locker
/// - track: array of integers, which user tracked
func didPatternInput(patterLock: OXPatternLock, track: [Int])
}
/// UI Element represent pattern lock
@IBDesignable
open class OXPatternLock: UIControl {
public weak var delegate: OXPatternLockDelegate?
/// Default state image
@IBInspectable
public var dot: UIImage? {
didSet {
updateLayoutConfiguration()
}
}
/// Tracked state image
@IBInspectable
public var dotSelected: UIImage?{
didSet {
updateLayoutConfiguration()
}
}
/// Grid size
@IBInspectable
public var lockSize: Int = 3{
didSet {
updateLayoutConfiguration()
}
}
/// Color of track line
@IBInspectable
public var trackLineColor: UIColor = UIColor.white{
didSet {
updateLayoutConfiguration()
}
}
/// Thickness of track line
@IBInspectable
public var trackLineThickness: CGFloat = 5{
didSet {
updateLayoutConfiguration()
}
}
private var lockTrack = [Int]()
private var lockFrames = [CGRect]()
//MARK: Draw
open override func draw(_ rect: CGRect) {
self.backgroundColor = UIColor.clear
guard let ctx = UIGraphicsGetCurrentContext() else {return}
guard let dot = dot else {return}
guard let dotSelected = dotSelected else {return}
#if !TARGET_INTERFACE_BUILDER
// this code will run in the app itself
#else
prepareTrackForInterfaceBuilder()
#endif
if !lockTrack.isEmpty {
drawTrackPath(ctx: ctx)
}
for (index,dotRect) in lockFrames.enumerated() {
if lockTrack.contains(index) {
dotSelected.draw(in: dotRect)
} else {
dot.draw(in: dotRect)
}
}
}
private func drawTrackPath(ctx: CGContext) {
let path = UIBezierPath()
for i in 0..<lockTrack.count - 1 {
let index = lockTrack[i]
let indexTo = lockTrack[i+1]
let rect = lockFrames[index]
path.move(to: CGPoint(x: rect.midX, y: rect.midY))
let rectTo = lockFrames[indexTo]
path.addLine(to: CGPoint(x: rectTo.midX, y: rectTo.midY))
}
trackLineColor.set()
ctx.setLineWidth(trackLineThickness)
ctx.setLineCap(.round)
ctx.setLineJoin(.round)
ctx.addPath(path.cgPath)
ctx.strokePath()
}
//MARK: Layout
private func updateLayoutConfiguration() {
guard let dot = dot else {return}
guard let _ = dotSelected else {return}
let rect = self.frame
let spacing = (rect.width - (CGFloat(lockSize) * dot.size.width)) / CGFloat(lockSize + 1)
let iconSize = dot.size
lockFrames.removeAll()
for y in 0..<lockSize {
for x in 0..<lockSize {
let point = CGPoint(x: spacing + CGFloat(x) * (iconSize.width + spacing), y: spacing + CGFloat(y) * (iconSize.width + spacing))
let dotRect = CGRect(origin: point, size: iconSize)
lockFrames.append(dotRect)
}
}
}
//MARK: Tracking
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
lockTrack.removeAll()
let point = touch.location(in: self)
if hitTestInLockFrames(at: point) {
setNeedsDisplay()
}
return super.beginTracking(touch, with: event)
}
open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let point = touch.location(in: self)
if hitTestInLockFrames(at: point) {
setNeedsDisplay()
}
return super.continueTracking(touch, with: event)
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
if lockTrack.count >= 2 {
delegate?.didPatternInput(patterLock: self, track: lockTrack)
}
lockTrack.removeAll()
setNeedsDisplay()
super.endTracking(touch, with: event)
}
private func hitTestInLockFrames(at point: CGPoint) -> Bool {
for (index, rect) in lockFrames.enumerated() {
if rect.contains(point) {
if !lockTrack.contains(index) {
lockTrack.append(index)
}
return true
}
}
return false
}
//MARK: IBDesignable
private func prepareTrackForInterfaceBuilder() {
lockTrack.removeAll()
lockTrack.append(0)
lockTrack.append(1)
lockTrack.append(lockSize)
lockTrack.append(lockSize + 1)
lockTrack.append(lockSize * 2 + 1)
}
}
| mit | 0f3102133abb4165d822afa5eff94796 | 25.470874 | 143 | 0.562259 | 4.536606 | false | false | false | false |
xedin/swift | test/Serialization/autolinking.swift | 1 | 3576 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version none -emit-ir -lmagic %s -I %t > %t/out.txt
// RUN: %FileCheck %s < %t/out.txt
// RUN: %FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/out.txt
// RUN: %empty-directory(%t/someModule.framework/Modules/someModule.swiftmodule)
// RUN: mv %t/someModule.swiftmodule %t/someModule.framework/Modules/someModule.swiftmodule/%target-swiftmodule-name
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version none -emit-ir -lmagic %s -F %t > %t/framework.txt
// RUN: %FileCheck -check-prefix=FRAMEWORK %s < %t/framework.txt
// RUN: %FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/framework.txt
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load
// RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -lmagic %s -I %t > %t/force-load.txt
// RUN: %FileCheck %s < %t/force-load.txt
// RUN: %FileCheck -check-prefix FORCE-LOAD-CLIENT -check-prefix FORCE-LOAD-CLIENT-%target-object-format %s < %t/force-load.txt
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version none -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift | %FileCheck --check-prefix=NO-FORCE-LOAD %s
// RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load | %FileCheck --check-prefix=FORCE-LOAD %s
// RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -parse-stdlib -module-name someModule -module-link-name 0module %S/../Inputs/empty.swift -autolink-force-load | %FileCheck --check-prefix=FORCE-LOAD-HEX %s
// Linux uses a different autolinking mechanism, based on
// swift-autolink-extract. This file tests the Darwin mechanism.
// UNSUPPORTED: autolink-extract
import someModule
// CHECK: !llvm.linker.options = !{
// CHECK-DAG: !{{[0-9]+}} = !{!{{"-lmagic"|"/DEFAULTLIB:magic.lib"}}}
// CHECK-DAG: !{{[0-9]+}} = !{!{{"-lmodule"|"/DEFAULTLIB:module.lib"}}}
// FRAMEWORK: !llvm.linker.options = !{
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!{{"-lmagic"|"/DEFAULTLIB:magic.lib"}}}
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!{{"-lmodule"|"/DEFAULTLIB:module.lib"}}}
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-framework", !"someModule"}
// NO-FORCE-LOAD-NOT: FORCE_LOAD
// FORCE-LOAD: define{{( dllexport)?}} void @"_swift_FORCE_LOAD_$_module"() {
// FORCE-LOAD: ret void
// FORCE-LOAD: }
// FORCE-LOAD-HEX: define{{( dllexport)?}} void @"_swift_FORCE_LOAD_$306d6f64756c65"() {
// FORCE-LOAD-HEX: ret void
// FORCE-LOAD-HEX: }
// FORCE-LOAD-CLIENT: @"_swift_FORCE_LOAD_$_module_$_autolinking" = weak_odr hidden constant void ()* @"_swift_FORCE_LOAD_$_module"
// FORCE-LOAD-CLIENT: @llvm.used = appending global [{{[0-9]+}} x i8*] [
// FORCE-LOAD-CLIENT: i8* bitcast (void ()** @"_swift_FORCE_LOAD_$_module_$_autolinking" to i8*)
// FORCE-LOAD-CLIENT: ], section "llvm.metadata"
// FORCE-LOAD-CLIENT-MACHO: declare extern_weak {{(dllimport )?}}void @"_swift_FORCE_LOAD_$_module"()
// FORCE-LOAD-CLIENT-COFF: declare extern {{(dllimport )?}}void @"_swift_FORCE_LOAD_$_module"()
| apache-2.0 | cabb1b879fdadf2dc34ab6728a843596 | 69.117647 | 272 | 0.703859 | 3.286765 | false | false | false | false |
timelessg/TLStoryCamera | TLStoryCameraFramework/TLStoryCameraFramework/Class/Controllers/TLStoryViewController.swift | 1 | 13821 | //
// TLStoryCameraViewController.swift
// TLStoryCamera
//
// Created by GarryGuo on 2017/5/10.
// Copyright © 2017年 GarryGuo. All rights reserved.
//
import UIKit
public enum TLStoryType {
case video
case photo
}
public protocol TLStoryViewDelegate: NSObjectProtocol {
func storyViewRecording(running:Bool)
func storyViewDidPublish(type:TLStoryType, url:URL?)
func storyViewClose()
}
public class TLStoryViewController: UIViewController {
public weak var delegate:TLStoryViewDelegate?
fileprivate var containerView = UIView.init()
fileprivate var bottomImagePicker:TLStoryBottomImagePickerView?
fileprivate var captureView:TLStoryCapturePreviewView?
fileprivate var outputView:TLStoryOverlayOutputView?
fileprivate var editContainerView:TLStoryEditContainerView?
fileprivate var controlView:TLStoryOverlayControlView?
fileprivate var editView:TLStoryOverlayEditView?
fileprivate var textStickerView:TLStoryOverlayTextStickerView?
fileprivate var imageStickerView:TLStoryOverlayImagePicker?
fileprivate var blurCoverView = UIVisualEffectView.init(effect: UIBlurEffect.init(style: .light))
fileprivate var swipeUp:UISwipeGestureRecognizer?
fileprivate var swipeDown:UISwipeGestureRecognizer?
fileprivate var output = TLStoryOutput.init()
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
self.view.isUserInteractionEnabled = true
self.automaticallyAdjustsScrollViewInsets = false
bottomImagePicker = TLStoryBottomImagePickerView.init(frame: CGRect.init(x: 0, y: self.view.safeRect.height - 165, width: self.view.safeRect.width, height: 165))
bottomImagePicker?.delegate = self
self.view.addSubview(bottomImagePicker!)
view.addSubview(containerView)
containerView.frame = self.view.safeRect
captureView = TLStoryCapturePreviewView.init(frame: self.containerView.bounds)
containerView.addSubview(captureView!)
outputView = TLStoryOverlayOutputView.init(frame: self.containerView.bounds)
outputView!.isHidden = true
containerView.addSubview(outputView!)
editContainerView = TLStoryEditContainerView.init(frame: self.containerView.bounds)
editContainerView!.delegate = self
outputView!.addSubview(editContainerView!)
controlView = TLStoryOverlayControlView.init(frame: self.containerView.bounds)
controlView!.delegate = self
controlView!.isHidden = true
containerView.addSubview(controlView!)
editView = TLStoryOverlayEditView.init(frame: self.containerView.bounds)
editView!.delegate = self
editView!.isHidden = true
containerView.addSubview(editView!)
textStickerView = TLStoryOverlayTextStickerView.init(frame: self.containerView.bounds)
textStickerView!.delegate = self
textStickerView!.isHidden = true
containerView.addSubview(textStickerView!)
imageStickerView = TLStoryOverlayImagePicker.init(frame: self.containerView.bounds)
imageStickerView?.delegate = self
imageStickerView!.isHidden = true
containerView.addSubview(imageStickerView!)
containerView.addSubview(blurCoverView)
blurCoverView.isUserInteractionEnabled = true
blurCoverView.frame = containerView.bounds
swipeUp = UISwipeGestureRecognizer.init(target: self, action: #selector(swipeAction))
swipeUp!.direction = .up
self.controlView?.addGestureRecognizer(swipeUp!)
self.checkAuthorized()
}
public func resumeCamera(open:Bool) {
self.captureView!.cameraSwitch(open: open)
if open {
UIView.animate(withDuration: 0.25, animations: {
self.blurCoverView.alpha = 0
}, completion: { (x) in
if x {
self.blurCoverView.isHidden = true
}
})
self.controlView?.beginHintAnim()
}else {
self.blurCoverView.alpha = 1
self.blurCoverView.isHidden = false
}
}
@objc fileprivate func swipeAction(sender:UISwipeGestureRecognizer) {
if sender.direction == .up && self.containerView.y == self.view.safeRect.origin.y {
self.bottomImagePicker(hidden: false)
return
}
if sender.direction == .down {
self.bottomImagePicker(hidden: true)
return
}
}
fileprivate func bottomImagePicker(hidden:Bool) {
if !hidden {
blurCoverView.isHidden = false
blurCoverView.alpha = 0
UIView.animate(withDuration: 0.25, animations: {
self.blurCoverView.alpha = 1
self.containerView.y -= 165 + self.view.safeRect.origin.y
}) { (x) in
self.swipeDown = UISwipeGestureRecognizer.init(target: self, action: #selector(self.swipeAction))
if let swipeDown = self.swipeDown {
swipeDown.direction = .down
self.blurCoverView.addGestureRecognizer(swipeDown)
}
self.bottomImagePicker?.loadPhotos()
}
} else {
blurCoverView.alpha = 1
UIView.animate(withDuration: 0.25, animations: {
self.blurCoverView.alpha = 0
self.containerView.y = self.view.safeRect.origin.y
}, completion: { (x) in
self.blurCoverView.isHidden = true
self.blurCoverView.alpha = 1
if let swipeDown = self.swipeDown {
self.blurCoverView.removeGestureRecognizer(swipeDown)
}
})
}
self.delegate?.storyViewRecording(running: !hidden)
}
fileprivate func checkAuthorized() {
let cameraAuthorization = TLAuthorizedManager.checkAuthorization(with: .camera)
let micAuthorization = TLAuthorizedManager.checkAuthorization(with: .mic)
if cameraAuthorization && micAuthorization {
if cameraAuthorization {
self.cameraStart()
}
if micAuthorization {
captureView!.enableAudio()
}
controlView!.isHidden = false
}else {
let authorizedVC = TLStoryAuthorizationController()
authorizedVC.view.frame = self.view.bounds
authorizedVC.delegate = self
self.view.addSubview(authorizedVC.view)
self.addChildViewController(authorizedVC)
}
}
fileprivate func cameraStart() {
if UIDevice.isSimulator {
return
}
captureView!.initCamera()
captureView!.startCapture()
}
fileprivate func previewDispay<T>(input:T, type:TLStoryType) {
self.outputView!.isHidden = false
self.output.type = type
self.editView?.dispaly()
self.editView?.setAudioEnableBtn(hidden: type == .photo)
self.controlView?.dismiss()
self.captureView?.pauseCamera()
self.delegate?.storyViewRecording(running: true)
if type == .photo, let img = input as? UIImage {
self.output.image = img
self.outputView?.display(withPhoto: img)
}
if type == .video, let url = input as? URL {
self.output.url = url
self.outputView?.display(withVideo: url)
}
}
fileprivate func previewDismiss() {
self.outputView!.isHidden = true
self.editView?.dismiss()
self.outputView?.reset()
self.editContainerView?.reset()
self.textStickerView?.reset()
self.controlView?.display()
self.captureView?.resumeCamera()
self.output.reset()
self.delegate?.storyViewRecording(running: false)
}
override public var prefersStatusBarHidden: Bool {
return true
}
}
extension TLStoryViewController: TLStoryOverlayControlDelegate {
func storyOverlayCameraClose() {
self.delegate?.storyViewClose()
}
func storyOverlayCameraFocused(point: CGPoint) {
captureView?.focus(point: point)
}
internal func storyOverlayCameraRecordingStart() {
captureView!.configVideoRecording()
captureView!.configAudioRecording()
captureView!.startRecording()
}
internal func storyOverlayCameraSwitch() {
captureView!.rotateCamera()
}
internal func storyOverlayCameraZoom(distance: CGFloat) {
captureView!.camera(distance: distance)
}
internal func storyOverlayCameraRecordingFinish(type: TLStoryType) {
if type == .photo {
self.captureView?.capturePhoto(complete: { (image) in
if let img = image {
self.previewDispay(input: img, type: .photo)
}
})
}else {
self.captureView!.finishRecording(complete: { [weak self] (x) in
if let url = x {
self?.previewDispay(input: url, type: .video)
}
})
}
}
internal func storyOverlayCameraFlashChange() -> AVCaptureDevice.TorchMode {
return self.captureView!.flashStatusChange()
}
}
extension TLStoryViewController: TLStoryOverlayEditViewDelegate {
internal func storyOverlayEditPublish() {
guard let container = self.editContainerView?.getScreenshot() else {
return
}
self.editView?.dismiss()
self.output.output(filterNamed: self.outputView!.currentFilterNamed, container: container, callback: { [weak self] (url, type) in
self?.editView?.dispaly()
self?.delegate?.storyViewDidPublish(type: type, url: url)
self?.previewDismiss()
})
}
internal func storyOverlayEditSave() {
let block:(() -> Void) = { () in
guard let container = self.editContainerView?.getScreenshot() else {
return
}
self.editView?.dismiss()
self.output.saveToAlbum(filterNamed: self.outputView!.currentFilterNamed, container: container, callback: { [weak self] (x) in
self?.editView?.dispaly()
})
}
guard TLAuthorizedManager.checkAuthorization(with: .album) else {
TLAuthorizedManager.requestAuthorization(with: .album, callback: { (type, success) in
if success {
block()
}
})
return
}
block()
}
internal func storyOverlayEditTextEditerDisplay() {
textStickerView?.show(sticker: nil)
}
internal func storyOverlayEditStickerPickerDisplay() {
imageStickerView?.display()
}
internal func storyOverlayEditDoodleEditable() {
self.editContainerView?.benginDrawing()
}
internal func storyOverlayEditClose() {
self.previewDismiss()
}
internal func storyOverlayEditAudio(enable: Bool) {
self.output.audioEnable = enable
self.outputView?.playerAudio(enable: enable)
}
}
extension TLStoryViewController: TLStoryOverlayTextStickerViewDelegate {
internal func textEditerDidCompleteEdited(sticker: TLStoryTextSticker?) {
if let s = sticker {
self.editContainerView?.add(textSticker: s)
}
editView?.dispaly()
}
}
extension TLStoryViewController: TLStoryOverlayImagePickerDelegate {
internal func storyOverlayImagePickerDismiss() {
editView?.dispaly()
}
internal func storyOverlayImagePickerDidSelected(img: UIImage) {
self.editContainerView?.add(img: img)
}
}
extension TLStoryViewController: TLStoryEditContainerViewDelegate {
internal func storyEditSwpieFilter(direction: UISwipeGestureRecognizerDirection) {
self.outputView?.switchFilter(direction: direction);
}
internal func storyEditContainerTap() {
self.editView?.dismiss()
self.textStickerView?.show(sticker: nil)
}
internal func storyEditContainerSwipeUp() {
self.editView?.dismiss()
self.imageStickerView?.display()
}
internal func storyEditContainerSticker(editing: Bool) {
if editing {
self.editView?.dismiss()
}else {
self.editView?.dispaly()
}
}
internal func storyEditContainerEndDrawing() {
self.editView?.dispaly()
}
internal func storyEditContainerTextStickerBeEditing(sticker: TLStoryTextSticker) {
self.editView?.dismiss()
self.textStickerView?.show(sticker: sticker)
}
}
extension TLStoryViewController: TLStoryBottomImagePickerViewDelegate {
func photoLibraryPickerDidSelectPhoto(image: UIImage) {
self.bottomImagePicker(hidden: true)
self.previewDispay(input: image, type: .photo)
}
func photoLibraryPickerDidSelectVideo(url: URL) {
self.bottomImagePicker(hidden: true)
self.previewDispay(input: url, type: .video)
}
}
extension TLStoryViewController: TLStoryAuthorizedDelegate {
internal func requestMicAuthorizeSuccess() {
captureView!.enableAudio()
}
internal func requestCameraAuthorizeSuccess() {
self.cameraStart()
}
internal func requestAllAuthorizeSuccess() {
self.controlView!.isHidden = false
}
}
| mit | 35da22f2c3519443d6802a9541ff6636 | 32.216346 | 169 | 0.629469 | 5.07455 | false | false | false | false |
TimurBK/SwiftSampleProject | Pods/Kingfisher/Sources/KingfisherManager.swift | 5 | 9404 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// 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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> ())
public typealias CompletionHandler = ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ())
/// RetrieveImageTask represents a task of image retrieving process.
/// It contains an async task of getting image from disk and from network.
public class RetrieveImageTask {
public static let empty = RetrieveImageTask()
// If task is canceled before the download task started (which means the `downloadTask` is nil),
// the download task should not begin.
var cancelledBeforeDownloadStarting: Bool = false
/// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task.
public var diskRetrieveTask: RetrieveImageDiskTask?
/// The network retrieve task in this image task.
public var downloadTask: RetrieveImageDownloadTask?
/**
Cancel current task. If this task does not begin or already done, do nothing.
*/
public func cancel() {
// From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime.
// It fixed in Xcode 7.1.
// See https://github.com/onevcat/Kingfisher/issues/99 for more.
if let diskRetrieveTask = diskRetrieveTask {
diskRetrieveTask.cancel()
}
if let downloadTask = downloadTask {
downloadTask.cancel()
} else {
cancelledBeforeDownloadStarting = true
}
}
}
/// Error domain of Kingfisher
public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
/// Shared manager used by the extensions across Kingfisher.
public static let shared = KingfisherManager()
/// Cache used by this manager
public var cache: ImageCache
/// Downloader used by this manager
public var downloader: ImageDownloader
convenience init() {
self.init(downloader: .default, cache: .default)
}
init(downloader: ImageDownloader, cache: ImageCache) {
self.downloader = downloader
self.cache = cache
}
/**
Get an image with resource.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
- parameter completionHandler: Called when the whole retrieving process finished.
- returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
@discardableResult
public func retrieveImage(with resource: Resource,
options: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let task = RetrieveImageTask()
if let options = options, options.forceRefresh {
_ = downloadAndCacheImage(
with: resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: options)
} else {
tryToRetrieveImageFromCache(
forKey: resource.cacheKey,
with: resource.downloadURL,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: options)
}
return task
}
@discardableResult
func downloadAndCacheImage(with url: URL,
forKey key: String,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask?
{
let options = options ?? KingfisherEmptyOptionsInfo
let downloader = options.downloader
return downloader.downloadImage(with: url, retrieveImageTask: retrieveImageTask, options: options,
progressBlock: { receivedSize, totalSize in
progressBlock?(receivedSize, totalSize)
},
completionHandler: { image, error, imageURL, originalData in
let targetCache = options.targetCache
if let error = error, error.code == KingfisherError.notModified.rawValue {
// Not modified. Try to find the image from cache.
// (The image should be in cache. It should be guaranteed by the framework users.)
targetCache.retrieveImage(forKey: key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
completionHandler?(cacheImage, nil, cacheType, url)
})
return
}
if let image = image, let originalData = originalData {
targetCache.store(image,
original: originalData,
forKey: key,
processorIdentifier:options.processor.identifier,
cacheSerializer: options.cacheSerializer,
toDisk: !options.cacheMemoryOnly,
completionHandler: nil)
}
completionHandler?(image, error, .none, url)
})
}
func tryToRetrieveImageFromCache(forKey key: String,
with url: URL,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: KingfisherOptionsInfo?)
{
let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in
// Break retain cycle created inside diskTask closure below
retrieveImageTask.diskRetrieveTask = nil
completionHandler?(image, error, cacheType, imageURL)
}
let targetCache = options?.targetCache ?? cache
let diskTask = targetCache.retrieveImage(forKey: key, options: options,
completionHandler: { image, cacheType in
if image != nil {
diskTaskCompletionHandler(image, nil, cacheType, url)
} else if let options = options, options.onlyFromCache {
let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notCached.rawValue, userInfo: nil)
diskTaskCompletionHandler(nil, error, .none, url)
} else {
self.downloadAndCacheImage(
with: url,
forKey: key,
retrieveImageTask: retrieveImageTask,
progressBlock: progressBlock,
completionHandler: diskTaskCompletionHandler,
options: options)
}
}
)
retrieveImageTask.diskRetrieveTask = diskTask
}
}
| mit | abc9acb20b65f8feff3516cec607924f | 43.150235 | 140 | 0.620268 | 5.79064 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Components/GooglePlaceAPI/WebonoiseAssignment/WebonoiseAssignment/APIAutoComplete.swift | 3 | 3364 | //
// APIAutoComplete.swift
// WebonoiseAssignment
//
// Created by Shridhar Mali on 4/15/17.
// Copyright © 2017 Shridhar Mali. All rights reserved.
//
import UIKit
import Gloss
//Object Mapping of APIAutoComplete
public struct APIAutoCompletePlaces: Decodable {
let predictions: [Predictions]?
public init?(json: JSON) {
self.predictions = "predictions" <~~ json
}
}
public struct Predictions: Decodable {
let description: String?
let placeId: String?
let structuredFormatting: StructuredFormatting?
public init?(json: JSON) {
self.description = "description" <~~ json
self.placeId = "place_id" <~~ json
self.structuredFormatting = "structured_formatting" <~~ json
}
}
public struct StructuredFormatting: Decodable {
let secondaryText: String?
public init?(json: JSON) {
self.secondaryText = "secondary_text" <~~ json
}
}
//MARK:- APIAutoCompleteResponse
public enum APIAutoCompleteResponse {
case error(APIError)
case success(APIAutoCompletePlaces)
}
//MARK:- Server Extention APIAutoComplete
extension Server {
public struct APIAutoComplete {
static func getPlacesHandler(_ places: [String: AnyObject]) -> APIAutoCompletePlaces? {
guard let obj = APIAutoCompletePlaces(json: places) else {
return nil
}
return obj
}
//Get place in autocomplete formate using search string
public static func invokeAPIAutoComplete(searchText: String, _ handler: @escaping(APIAutoCompleteResponse) -> Void) -> URLSessionDataTask {
// Google autocomplete API for getting search places
let apiAutoComplete = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=\(searchText)&types=geocode&key=\(Server.URLs.apiKey)"
let escapedString = apiAutoComplete.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
let rqst = SRKRequestManager.generateRequest(escapedString!,
dictionaryOfHeaders: nil,
postData: nil,
requestType: .Get,
timeOut: 60)
return SRKRequestManager.invokeRequestForJSON(rqst) { (response: JSONResponse) in
SRKUtility.hideProgressHUD()
let apiAutoCompleteResponse = Server.handleResponse(response)
switch apiAutoCompleteResponse {
case let .successWithArray(arrayOfRawPlaces):
print(arrayOfRawPlaces)
handler(APIAutoCompleteResponse.error(APIError.invalidResponseReceived))
case let .successWithDictionary(rawPlaces):
if let businesscard = Server.APIAutoComplete.getPlacesHandler(rawPlaces as [String : AnyObject]) {
handler(APIAutoCompleteResponse.success(businesscard))
} else {
handler(APIAutoCompleteResponse.error(APIError.invalidResponseReceived))
}
case let .error(error):
handler(APIAutoCompleteResponse.error(error))
}
}
}
}
}
| apache-2.0 | 7a3f4633ed7768e8d011d3c48ffefa7b | 39.518072 | 156 | 0.612251 | 5.363636 | false | false | false | false |
kak-ios-codepath/everest | Everest/Everest/Models/Action.swift | 1 | 777 | //
// Action.swift
// Everest
//
// Created by user on 10/14/17.
// Copyright © 2017 Kavita Gaitonde. All rights reserved.
//
import Foundation
import SwiftyJSON
class Action: NSObject {
var id: String //same id from acts
var createdAt: String
var status: String
var momentIds: [String]?
init(id: String, createdAt: String, status: String) {
self.id = id
self.createdAt = createdAt
self.status = status
}
init(action: JSON) {
self.id = action["id"].string!
self.createdAt = action["createdAt"].string!
self.status = action["status"].string!
if let momentIds = action["momentIds"].dictionary {
self.momentIds = Array(momentIds.keys)
}
}
}
| apache-2.0 | c280dff9ca3bf56604e904293403468a | 22.515152 | 59 | 0.594072 | 3.919192 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.