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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jaropawlak/Signal-iOS | Signal/src/network/GiphyDownloader.swift | 1 | 30136 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import ObjectiveC
// Stills should be loaded before full GIFs.
enum GiphyRequestPriority {
case low, high
}
enum GiphyAssetSegmentState: UInt {
case waiting
case downloading
case complete
case failed
}
class GiphyAssetSegment {
let TAG = "[GiphyAssetSegment]"
public let index: UInt
public let segmentStart: UInt
public let segmentLength: UInt
// The amount of the segment that is overlap.
// The overlap lies in the _first_ n bytes of the segment data.
public let redundantLength: UInt
// This state should only be accessed on the main thread.
public var state: GiphyAssetSegmentState = .waiting {
didSet {
AssertIsOnMainThread()
}
}
// This state is accessed off the main thread.
//
// * During downloads it will be accessed on the task delegate queue.
// * After downloads it will be accessed on a worker queue.
private var segmentData = Data()
// This state should only be accessed on the main thread.
public weak var task: URLSessionDataTask?
init(index: UInt,
segmentStart: UInt,
segmentLength: UInt,
redundantLength: UInt) {
self.index = index
self.segmentStart = segmentStart
self.segmentLength = segmentLength
self.redundantLength = redundantLength
}
public func totalDataSize() -> UInt {
return UInt(segmentData.count)
}
public func append(data: Data) {
guard state == .downloading else {
owsFail("\(TAG) appending data in invalid state: \(state)")
return
}
segmentData.append(data)
}
public func mergeData(assetData: inout Data) -> Bool {
guard state == .complete else {
owsFail("\(TAG) merging data in invalid state: \(state)")
return false
}
guard UInt(segmentData.count) == segmentLength else {
owsFail("\(TAG) segment data length: \(segmentData.count) doesn't match expected length: \(segmentLength)")
return false
}
// In some cases the last two segments will overlap.
// In that case, we only want to append the non-overlapping
// tail of the segment data.
let bytesToIgnore = Int(redundantLength)
if bytesToIgnore > 0 {
let subdata = segmentData.subdata(in: bytesToIgnore..<Int(segmentLength))
assetData.append(subdata)
} else {
assetData.append(segmentData)
}
return true
}
}
enum GiphyAssetRequestState: UInt {
// Does not yet have content length.
case waiting
// Getting content length.
case requestingSize
// Has content length, ready for downloads or downloads in flight.
case active
// Success
case complete
// Failure
case failed
}
// Represents a request to download a GIF.
//
// Should be cancelled if no longer necessary.
@objc class GiphyAssetRequest: NSObject {
static let TAG = "[GiphyAssetRequest]"
let TAG = "[GiphyAssetRequest]"
let rendition: GiphyRendition
let priority: GiphyRequestPriority
// Exactly one of success or failure should be called once,
// on the main thread _unless_ this request is cancelled before
// the request succeeds or fails.
private var success: ((GiphyAssetRequest?, GiphyAsset) -> Void)?
private var failure: ((GiphyAssetRequest) -> Void)?
var wasCancelled = false
// This property is an internal implementation detail of the download process.
var assetFilePath: String?
// This state should only be accessed on the main thread.
private var segments = [GiphyAssetSegment]()
public var state: GiphyAssetRequestState = .waiting
public var contentLength: Int = 0 {
didSet {
AssertIsOnMainThread()
assert(oldValue == 0)
assert(contentLength > 0)
createSegments()
}
}
public weak var contentLengthTask: URLSessionDataTask?
init(rendition: GiphyRendition,
priority: GiphyRequestPriority,
success:@escaping ((GiphyAssetRequest?, GiphyAsset) -> Void),
failure:@escaping ((GiphyAssetRequest) -> Void)) {
self.rendition = rendition
self.priority = priority
self.success = success
self.failure = failure
super.init()
}
private func segmentSize() -> UInt {
AssertIsOnMainThread()
let contentLength = UInt(self.contentLength)
guard contentLength > 0 else {
owsFail("\(TAG) rendition missing contentLength")
requestDidFail()
return 0
}
let k1MB: UInt = 1024 * 1024
let k500KB: UInt = 500 * 1024
let k100KB: UInt = 100 * 1024
let k50KB: UInt = 50 * 1024
let k10KB: UInt = 10 * 1024
let k1KB: UInt = 1 * 1024
for segmentSize in [k1MB, k500KB, k100KB, k50KB, k10KB, k1KB ] {
if contentLength >= segmentSize {
return segmentSize
}
}
return contentLength
}
private func createSegments() {
AssertIsOnMainThread()
let segmentLength = segmentSize()
guard segmentLength > 0 else {
return
}
let contentLength = UInt(self.contentLength)
var nextSegmentStart: UInt = 0
var index: UInt = 0
while nextSegmentStart < contentLength {
var segmentStart: UInt = nextSegmentStart
var redundantLength: UInt = 0
// The last segment may overlap the penultimate segment
// in order to keep the segment sizes uniform.
if segmentStart + segmentLength > contentLength {
redundantLength = segmentStart + segmentLength - contentLength
segmentStart = contentLength - segmentLength
}
let assetSegment = GiphyAssetSegment(index:index,
segmentStart:segmentStart,
segmentLength:segmentLength,
redundantLength:redundantLength)
segments.append(assetSegment)
nextSegmentStart = segmentStart + segmentLength
index += 1
}
}
private func firstSegmentWithState(state: GiphyAssetSegmentState) -> GiphyAssetSegment? {
AssertIsOnMainThread()
for segment in segments {
guard segment.state != .failed else {
owsFail("\(TAG) unexpected failed segment.")
continue
}
if segment.state == state {
return segment
}
}
return nil
}
public func firstWaitingSegment() -> GiphyAssetSegment? {
AssertIsOnMainThread()
return firstSegmentWithState(state:.waiting)
}
public func downloadingSegmentsCount() -> UInt {
AssertIsOnMainThread()
var result: UInt = 0
for segment in segments {
guard segment.state != .failed else {
owsFail("\(TAG) unexpected failed segment.")
continue
}
if segment.state == .downloading {
result += 1
}
}
return result
}
public func areAllSegmentsComplete() -> Bool {
AssertIsOnMainThread()
for segment in segments {
guard segment.state == .complete else {
return false
}
}
return true
}
public func writeAssetToFile(gifFolderPath: String) -> GiphyAsset? {
var assetData = Data()
for segment in segments {
guard segment.state == .complete else {
owsFail("\(TAG) unexpected incomplete segment.")
return nil
}
guard segment.totalDataSize() > 0 else {
owsFail("\(TAG) could not merge empty segment.")
return nil
}
guard segment.mergeData(assetData: &assetData) else {
owsFail("\(TAG) failed to merge segment data.")
return nil
}
}
guard assetData.count == contentLength else {
owsFail("\(TAG) asset data has unexpected length.")
return nil
}
guard assetData.count > 0 else {
owsFail("\(TAG) could not write empty asset to disk.")
return nil
}
let fileExtension = rendition.fileExtension
let fileName = (NSUUID().uuidString as NSString).appendingPathExtension(fileExtension)!
let filePath = (gifFolderPath as NSString).appendingPathComponent(fileName)
Logger.verbose("\(TAG) filePath: \(filePath).")
do {
try assetData.write(to: NSURL.fileURL(withPath:filePath), options: .atomicWrite)
let asset = GiphyAsset(rendition: rendition, filePath : filePath)
return asset
} catch let error as NSError {
owsFail("\(GiphyAsset.TAG) file write failed: \(filePath), \(error)")
return nil
}
}
public func cancel() {
AssertIsOnMainThread()
wasCancelled = true
contentLengthTask?.cancel()
contentLengthTask = nil
for segment in segments {
segment.task?.cancel()
segment.task = nil
}
// Don't call the callbacks if the request is cancelled.
clearCallbacks()
}
private func clearCallbacks() {
AssertIsOnMainThread()
success = nil
failure = nil
}
public func requestDidSucceed(asset: GiphyAsset) {
AssertIsOnMainThread()
success?(self, asset)
// Only one of the callbacks should be called, and only once.
clearCallbacks()
}
public func requestDidFail() {
AssertIsOnMainThread()
failure?(self)
// Only one of the callbacks should be called, and only once.
clearCallbacks()
}
}
// Represents a downloaded gif asset.
//
// The blob on disk is cleaned up when this instance is deallocated,
// so consumers of this resource should retain a strong reference to
// this instance as long as they are using the asset.
@objc class GiphyAsset: NSObject {
static let TAG = "[GiphyAsset]"
let rendition: GiphyRendition
let filePath: String
init(rendition: GiphyRendition,
filePath: String) {
self.rendition = rendition
self.filePath = filePath
}
deinit {
// Clean up on the asset on disk.
let filePathCopy = filePath
DispatchQueue.global().async {
do {
let fileManager = FileManager.default
try fileManager.removeItem(atPath:filePathCopy)
} catch let error as NSError {
owsFail("\(GiphyAsset.TAG) file cleanup failed: \(filePathCopy), \(error)")
}
}
}
}
// A simple LRU cache bounded by the number of entries.
//
// TODO: We might want to observe memory pressure notifications.
class LRUCache<KeyType: Hashable & Equatable, ValueType> {
private var cacheMap = [KeyType: ValueType]()
private var cacheOrder = [KeyType]()
private let maxSize: Int
init(maxSize: Int) {
self.maxSize = maxSize
}
public func get(key: KeyType) -> ValueType? {
guard let value = cacheMap[key] else {
return nil
}
// Update cache order.
cacheOrder = cacheOrder.filter { $0 != key }
cacheOrder.append(key)
return value
}
public func set(key: KeyType, value: ValueType) {
cacheMap[key] = value
// Update cache order.
cacheOrder = cacheOrder.filter { $0 != key }
cacheOrder.append(key)
while cacheOrder.count > maxSize {
guard let staleKey = cacheOrder.first else {
owsFail("Cache ordering unexpectedly empty")
return
}
cacheOrder.removeFirst()
cacheMap.removeValue(forKey:staleKey)
}
}
}
private var URLSessionTaskGiphyAssetRequest: UInt8 = 0
private var URLSessionTaskGiphyAssetSegment: UInt8 = 0
// This extension is used to punch an asset request onto a download task.
extension URLSessionTask {
var assetRequest: GiphyAssetRequest {
get {
return objc_getAssociatedObject(self, &URLSessionTaskGiphyAssetRequest) as! GiphyAssetRequest
}
set {
objc_setAssociatedObject(self, &URLSessionTaskGiphyAssetRequest, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var assetSegment: GiphyAssetSegment {
get {
return objc_getAssociatedObject(self, &URLSessionTaskGiphyAssetSegment) as! GiphyAssetSegment
}
set {
objc_setAssociatedObject(self, &URLSessionTaskGiphyAssetSegment, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
@objc class GiphyDownloader: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
// MARK: - Properties
let TAG = "[GiphyDownloader]"
static let sharedInstance = GiphyDownloader()
var gifFolderPath = ""
// Force usage as a singleton
override private init() {
AssertIsOnMainThread()
super.init()
ensureGifFolder()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private let kGiphyBaseURL = "https://api.giphy.com/"
private lazy var giphyDownloadSession: URLSession = {
AssertIsOnMainThread()
let configuration = GiphyAPI.giphySessionConfiguration()
configuration.urlCache = nil
configuration.requestCachePolicy = .reloadIgnoringCacheData
configuration.httpMaximumConnectionsPerHost = 10
let session = URLSession(configuration:configuration,
delegate:self,
delegateQueue:nil)
return session
}()
// 100 entries of which at least half will probably be stills.
// Actual animated GIFs will usually be less than 3 MB so the
// max size of the cache on disk should be ~150 MB. Bear in mind
// that assets are not always deleted on disk as soon as they are
// evacuated from the cache; if a cache consumer (e.g. view) is
// still using the asset, the asset won't be deleted on disk until
// it is no longer in use.
private var assetMap = LRUCache<NSURL, GiphyAsset>(maxSize:100)
// TODO: We could use a proper queue, e.g. implemented with a linked
// list.
private var assetRequestQueue = [GiphyAssetRequest]()
// The success and failure callbacks are always called on main queue.
//
// The success callbacks may be called synchronously on cache hit, in
// which case the GiphyAssetRequest parameter will be nil.
public func requestAsset(rendition: GiphyRendition,
priority: GiphyRequestPriority,
success:@escaping ((GiphyAssetRequest?, GiphyAsset) -> Void),
failure:@escaping ((GiphyAssetRequest) -> Void)) -> GiphyAssetRequest? {
AssertIsOnMainThread()
if let asset = assetMap.get(key:rendition.url) {
// Synchronous cache hit.
Logger.verbose("\(self.TAG) asset cache hit: \(rendition.url)")
success(nil, asset)
return nil
}
// Cache miss.
//
// Asset requests are done queued and performed asynchronously.
Logger.verbose("\(self.TAG) asset cache miss: \(rendition.url)")
let assetRequest = GiphyAssetRequest(rendition:rendition,
priority:priority,
success:success,
failure:failure)
assetRequestQueue.append(assetRequest)
// Process the queue (which may start this request)
// asynchronously so that the caller has time to store
// a reference to the asset request returned by this
// method before its success/failure handler is called.
processRequestQueueAsync()
return assetRequest
}
public func cancelAllRequests() {
AssertIsOnMainThread()
Logger.verbose("\(self.TAG) cancelAllRequests")
self.assetRequestQueue.forEach { $0.cancel() }
self.assetRequestQueue = []
}
private func segmentRequestDidSucceed(assetRequest: GiphyAssetRequest, assetSegment: GiphyAssetSegment) {
DispatchQueue.main.async {
assetSegment.state = .complete
if assetRequest.areAllSegmentsComplete() {
// If the asset request has completed all of its segments,
// try to write the asset to file.
assetRequest.state = .complete
// Move write off main thread.
DispatchQueue.global().async {
guard let asset = assetRequest.writeAssetToFile(gifFolderPath:self.gifFolderPath) else {
self.segmentRequestDidFail(assetRequest:assetRequest, assetSegment:assetSegment)
return
}
self.assetRequestDidSucceed(assetRequest: assetRequest, asset: asset)
}
} else {
self.processRequestQueueSync()
}
}
}
private func assetRequestDidSucceed(assetRequest: GiphyAssetRequest, asset: GiphyAsset) {
DispatchQueue.main.async {
self.assetMap.set(key:assetRequest.rendition.url, value:asset)
self.removeAssetRequestFromQueue(assetRequest:assetRequest)
assetRequest.requestDidSucceed(asset:asset)
}
}
// TODO: If we wanted to implement segment retry, we'll need to add
// a segmentRequestDidFail() method.
private func segmentRequestDidFail(assetRequest: GiphyAssetRequest, assetSegment: GiphyAssetSegment) {
DispatchQueue.main.async {
assetSegment.state = .failed
assetRequest.state = .failed
self.assetRequestDidFail(assetRequest:assetRequest)
}
}
private func assetRequestDidFail(assetRequest: GiphyAssetRequest) {
DispatchQueue.main.async {
self.removeAssetRequestFromQueue(assetRequest:assetRequest)
assetRequest.requestDidFail()
}
}
private func removeAssetRequestFromQueue(assetRequest: GiphyAssetRequest) {
AssertIsOnMainThread()
guard assetRequestQueue.contains(assetRequest) else {
Logger.warn("\(TAG) could not remove asset request from queue: \(assetRequest.rendition.url)")
return
}
assetRequestQueue = assetRequestQueue.filter { $0 != assetRequest }
// Process the queue async to ensure that state in the downloader
// classes is consistent before we try to start a new request.
processRequestQueueAsync()
}
private func processRequestQueueAsync() {
DispatchQueue.main.async {
self.processRequestQueueSync()
}
}
// * Start a segment request or content length request if possible.
// * Complete/cancel asset requests if possible.
//
private func processRequestQueueSync() {
AssertIsOnMainThread()
guard let assetRequest = popNextAssetRequest() else {
return
}
guard !assetRequest.wasCancelled else {
// Discard the cancelled asset request and try again.
removeAssetRequestFromQueue(assetRequest: assetRequest)
return
}
guard UIApplication.shared.applicationState == .active else {
// If app is not active, fail the asset request.
assetRequest.state = .failed
assetRequestDidFail(assetRequest:assetRequest)
processRequestQueueSync()
return
}
if let asset = assetMap.get(key:assetRequest.rendition.url) {
// Deferred cache hit, avoids re-downloading assets that were
// downloaded while this request was queued.
assetRequest.state = .complete
assetRequestDidSucceed(assetRequest : assetRequest, asset: asset)
return
}
if assetRequest.state == .waiting {
// If asset request hasn't yet determined the resource size,
// try to do so now.
assetRequest.state = .requestingSize
var request = URLRequest(url: assetRequest.rendition.url as URL)
request.httpMethod = "HEAD"
request.httpShouldUsePipelining = true
let task = giphyDownloadSession.dataTask(with:request, completionHandler: { data, response, error -> Void in
if let data = data, data.count > 0 {
owsFail("\(self.TAG) HEAD request has unexpected body: \(data.count).")
}
self.handleAssetSizeResponse(assetRequest:assetRequest, response:response, error:error)
})
assetRequest.contentLengthTask = task
task.resume()
} else {
// Start a download task.
guard let assetSegment = assetRequest.firstWaitingSegment() else {
owsFail("\(TAG) queued asset request does not have a waiting segment.")
return
}
assetSegment.state = .downloading
var request = URLRequest(url: assetRequest.rendition.url as URL)
request.httpShouldUsePipelining = true
let rangeHeaderValue = "bytes=\(assetSegment.segmentStart)-\(assetSegment.segmentStart + assetSegment.segmentLength - 1)"
request.addValue(rangeHeaderValue, forHTTPHeaderField: "Range")
let task = giphyDownloadSession.dataTask(with:request)
task.assetRequest = assetRequest
task.assetSegment = assetSegment
assetSegment.task = task
task.resume()
}
// Recurse; we may be able to start multiple downloads.
processRequestQueueSync()
}
private func handleAssetSizeResponse(assetRequest: GiphyAssetRequest, response: URLResponse?, error: Error?) {
guard error == nil else {
assetRequest.state = .failed
self.assetRequestDidFail(assetRequest:assetRequest)
return
}
guard let httpResponse = response as? HTTPURLResponse else {
owsFail("\(self.TAG) Asset size response is invalid.")
assetRequest.state = .failed
self.assetRequestDidFail(assetRequest:assetRequest)
return
}
guard let contentLengthString = httpResponse.allHeaderFields["Content-Length"] as? String else {
owsFail("\(self.TAG) Asset size response is missing content length.")
assetRequest.state = .failed
self.assetRequestDidFail(assetRequest:assetRequest)
return
}
guard let contentLength = Int(contentLengthString) else {
owsFail("\(self.TAG) Asset size response has unparsable content length.")
assetRequest.state = .failed
self.assetRequestDidFail(assetRequest:assetRequest)
return
}
guard contentLength > 0 else {
owsFail("\(self.TAG) Asset size response has invalid content length.")
assetRequest.state = .failed
self.assetRequestDidFail(assetRequest:assetRequest)
return
}
DispatchQueue.main.async {
assetRequest.contentLength = contentLength
assetRequest.state = .active
self.processRequestQueueSync()
}
}
// Return the first asset request for which we either:
//
// * Need to download the content length.
// * Need to download at least one of its segments.
private func popNextAssetRequest() -> GiphyAssetRequest? {
AssertIsOnMainThread()
let kMaxAssetRequestCount: UInt = 3
let kMaxAssetRequestsPerAssetCount: UInt = kMaxAssetRequestCount - 1
// Prefer the first "high" priority request;
// fall back to the first "low" priority request.
var activeAssetRequestsCount: UInt = 0
for priority in [GiphyRequestPriority.high, GiphyRequestPriority.low] {
for assetRequest in assetRequestQueue where assetRequest.priority == priority {
switch assetRequest.state {
case .waiting:
// This asset request needs its content length.
return assetRequest
case .requestingSize:
activeAssetRequestsCount += 1
// Ensure that only N requests are active at a time.
guard activeAssetRequestsCount < kMaxAssetRequestCount else {
return nil
}
continue
case .active:
break
case .complete:
continue
case .failed:
continue
}
let downloadingSegmentsCount = assetRequest.downloadingSegmentsCount()
activeAssetRequestsCount += downloadingSegmentsCount
// Ensure that only N segment requests are active per asset at a time.
guard downloadingSegmentsCount < kMaxAssetRequestsPerAssetCount else {
continue
}
// Ensure that only N requests are active at a time.
guard activeAssetRequestsCount < kMaxAssetRequestCount else {
return nil
}
guard assetRequest.firstWaitingSegment() != nil else {
/// Asset request does not have a waiting segment.
continue
}
return assetRequest
}
}
return nil
}
// MARK: URLSessionDataDelegate
@nonobjc
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
completionHandler(.allow)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
let assetRequest = dataTask.assetRequest
let assetSegment = dataTask.assetSegment
guard !assetRequest.wasCancelled else {
dataTask.cancel()
segmentRequestDidFail(assetRequest:assetRequest, assetSegment:assetSegment)
return
}
assetSegment.append(data:data)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Swift.Void) {
completionHandler(nil)
}
// MARK: URLSessionTaskDelegate
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
let assetRequest = task.assetRequest
let assetSegment = task.assetSegment
guard !assetRequest.wasCancelled else {
task.cancel()
segmentRequestDidFail(assetRequest:assetRequest, assetSegment:assetSegment)
return
}
if let error = error {
Logger.error("\(TAG) download failed with error: \(error)")
segmentRequestDidFail(assetRequest:assetRequest, assetSegment:assetSegment)
return
}
guard let httpResponse = task.response as? HTTPURLResponse else {
Logger.error("\(TAG) missing or unexpected response: \(task.response)")
segmentRequestDidFail(assetRequest:assetRequest, assetSegment:assetSegment)
return
}
let statusCode = httpResponse.statusCode
guard statusCode >= 200 && statusCode < 400 else {
Logger.error("\(TAG) response has invalid status code: \(statusCode)")
segmentRequestDidFail(assetRequest:assetRequest, assetSegment:assetSegment)
return
}
guard assetSegment.totalDataSize() == assetSegment.segmentLength else {
Logger.error("\(TAG) segment is missing data: \(statusCode)")
segmentRequestDidFail(assetRequest:assetRequest, assetSegment:assetSegment)
return
}
segmentRequestDidSucceed(assetRequest : assetRequest, assetSegment: assetSegment)
}
// MARK: Temp Directory
public func ensureGifFolder() {
// We write assets to the temporary directory so that iOS can clean them up.
// We try to eagerly clean up these assets when they are no longer in use.
let tempDirPath = NSTemporaryDirectory()
let dirPath = (tempDirPath as NSString).appendingPathComponent("GIFs")
do {
let fileManager = FileManager.default
// Try to delete existing folder if necessary.
if fileManager.fileExists(atPath:dirPath) {
try fileManager.removeItem(atPath:dirPath)
gifFolderPath = dirPath
}
// Try to create folder if necessary.
if !fileManager.fileExists(atPath:dirPath) {
try fileManager.createDirectory(atPath:dirPath,
withIntermediateDirectories:true,
attributes:nil)
gifFolderPath = dirPath
}
// Don't back up Giphy downloads.
OWSFileSystem.protectFolder(atPath:dirPath)
} catch let error as NSError {
owsFail("\(GiphyAsset.TAG) ensureTempFolder failed: \(dirPath), \(error)")
gifFolderPath = tempDirPath
}
}
}
| gpl-3.0 | a178754ddf8f9c6716cfcbc5e7a93198 | 34.329426 | 201 | 0.60957 | 5.316867 | false | false | false | false |
TheBasicMind/SlackReporter | Pod/Classes/SRForm.swift | 1 | 24644 | //
// SRForm.swift
// SlackReporter
//
// Created by Paul Lancefield on 28/12/2015.
// Copyright © 2015 Paul Lancefield. All rights reserved.
// Released under the MIT license
//
import Foundation
import UIKit
@objc protocol SRFeedbackReceptical
{
var feedback: String { set get }
var placeholderText: String? { set get }
var feedbackView: UIView? { get }
func tapAnywhereAssignsFirstResponder()->Bool
}
@objc public enum SRFeedbackType: Int
{
case SingleLineText
case MultilineText
case Email
case ListSelection
//case RatingSelection
//case Image
}
@objc public enum SRSystemFeedbackLocation: Int
{
case Top
case Bottom
}
public class SRSystemFeedback: NSObject
{
public var identifier: String = ""
public var title: String = ""
public var feedback: String = ""
public var feedbackLocation: SRSystemFeedbackLocation = SRSystemFeedbackLocation.Top
public init(withIdentifier identifier: String, title: String, feedback: String, feedbackLocation: SRSystemFeedbackLocation) {
self.identifier = identifier
self.title = title
self.feedback = feedback
self.feedbackLocation = feedbackLocation
}
}
/**
A Slack Reporter form element. An element is representative
of e.g. each feedback entity, such as a singleLineText field
or a MultiLineText field
*/
public class SRFormElement: NSObject, NSCoding
{
public var identifier: String
public var title: String
public var feedbackType: SRFeedbackType
public var feedbackValues: [String]
public var rememberResult: Bool
/**
Returns a Slack Reporter form element definition object.
- parameter identifier: The identifier for a form element. Cannot be nil. The
identifier does not have to be unique, but may be used to disambiguate form elements with
the same Title used accross multiple forms. The SRForm object has parameters which allow
it to be determined if form identifiers or titles or both are displayed in the Slack
feedback message.
- parameter title: The title of the form element, displayed to the user.
- parameter type: The type of the form element
- parameter feedbackValues: An array of element values, must be of type NSString, may be nil.
Element values are only utilised by TextEntry and ListSelection feedback types. For the
text entry type only the first string in the array is used as placeholder text, for the
ListSelection type the array is used to generate the list selector item list.
- parameter description: An optional description that can be used to provide the user
with more informaton about the kind of feedback sought.
*/
public init(identifier:String, title:String, type:SRFeedbackType, feedbackValues:[String], rememberResult:Bool)
{
self.identifier = identifier
self.title = title
feedbackType = type
self.feedbackValues = feedbackValues
self.rememberResult = rememberResult
}
public required convenience init?(coder aDecoder: NSCoder)
{
let identifier = aDecoder.decodeObjectForKey("identifier") as! String
let title = aDecoder.decodeObjectForKey("title") as! String
let feedbackType = SRFeedbackType(rawValue: aDecoder.decodeIntegerForKey("feedbackType") )!
let feedbackValues:[String] = aDecoder.decodeObjectForKey("feedbackValues") as! [String]
let rememberResult = aDecoder.decodeBoolForKey("rememberResult")
self.init( identifier: identifier,
title: title,
type: feedbackType,
feedbackValues: feedbackValues,
rememberResult: rememberResult)
}
public func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeObject(identifier, forKey: "identifier")
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeInteger(Int(feedbackType.rawValue), forKey: "feedbackType")
aCoder.encodeObject(feedbackValues, forKey: "feedbackValues")
aCoder.encodeBool(rememberResult, forKey: "rememberResult")
}
public override var description: String
{
get {
return "SRFormElement title:\(identifier), title:\(title), feedbackType:\(feedbackType), feedbackValues:\(feedbackValues) rememberResult:\(rememberResult)"
}
}
}
/**
A Slack Reporter form element. A section represents a group of table
elements and can ensure title text is displayed above the group
holds the elements themselves and ensures footer text is displayed
below the group.
*/
public class SRFormSection: NSObject, NSCoding
{
public var title: String
public var elements: [SRFormElement]
public var footerText: String?
public subscript(element: Int)->SRFormElement?
{
get {
guard elements.indices.contains(element) else {
return nil
}
return elements[element]
}
}
/**
Returns a Slack Reporter form section object.
- parameter title: the title of the form element, displayed to the user. If the section has no title pass a zero length string.
- parameter elements: an array of SRElements to be displayed within the section
- parameter footerText: subscript text description displayed below the section. Typically used for providing directions qualifying what is expected of the user.
*/
public init(title:String, elements:[SRFormElement], footerText:String?)
{
self.title = title
self.elements = elements
self.footerText = footerText
super.init()
}
public required convenience init?(coder aDecoder: NSCoder)
{
let title = aDecoder.decodeObjectForKey("title") as! String
let someElements = aDecoder.decodeObjectForKey("elements") as! NSArray
let myFooterText = aDecoder.decodeObjectForKey("footerText") as! String
guard let swiftElements = someElements as? [SRFormElement] else {
// downcastedSwiftArray contains only NSView objects
return nil
}
self.init( title: title, elements: swiftElements, footerText: myFooterText )
}
public func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(elements, forKey: "elements")
aCoder.encodeObject(footerText, forKey: "footerText")
}
public override var description: String
{
get {
return "SRFormElement title:\(title), elements:\(elements), footerText:\(footerText)"
}
}
}
/**
A Slack Reporter form element. An element can represent a table group header
*/
public class SRForm: NSObject, NSCoding
{
public var title: String
public var channel: String = ""
public var sections: [SRFormSection]
/**
Add system feedback elements to this array to insert feedback that will be reported
to Slack but withoug being shown in the form. This can be used, for instance
to supply information that doesn't require user input such as the device type.
Indeed the default forms include the device type and software system.
*/
public var systemFeedback: [SRSystemFeedback]
public var token: String = ""
/**
If this is checked, the form ID of each element is shown in the report to slack.
If displayTitle is also checked, both will be shown.
*/
public var displayID: Bool = true
/**
If this is checked, the form title of each element is shown in the report to slack
if displayID is also checked, both will be shown
*/
public var displayTitle: Bool = false
/**
A static function to get the default form with dynamic project name insertion
*/
private class func defaultFormContent()->[SRFormSection]
{
let details = NSLocalizedString("Your details", comment:"Label given to Your Details form element group")
let name = NSLocalizedString("Name", comment:"Label given to First Name field")
let email = NSLocalizedString("Email", comment:"Label given to Email field")
let defaultSection1Elements = [
SRFormElement(identifier: name, title: name, type: .SingleLineText, feedbackValues: [], rememberResult: true),
SRFormElement(identifier: email, title: email, type: .Email, feedbackValues: [], rememberResult: true),
]
let remember = NSLocalizedString("You only need to provide these details once. We will remember them from now on.", comment:"Subsection comment given to your details form element group")
let feedback = NSLocalizedString("Feedback", comment:"ID given to Feedback field")
let readinessTitle = NSLocalizedString("Readiness", comment: "Title for readiness feedback form element")
let readinessOption1 = NSLocalizedString("Ready for launch", comment: "readiness form feedback option 1")
let readinessOption2 = NSLocalizedString("Still a Beta", comment: "readiness form feedback option 2")
let readinessOption3 = NSLocalizedString("Not even a beta", comment: "readiness form feedback option 3")
let defaultSection2Element = [
SRFormElement( identifier: readinessTitle,
title: readinessTitle,
type: .ListSelection,
feedbackValues: [readinessOption1,readinessOption2,readinessOption3],
rememberResult: false)]
let defaultSection3Elements = [
SRFormElement(identifier: feedback, title: "", type: .MultilineText, feedbackValues: [], rememberResult: false)]
let appName: String = ", " + ((NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String) ?? "")
let ourReadiness = NSLocalizedString("Tell, as a prospective user, how ready you think the app is for launch", comment:"Subsection comment for Feedback form element group")
let tellUs = NSLocalizedString("Tell us what you think of this app\(appName)", comment:"Subsection comment for Feedback form element group")
let ourSections:[SRFormSection] = [
SRFormSection(title: details, elements: defaultSection1Elements, footerText: remember),
SRFormSection(title: "", elements: defaultSection2Element, footerText: ourReadiness),
SRFormSection(title: feedback, elements: defaultSection3Elements, footerText: tellUs)
]
return ourSections
}
/**
Improvement suggestion form sections
*/
private static func defaultFeatureSuggestionSections()->[SRFormSection]
{
//////////////////////
//////////////////////
////
//// Section 1 Details
let section1Header = NSLocalizedString("Your Details", comment:"Label given to Your Details form element group")
let name = NSLocalizedString("Name", comment:"Label given to First Name field")
let email = NSLocalizedString("Email", comment:"Label given to Email field")
let section1Elements = [
SRFormElement(identifier: name, title: name, type: .SingleLineText, feedbackValues: [], rememberResult: true),
SRFormElement(identifier: email, title: email, type: .Email, feedbackValues: [], rememberResult: true),
]
let section1Footer = NSLocalizedString("You only need to provide these details once. We will remember them from now on.", comment:"Form subsection comment")
///////////////////////////
///////////////////////////
////
//// Section 2 Problem Type
let section2Header = NSLocalizedString("Feature suggestion", comment: "Form section header")
let title = NSLocalizedString("Title", comment: "User provided name for the feature suggestion")
let problemType = NSLocalizedString("Type", comment: "Feature suggestion type feedback element")
let pt1 = NSLocalizedString("Existing feature improvement", comment: "Form option")
let pt2 = NSLocalizedString("New feature suggestion", comment: "Form option")
let section2Elements = [
SRFormElement( identifier: title,
title: title,
type: .SingleLineText,
feedbackValues: [],
rememberResult: false),
SRFormElement( identifier: problemType,
title: problemType,
type: .ListSelection,
feedbackValues: [pt1,pt2],
rememberResult: false),]
//////////////////////////////////
//////////////////////////////////
////
//// Section 3 Description
let section3Header = NSLocalizedString("Description", comment:"Section header")
let section3Elements = [
SRFormElement(identifier: section3Header, title: "", type: .MultilineText, feedbackValues: [], rememberResult: false)
]
let section3Footer = NSLocalizedString("Please describe the improvement/suggestion.", comment:"Form section footer")
let ourSections:[SRFormSection] = [
SRFormSection(title: section1Header, elements: section1Elements, footerText: section1Footer),
SRFormSection(title: section2Header, elements: section2Elements, footerText: nil),
SRFormSection(title: section3Header, elements: section3Elements, footerText: section3Footer)
]
return ourSections
}
/**
Problem report form sections
*/
private static func defaultProblemReportSections()->[SRFormSection]
{
//////////////////////
//////////////////////
////
//// Section 1 Details
let section1Header = NSLocalizedString("Your details", comment:"Label given to Your Details form element group")
let name = NSLocalizedString("Name", comment:"Label given to First Name field")
let email = NSLocalizedString("Email", comment:"Label given to Email field")
let section1Elements = [
SRFormElement(identifier: name, title: name, type: .SingleLineText, feedbackValues: [], rememberResult: true),
SRFormElement(identifier: email, title: email, type: .Email, feedbackValues: [], rememberResult: true),
]
let section1Footer = NSLocalizedString("You only need to provide these details once. We will remember them from now on.", comment:"Form subsection comment")
///////////////////////////
///////////////////////////
////
//// Section 2 Problem Type
let section2Header = NSLocalizedString("Problem Details", comment:"Form section title")
let issueTitle = NSLocalizedString("Problem Title", comment: "User provided name for the issue")
let problemType = NSLocalizedString("Type", comment: "Title Problem Report type feedback element")
let pt1 = NSLocalizedString("Bug", comment: "Form option")
let pt2 = NSLocalizedString("Text/Language", comment: "Form option")
let pt3 = NSLocalizedString("Usability Issue", comment: "Form option")
let pt4 = NSLocalizedString("Other", comment: "Form option")
let reproducibility = NSLocalizedString("Frequency", comment: "Title of Problem Report field asking for reproducibility information")
let r1 = NSLocalizedString("100% Reproducible", comment: "Form option")
let r2 = NSLocalizedString("Occurs often", comment: "Form option")
let r3 = NSLocalizedString("Occurs occassionaly", comment: "Form option")
let r4 = NSLocalizedString("Very rarely but more than once", comment: "Form option")
let r5 = NSLocalizedString("Only seen once", comment: "Form option")
let r6 = NSLocalizedString("Shucks, I haven't tried to reproduce it", comment: "Form option")
let section2Elements = [
SRFormElement( identifier: issueTitle,
title: issueTitle,
type: .SingleLineText,
feedbackValues: [],
rememberResult: false),
SRFormElement( identifier: problemType,
title: problemType,
type: .ListSelection,
feedbackValues: [pt1,pt2,pt3,pt4],
rememberResult: false),
SRFormElement( identifier: reproducibility,
title: reproducibility,
type: .ListSelection,
feedbackValues: [r1,r2,r3,r4,r5,r6],
rememberResult: false)
]
let section2Footer = NSLocalizedString("Let us know if you can reproduce the issue. Accurate use of this field helps us greatly", comment:"Subsection comment given to your details form element group")
//////////////////////////////////
//////////////////////////////////
////
//// Section 3 Preconditions
let section3Header = NSLocalizedString("Preconditions", comment:"ID given to Feedback field")
let section3Elements = [
SRFormElement(identifier: section3Header, title: "", type: .MultilineText, feedbackValues: [], rememberResult: false)]
let section3Footer = NSLocalizedString("Please describe the steps you took leading up to the issue.", comment:"Form section footer")
//////////////////////////////////
//////////////////////////////////
////
//// Section 4 Description
let section4Header = NSLocalizedString("Problem Description", comment:"Section header")
let resultField = NSLocalizedString("Result", comment:"Field title")
let rf1 = NSLocalizedString("Suboptimal Experience", comment: "Form option")
let rf2 = NSLocalizedString("Hang - No input possible", comment: "Form option")
let rf3 = NSLocalizedString("Hang - Slow/bad input possible", comment: "Form option")
let rf4 = NSLocalizedString("Crash to homescreen", comment: "Form option")
let rf5 = NSLocalizedString("Other", comment: "Form option")
let descriptionField = NSLocalizedString("Problem Description", comment:"Field title")
let section4Elements = [
SRFormElement(identifier: resultField, title: resultField, type: .ListSelection, feedbackValues: [rf1,rf2,rf3,rf4,rf5], rememberResult: false),
SRFormElement(identifier: descriptionField, title: "", type: .MultilineText, feedbackValues: [], rememberResult: false)
]
let section4Footer = NSLocalizedString("Please describe the problem and the result.", comment:"Form section footer")
let ourSections:[SRFormSection] = [
SRFormSection(title: section1Header, elements: section1Elements, footerText: section1Footer),
SRFormSection(title: section2Header, elements: section2Elements, footerText: section2Footer),
SRFormSection(title: section3Header, elements: section3Elements, footerText: section3Footer),
SRFormSection(title: section4Header, elements: section4Elements, footerText: section4Footer)
]
return ourSections
}
private static func defaultSystemFeedbackElements()->[SRSystemFeedback]
{
return [SRSystemFeedback(withIdentifier: "Device type", title: "Device type", feedback: UIDevice.currentDevice().modelName, feedbackLocation: .Bottom)]
}
/**
The designated intialiser returning a Slack Reporter form object.
see Settings->iTunes & App Stores on the iphone
for an example of the layout you can expect to see.
Create your own custom form as follows:
```
let elmnt1 = SRFormElement(title: "Email",
type: .Email,
feedbackValues: nil,
rememberResult: true)
let elmnt2 = SRFormElement(title: "Feedback",
type: .MultilineText
feedbackValues: nil
rememberResult: false)
let sctnA = SRFormSection(title: "A Section Title",
elements: [elmnt1, elmnt2],
footer: "Descriptive text in the section footer")
let form = SRForm(title:"My SLForm", sections:[sctnA])
```
- parameter title: the title of the form. May be nil
in which case a default title is given. If you want the title
to be blank, pass in an empty string
- parameter sections: an array of SRFormSection objects. May be
nil, in which case a simple default feedback form will be generated.
*/
subscript(section: Int)->SRFormSection?
{
get {
guard sections.indices.contains(section) else {
return nil
}
return sections[section]
}
}
subscript(section: Int, item: Int)->SRFormElement?
{
get {
guard sections.indices.contains(section) else {
return nil
}
guard sections[section].elements.indices.contains(item) else {
return nil
}
return sections[section].elements[item]
}
}
/**
The designated initialiser for a SlackReporter form.
*/
public init(title:String?, sections:[SRFormSection]?, systemFeedbackElements:[SRSystemFeedback]?)
{
self.title = title ?? NSLocalizedString("General Feedback", comment:"Title label given to form")
self.sections = sections ?? SRForm.defaultFormContent()
self.systemFeedback = systemFeedbackElements ?? SRForm.defaultSystemFeedbackElements()
super.init()
}
public static func defaultForms()->[SRForm]
{
return [SRForm(title:nil, sections:nil, systemFeedbackElements: nil), SRForm.improvementReportForm(), SRForm.problemReportForm()]
}
public static func improvementReportForm()->SRForm
{
return SRForm(title:"Improvement suggestion", sections: defaultFeatureSuggestionSections(), systemFeedbackElements: nil )
}
public static func problemReportForm()->SRForm
{
return SRForm(title:"Report problem", sections: defaultProblemReportSections(), systemFeedbackElements: nil )
}
public required convenience init?(coder aDecoder: NSCoder)
{
let title = aDecoder.decodeObjectForKey("title") as! String
let someSections = aDecoder.decodeObjectForKey("sections") as! NSArray
guard let swiftSections = someSections as? [SRFormSection] else {
// downcastedSwiftArray contains only NSView objects
return nil
}
self.init( title: title, sections: swiftSections, systemFeedbackElements: nil )
}
public func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(sections, forKey: "sections")
}
public override var description: String
{
get {
return "SRForm title:\(title), sections:\(sections)"
}
}
} | mit | cf5efa6f8f5d18643fb347df39821d8f | 42.463845 | 213 | 0.608773 | 5.335137 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | Aztec/Classes/Extensions/Array+ShortcodeAttribute.swift | 2 | 895 | import Foundation
public extension Array where Element == ShortcodeAttribute {
subscript(_ key: String) -> ShortcodeAttribute? {
get {
return first() { $0.key == key }
}
}
mutating func set(_ value: String, forKey key: String) {
set(.string(value), forKey: key)
}
mutating func set(_ value: ShortcodeAttribute.Value, forKey key: String) {
let newAttribute = ShortcodeAttribute(key: key, value: value)
guard let attributeIndex = firstIndex(where: { $0.key == key }) else {
append(newAttribute)
return
}
self[attributeIndex] = newAttribute
}
mutating func remove(key: String) {
guard let attributeIndex = firstIndex(where: { $0.key == key }) else {
return
}
remove(at: attributeIndex)
}
}
| mpl-2.0 | 2103357282dc4fc8ba4872e5018db94e | 26.121212 | 78 | 0.557542 | 4.520202 | false | false | false | false |
XeresRazor/SMeaGOL | SmeagolMath/SmeagolMath/Geometry/Matrix3.swift | 1 | 10435 | //
// Matrix3.swift
// Smeagol
//
// Created by Green2, David on 10/5/14.
// Copyright (c) 2014 Digital Worlds. All rights reserved.
//
import Foundation
//
// MARK: - Definition and initializes -
//
public struct Matrix3 {
let m00: Float, m01: Float, m02: Float
let m10: Float, m11: Float, m12: Float
let m20: Float, m21: Float, m22: Float
public static var identity: Matrix3 {
return Matrix3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
}
public init(_ m00: Float, _ m01: Float, _ m02: Float, _ m10: Float, _ m11: Float, _ m12: Float, _ m20: Float, _ m21: Float, _ m22: Float) {
self.m00 = m00
self.m01 = m01
self.m02 = m02
self.m10 = m10
self.m11 = m11
self.m12 = m12
self.m20 = m20
self.m21 = m21
self.m22 = m22
}
public init(array: [Float]) {
assert(array.count == 9, "Matrix3 must be instantiated with 9 values.")
self.m00 = array[0]
self.m01 = array[1]
self.m02 = array[2]
self.m10 = array[3]
self.m11 = array[4]
self.m12 = array[5]
self.m20 = array[6]
self.m21 = array[7]
self.m22 = array[8]
}
public init(var quaternion: Quaternion) {
quaternion = quaternion.normalize()
let x = quaternion.x
let y = quaternion.y
let z = quaternion.z
let w = quaternion.w
let _2x = x + x
let _2y = y + y
let _2z = z + z
let _2w = w + w
self.m00 = 1.0 - _2y * y - _2z * z
self.m01 = _2x * y + _2w * z
self.m02 = _2x * z - _2w * y
self.m10 = _2x * y - _2w * z
self.m11 = 1.0 - _2x * x - _2z * z
self.m12 = _2y * z + _2w * x
self.m20 = _2x * z + _2w * y
self.m21 = _2y * z - _2w * x
self.m22 = 1.0 - _2x * x - _2y * y
}
public init(scaleX: Float, scaleY: Float, scaleZ: Float) {
self = Matrix3.identity
self.m00 = scaleX
self.m11 = scaleY
self.m22 = scaleZ
}
public init(rotationAngle radians: Float, axisX x: Float, axisY y: Float, axisZ z: Float) {
let v = Vector3(x, y, z).normalize()
let _cos = cos(radians)
let _cosp = 1.0 - _cos
let _sin = sin(radians)
self = Matrix3.identity
self.m00 = _cos + _cosp * v.x * v.x
self.m01 = _cosp * v.x * v.y + v.z * _sin
self.m02 = _cosp * v.x * v.z - v.y * _sin
self.m10 = _cosp * v.x * v.y - v.z * _sin
self.m11 = _cos + _cosp * v.y * v.y
self.m12 = _cosp * v.y * v.z + v.x * _sin
self.m20 = _cosp * v.x * v.z + v.y * _sin
self.m21 = _cosp * v.y * v.z - v.y * _sin
self.m22 = _cos + _cosp * v.z * v.z
}
public init(rotationAngleAroundX radians: Float) {
let _cos = cos(radians)
let _sin = sin(radians)
self = Matrix3.identity
self.m11 = _cos
self.m12 = _sin
self.m21 = -_sin
self.m22 = _cos
}
public init(rotationAngleAroundY radians: Float) {
let _cos = cos(radians)
let _sin = sin(radians)
self = Matrix3.identity
self.m22 = _cos
self.m20 = _sin
self.m02 = -_sin
self.m00 = _cos
}
public init(rotationAngleAroundZ radians: Float) {
let _cos = cos(radians)
let _sin = sin(radians)
self = Matrix3.identity
self.m00 = _cos
self.m01 = _sin
self.m10 = -_sin
self.m11 = _cos
}
}
//
// MARK: - Property accessors -
//
public extension Matrix3 { // Property getters
// Array property
public subscript (index: Int) -> Float {
assert(index >= 0 && index < 9, "Index must be in the range 0...8")
switch index {
case 0:
return self.m00
case 1:
return self.m01
case 2:
return self.m02
case 3:
return self.m10
case 4:
return self.m11
case 5:
return self.m12
case 6:
return self.m20
case 7:
return self.m21
case 8:
return self.m22
default:
fatalError("Index out of bounds accessing Matrix3")
}
}
// 2D Array property
public subscript (index: (x:Int, y:Int)) -> Float {
assert(index.x >= 0 && index.x < 3 && index.y >= 0 && index.y < 3, "Index must be in the range 0...2")
switch index {
case (0,0):
return self.m00
case (0,1):
return self.m01
case (0,2):
return self.m02
case (1,0):
return self.m10
case (1,1):
return self.m11
case (1,2):
return self.m12
case (2,0):
return self.m20
case (2,1):
return self.m21
case (2,2):
return self.m22
default:
fatalError("Index out of bounds accessing Matrix3")
}
}
}
//
// MARK: - Methods -
//
public extension Matrix3 {
public func transposed() -> Matrix3 {
return Matrix3(self.m00, self.m10, self.m20, self.m01, self.m11, self.m21, self.m02, self.m12, self.m22)
}
public func inverse() -> Matrix3? {
var inverse = Array<Float>(count: 9, repeatedValue: 0.0)
inverse[0] = self.m11 * self.m22 - self.m12 * self.m21
inverse[3] = self.m12 * self.m20 - self.m10 * self.m22
inverse[6] = self.m10 * self.m21 - self.m11 * self.m20
let det: Float = self.m00 * inverse[0] + self.m01 * inverse[3] + self.m02 * inverse[6]
if abs(det) < 1e-14 {
return nil
}
let invDet = 1.0 / det
inverse[1] = self.m02 * self.m21 - self.m01 * self.m22
inverse[2] = self.m01 * self.m12 - self.m02 * self.m11
inverse[4] = self.m00 * self.m22 - self.m02 * self.m20
inverse[5] = self.m02 * self.m10 - self.m00 * self.m12
inverse[7] = self.m01 * self.m20 - self.m00 * self.m21
inverse[8] = self.m00 * self.m11 - self.m01 * self.m10
for i in 0..<9 {
inverse[i] = inverse[i] * invDet
}
return Matrix3(array: inverse)
}
public func matrix2() -> Matrix2 {
return Matrix2(self[0], self[1], self[3], self[4])
}
public func getRow(row: Int) -> Vector3 {
return Vector3(self[row], self[3 + row], self[6 + row])
}
public func getColumn(column: Int) -> Vector3 {
let columnOffset = column * 3
return Vector3(self[columnOffset + 0], self[columnOffset + 1], self[columnOffset + 2])
}
public func scaledBy(scaleX: Float, scaleY: Float, scaleZ: Float) -> Matrix3 {
return Matrix3(
self.m00 * scaleX, self.m01 * scaleX, self.m02 * scaleX,
self.m10 * scaleY, self.m11 * scaleY, self.m12 * scaleY,
self.m20 * scaleZ, self.m21 * scaleZ, self.m22 * scaleZ
)
}
public func scaledBy(vector: Vector3) -> Matrix3 {
return Matrix3(
self.m00 * vector.x, self.m01 * vector.x, self.m02 * vector.x,
self.m10 * vector.y, self.m11 * vector.y, self.m12 * vector.y,
self.m20 * vector.z, self.m21 * vector.z, self.m22 * vector.z
)
}
public func scaledBy(vector: Vector4) -> Matrix3 {
return Matrix3(
self.m00 * vector.x, self.m01 * vector.x, self.m02 * vector.x,
self.m10 * vector.y, self.m11 * vector.y, self.m12 * vector.y,
self.m20 * vector.z, self.m21 * vector.z, self.m22 * vector.z
)
}
public func rotatedBy(angle radians: Float, axisX: Float, axisY: Float, axisZ: Float) -> Matrix3 {
let rm = Matrix3(rotationAngle: radians, axisX: axisX, axisY: axisY, axisZ: axisZ)
return self * rm
}
public func rotatedBy(angle radians: Float, axisVector: Vector3) -> Matrix3 {
let rm = Matrix3(rotationAngle: radians, axisX: axisVector.x, axisY: axisVector.y, axisZ: axisVector.z)
return self * rm
}
public func rotatedBy(angle radians: Float, axisVector: Vector4) -> Matrix3 {
let rm = Matrix3(rotationAngle: radians, axisX: axisVector.x, axisY: axisVector.y, axisZ: axisVector.z)
return self * rm
}
public func rotatedAroundXBy(angle radians: Float) -> Matrix3 {
let rm = Matrix3(rotationAngleAroundX: radians)
return self * rm
}
public func rotatedAroundYBy(angle radians: Float) -> Matrix3 {
let rm = Matrix3(rotationAngleAroundY: radians)
return self * rm
}
public func rotatedAroundZBy(angle radians: Float) -> Matrix3 {
let rm = Matrix3(rotationAngleAroundZ: radians)
return self * rm
}
}
//
// MARK: - Operators -
//
public func + (lhs: Matrix3, rhs: Matrix3) -> Matrix3 {
var newValues: [Float] = Array(count: 9, repeatedValue: 0.0)
for i in 0..<9 {
newValues[i] = lhs[i] + rhs[i]
}
return Matrix3(array: newValues)
}
public func += (inout lhs: Matrix3, rhs: Matrix3) {
var newValues: [Float] = Array(count: 9, repeatedValue: 0.0)
for i in 0..<9 {
newValues[i] = lhs[i] + rhs[i]
}
lhs = Matrix3(array: newValues)
}
public func - (lhs: Matrix3, rhs: Matrix3) -> Matrix3 {
var newValues: [Float] = Array(count: 9, repeatedValue: 0.0)
for i in 0..<9 {
newValues[i] = lhs[i] - rhs[i]
}
return Matrix3(array: newValues)
}
public func -= (inout lhs: Matrix3, rhs: Matrix3) {
var newValues: [Float] = Array<Float>(count: 9, repeatedValue: 0.0)
for i in 0..<9 {
newValues[i] = lhs[i] - rhs[i]
}
lhs = Matrix3(array: newValues)
}
public func * (lhs: Matrix3, rhs: Matrix3) -> Matrix3 {
let _00: Float = lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01 + lhs.m20 * rhs.m02
let _01: Float = lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01 + lhs.m21 * rhs.m02
let _02: Float = lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01 + lhs.m22 * rhs.m02
let _10: Float = lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11 + lhs.m20 * rhs.m12
let _11: Float = lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11 + lhs.m21 * rhs.m12
let _12: Float = lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11 + lhs.m22 * rhs.m12
let _20: Float = lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21 + lhs.m20 * rhs.m22
let _21: Float = lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21 + lhs.m21 * rhs.m22
let _22: Float = lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21 + lhs.m22 * rhs.m22
return Matrix3(
_00, _01, _02,
_10, _11, _12,
_20, _21, _22
)
}
public func *= (inout lhs: Matrix3, rhs: Matrix3) {
let _00: Float = lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01 + lhs.m20 * rhs.m02
let _01: Float = lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01 + lhs.m21 * rhs.m02
let _02: Float = lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01 + lhs.m22 * rhs.m02
let _10: Float = lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11 + lhs.m20 * rhs.m12
let _11: Float = lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11 + lhs.m21 * rhs.m12
let _12: Float = lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11 + lhs.m22 * rhs.m12
let _20: Float = lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21 + lhs.m20 * rhs.m22
let _21: Float = lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21 + lhs.m21 * rhs.m22
let _22: Float = lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21 + lhs.m22 * rhs.m22
lhs = Matrix3(
_00, _01, _02,
_10, _11, _12,
_20, _21, _22
)
}
public func * (lhs: Matrix3, rhs: Vector3) -> Vector3 {
return Vector3(
lhs.m00 * rhs.x + lhs.m10 * rhs.y + lhs.m20 * rhs.z,
lhs.m01 * rhs.x + lhs.m11 * rhs.y + lhs.m21 * rhs.z,
lhs.m02 * rhs.x + lhs.m12 * rhs.y + lhs.m22 * rhs.z
)
}
public func * (lhs: Matrix3, inout rhs: [Vector3]) {
for i in 0 ..< rhs.count {
rhs[i] = lhs * rhs[i]
}
}
| mit | 0e8b5adbe81e8b35b8ecdf436d4da3e0 | 25.825193 | 140 | 0.610062 | 2.440365 | false | false | false | false |
practicalswift/swift | validation-test/compiler_crashers_2_fixed/0173-circular-generic-type-alias-deserialization.swift | 27 | 383 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-module-path %t/foo.swiftmodule %s
public protocol P { }
public struct X<T: P> {
public init() { }
}
public protocol Q {
associatedtype A: P
associatedtype C: Collection where C.Element == MyX
typealias MyX = X<A>
}
public struct Y: P { }
extension X: Q {
public typealias A = Y
public typealias C = [MyX]
}
| apache-2.0 | 7f4dc0abfc36b1473e7765c2785fc600 | 21.529412 | 67 | 0.663185 | 3.08871 | false | false | false | false |
edstewbob/cs193p-winter-2015 | SmashtagMentions/SmashtagMentions/User.swift | 2 | 2403 | //
// User.swift
// Twitter
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
// Modified 4/11/15 by jrm @ Riesam LLC to fix incompatibilities with Xcode 6.3
//
import Foundation
// container to hold data about a Twitter user
public struct User: Printable
{
//jrm removed 4/11/15
//public let screenName: String
//public let name: String
//public let profileImageURL: NSURL?
//public let verified: Bool = false
//public var verified: Bool = false
//public let id: String!
//jrm added 4/11/15
public var screenName: String
public var name: String
public var profileImageURL: NSURL?
public var verified: Bool = false
public var id: String!
public var description: String { var v = verified ? " ✅" : ""; return "@\(screenName) (\(name))\(v)" }
// MARK: - Private Implementation
init?(data: NSDictionary?) {
let name = data?.valueForKeyPath(TwitterKey.Name) as? String
let screenName = data?.valueForKeyPath(TwitterKey.ScreenName) as? String
if name != nil && screenName != nil {
self.name = name!
self.screenName = screenName!
self.id = data?.valueForKeyPath(TwitterKey.ID) as? String
if let verified = data?.valueForKeyPath(TwitterKey.Verified)?.boolValue {
self.verified = verified
}
if let urlString = data?.valueForKeyPath(TwitterKey.ProfileImageURL) as? String {
self.profileImageURL = NSURL(string: urlString)
}
} else {
return nil
}
}
var asPropertyList: AnyObject {
var dictionary = Dictionary<String,String>()
dictionary[TwitterKey.Name] = self.name
dictionary[TwitterKey.ScreenName] = self.screenName
dictionary[TwitterKey.ID] = self.id
dictionary[TwitterKey.Verified] = verified ? "YES" : "NO"
dictionary[TwitterKey.ProfileImageURL] = profileImageURL?.absoluteString
return dictionary
}
init() {
screenName = "Unknown"
name = "Unknown"
}
struct TwitterKey {
static let Name = "name"
static let ScreenName = "screen_name"
static let ID = "id_str"
static let Verified = "verified"
static let ProfileImageURL = "profile_image_url"
}
}
| mit | a05384ee7221af0ac23a59d0faf1297c | 30.181818 | 106 | 0.618492 | 4.48785 | false | false | false | false |
renshu16/DouyuSwift | DouyuSwift/DouyuSwift/Classes/Home/Controller/BaseAnchorContorller.swift | 1 | 4127 | //
// BaseAnchorContorller.swift
// DouyuSwift
//
// Created by ToothBond on 16/12/1.
// Copyright © 2016年 ToothBond. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
let kItemWidth : CGFloat = (kScreenW - 3 * kItemMargin)/2
let kNormalItemHeight : CGFloat = kItemWidth * 3/4
let kPrettyItemHeight : CGFloat = kItemWidth * 4/3
private let kHeaderHeight : CGFloat = 50
private let kCycleViewH = kScreenW * 3/8
private let kGameViewH : CGFloat = 90
private let kNormalCellIdentify : String = "kNormalCellIdentify"
let kPrettyCellIdentify : String = "kPrettyCellIdentify"
private let kHeaderIdentify : String = "kHeaderIdentify"
class BaseAnchorContorller: UIViewController {
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemWidth, height: kNormalItemHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderHeight)
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.delegate = self;
collectionView.dataSource = self;
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellIdentify)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellIdentify)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderIdentify)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
extension BaseAnchorContorller {
func setupUI() {
self.view.addSubview(collectionView)
}
func loadData() {
}
}
extension BaseAnchorContorller : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellIdentify, for: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderIdentify, for: indexPath) as! CollectionHeaderView
headerView.group = baseVM.anchorGroups[indexPath.section]
return headerView
}
}
extension BaseAnchorContorller : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let group : AnchorGroup = baseVM.anchorGroups[indexPath.section]
let model : AnchorModel = group.anchors[indexPath.item]
let roomVC = RoomController()
if model.isVertical == 0 {
navigationController?.pushViewController(roomVC, animated: true)
}else{
present(roomVC, animated: true, completion: nil)
}
}
}
| mit | d90d62e5bab2efaa237919cccc4cec05 | 35.175439 | 197 | 0.70805 | 5.626194 | false | false | false | false |
Antondomashnev/Sourcery | SourceryRuntime/Sources/Variable.swift | 1 | 6372 | //
// Created by Krzysztof Zablocki on 13/09/2016.
// Copyright (c) 2016 Pixle. All rights reserved.
//
import Foundation
public typealias SourceryVariable = Variable
/// Defines variable
public final class Variable: NSObject, SourceryModel, Typed, Annotated, Definition {
/// Variable name
public let name: String
/// Variable type name
public let typeName: TypeName
// sourcery: skipEquality, skipDescription
/// Variable type, if known
public var type: Type?
/// Whether variable is computed
public let isComputed: Bool
/// Whether variable is static
public let isStatic: Bool
/// Variable read access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open`
public let readAccess: String
/// Variable write access, i.e. `internal`, `private`, `fileprivate`, `public`, `open`.
/// For immutable variables this value is empty string
public let writeAccess: String
/// Whether variable is mutable or not
public var isMutable: Bool {
return writeAccess != AccessLevel.none.rawValue
}
/// Variable default value expression
public var defaultValue: String?
/// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2
public var annotations: [String: NSObject] = [:]
/// Variable attributes, i.e. `@IBOutlet`, `@IBInspectable`
public var attributes: [String: Attribute]
/// Whether variable is final or not
public var isFinal: Bool {
return attributes[Attribute.Identifier.final.name] != nil
}
/// Reference to type name where the variable is defined,
/// nil if defined outside of any `enum`, `struct`, `class` etc
public let definedInTypeName: TypeName?
/// Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a `definedInTypeName`
public var actualDefinedInTypeName: TypeName? {
return definedInTypeName?.actualTypeName ?? definedInTypeName
}
// sourcery: skipEquality, skipDescription
/// Reference to actual type where the object is defined,
/// nil if defined outside of any `enum`, `struct`, `class` etc or type is unknown
public var definedInType: Type?
// Underlying parser data, never to be used by anything else
// sourcery: skipEquality, skipDescription, skipCoding, skipJSExport
/// :nodoc:
public var __parserData: Any?
/// :nodoc:
public init(name: String = "",
typeName: TypeName,
type: Type? = nil,
accessLevel: (read: AccessLevel, write: AccessLevel) = (.internal, .internal),
isComputed: Bool = false,
isStatic: Bool = false,
defaultValue: String? = nil,
attributes: [String: Attribute] = [:],
annotations: [String: NSObject] = [:],
definedInTypeName: TypeName? = nil) {
self.name = name
self.typeName = typeName
self.type = type
self.isComputed = isComputed
self.isStatic = isStatic
self.defaultValue = defaultValue
self.readAccess = accessLevel.read.rawValue
self.writeAccess = accessLevel.write.rawValue
self.attributes = attributes
self.annotations = annotations
self.definedInTypeName = definedInTypeName
}
// sourcery:inline:Variable.AutoCoding
/// :nodoc:
required public init?(coder aDecoder: NSCoder) {
guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name
guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName
self.type = aDecoder.decode(forKey: "type")
self.isComputed = aDecoder.decode(forKey: "isComputed")
self.isStatic = aDecoder.decode(forKey: "isStatic")
guard let readAccess: String = aDecoder.decode(forKey: "readAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["readAccess"])); fatalError() }; self.readAccess = readAccess
guard let writeAccess: String = aDecoder.decode(forKey: "writeAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["writeAccess"])); fatalError() }; self.writeAccess = writeAccess
self.defaultValue = aDecoder.decode(forKey: "defaultValue")
guard let annotations: [String: NSObject] = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations
guard let attributes: [String: Attribute] = aDecoder.decode(forKey: "attributes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["attributes"])); fatalError() }; self.attributes = attributes
self.definedInTypeName = aDecoder.decode(forKey: "definedInTypeName")
self.definedInType = aDecoder.decode(forKey: "definedInType")
}
/// :nodoc:
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.typeName, forKey: "typeName")
aCoder.encode(self.type, forKey: "type")
aCoder.encode(self.isComputed, forKey: "isComputed")
aCoder.encode(self.isStatic, forKey: "isStatic")
aCoder.encode(self.readAccess, forKey: "readAccess")
aCoder.encode(self.writeAccess, forKey: "writeAccess")
aCoder.encode(self.defaultValue, forKey: "defaultValue")
aCoder.encode(self.annotations, forKey: "annotations")
aCoder.encode(self.attributes, forKey: "attributes")
aCoder.encode(self.definedInTypeName, forKey: "definedInTypeName")
aCoder.encode(self.definedInType, forKey: "definedInType")
}
// sourcery:end
}
| mit | 56973f08c1b8bfb3f4b8e3b9e312077f | 47.641221 | 274 | 0.66447 | 4.776612 | false | false | false | false |
ZhiQiang-Yang/pppt | v2exProject 2/Pods/SwiftDate/Sources/SwiftDate/DateInRegion+Operations.swift | 6 | 5397 | //
// SwiftDate, an handy tool to manage date and timezones in swift
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Operators
public extension DateInRegion {
/// Returns, as an NSDateComponents object using specified components, the difference between
/// the receiver and the supplied date.
///
/// - Parameters:
/// - toDate: a date to calculate against
/// - unitFlags: Specifies the components for the returned NSDateComponents object
///
/// - Returns: An NSDateComponents object whose components are specified by unitFlags and
/// calculated from the difference between the resultDate and startDate.
///
/// - note: This value is calculated in the context of the calendar of the receiver
///
public func difference(toDate: DateInRegion, unitFlags: NSCalendarUnit) -> NSDateComponents? {
return calendar.components(unitFlags, fromDate: self.absoluteTime,
toDate: toDate.absoluteTime, options: NSCalendarOptions(rawValue: 0))
}
public func add(years years: Int? = nil, months: Int? = nil, weeks: Int? = nil,
days: Int? = nil, hours: Int? = nil, minutes: Int? = nil, seconds: Int? = nil,
nanoseconds: Int? = nil) -> DateInRegion {
let components = NSDateComponents()
components.year = years ?? NSDateComponentUndefined
components.month = months ?? NSDateComponentUndefined
components.weekOfYear = weeks ?? NSDateComponentUndefined
components.day = days ?? NSDateComponentUndefined
components.hour = hours ?? NSDateComponentUndefined
components.minute = minutes ?? NSDateComponentUndefined
components.second = seconds ?? NSDateComponentUndefined
components.nanosecond = nanoseconds ?? NSDateComponentUndefined
let newDate = self.add(components)
return newDate
}
public func add(components: NSDateComponents) -> DateInRegion {
let absoluteTime = region.calendar.dateByAddingComponents(components,
toDate: self.absoluteTime, options: NSCalendarOptions(rawValue: 0))!
return DateInRegion(absoluteTime: absoluteTime, region: self.region)
}
public func add(components dict: [NSCalendarUnit : AnyObject]) -> DateInRegion {
let components = dict.components()
return self.add(components)
}
}
/// Returns a new DateInRegion object representing a new time calculated by subtracting given right
/// hand components from the left hand date.
///
/// - Parameters:
/// - lhs: the date to subtract components from
/// - rhs: the components to subtract from the date
///
/// - Returns: A new DateInRegion object representing the time calculated by subtracting from date
/// the calendrical components specified by components.
///
/// - note: This value is calculated in the context of the calendar of the date
///
public func - (lhs: DateInRegion, rhs: NSDateComponents) -> DateInRegion {
return lhs + (-rhs)
}
/// Returns a new DateInRegion object representing a new time calculated by adding given right hand
/// components to the left hand date.
///
/// - Parameters:
/// - lhs: the date to add the components to
/// - rhs: the components to add to the date
///
/// - Returns: A new DateInRegion object representing the time calculated by adding to date the
/// calendrical components specified by components.
///
/// - note: This value is calculated in the context of the calendar of the date
///
public func + (lhs: DateInRegion, rhs: NSDateComponents) -> DateInRegion {
return lhs.add(rhs)
}
/// Returns a new NSDateComponents object representing the negative values of components that are
/// submitted
///
/// - Parameters:
/// - dateComponents: the components to process
///
/// - Returns: A new NSDateComponents object representing the negative values of components that
/// are submitted
///
public prefix func - (dateComponents: NSDateComponents) -> NSDateComponents {
let result = NSDateComponents()
for unit in DateInRegion.componentFlagSet {
let value = dateComponents.valueForComponent(unit)
if value != Int(NSDateComponentUndefined) {
result.setValue(-value, forComponent: unit)
}
}
return result
}
| apache-2.0 | 6458b30858998844a773dbf31186817c | 40.515385 | 99 | 0.71058 | 4.853417 | false | false | false | false |
TarangKhanna/Inspirator | WorkoutMotivation/MKColor.swift | 26 | 1609 | //
// MKColor.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
extension UIColor {
convenience public init(hex: Int, alpha: CGFloat = 1.0) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
let blue = CGFloat((hex & 0xFF)) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
public struct MKColor {
public static let Red = UIColor(hex: 0xF44336)
public static let Pink = UIColor(hex: 0xE91E63)
public static let Purple = UIColor(hex: 0x9C27B0)
public static let DeepPurple = UIColor(hex: 0x67AB7)
public static let Indigo = UIColor(hex: 0x3F51B5)
public static let Blue = UIColor(hex: 0x2196F3)
public static let LightBlue = UIColor(hex: 0x03A9F4)
public static let Cyan = UIColor(hex: 0x00BCD4)
public static let Teal = UIColor(hex: 0x009688)
public static let Green = UIColor(hex: 0x4CAF50)
public static let LightGreen = UIColor(hex: 0x8BC34A)
public static let Lime = UIColor(hex: 0xCDDC39)
public static let Yellow = UIColor(hex: 0xFFEB3B)
public static let Amber = UIColor(hex: 0xFFC107)
public static let Orange = UIColor(hex: 0xFF9800)
public static let DeepOrange = UIColor(hex: 0xFF5722)
public static let Brown = UIColor(hex: 0x795548)
public static let Grey = UIColor(hex: 0x9E9E9E)
public static let BlueGrey = UIColor(hex: 0x607D8B)
}
}
| apache-2.0 | 973e6f0ccec347f3f4758785698edeb8 | 39.225 | 63 | 0.648229 | 3.373166 | false | false | false | false |
tranhieutt/Swiftz | Swiftz/JSONKeypath.swift | 1 | 1166 | //
// JSONKeypath.swift
// Swiftz
//
// Created by Robert Widmann on 1/29/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// Represents a subscript into a nested set of dictionaries. When used in conjunction with the
/// JSON decoding machinery, this class can be used to combine strings into keypaths to target
/// values inside nested JSON objects.
public struct JSONKeypath : StringLiteralConvertible {
public typealias StringLiteralType = String
public let path : [String]
public init(_ path : [String]) {
self.path = path
}
public init(unicodeScalarLiteral value : UnicodeScalar) {
self.path = ["\(value)"]
}
public init(extendedGraphemeClusterLiteral value : String) {
self.path = [value]
}
public init(stringLiteral value : String) {
self.path = [value]
}
}
extension JSONKeypath : Monoid {
public static var mempty : JSONKeypath {
return JSONKeypath([])
}
public func op(other : JSONKeypath) -> JSONKeypath {
return JSONKeypath(self.path + other.path)
}
}
extension JSONKeypath : CustomStringConvertible {
public var description : String {
return self.path.intersperse(".").reduce("", combine: +)
}
}
| bsd-3-clause | b4f57be8e18feaa6e2dc52c8f14b6133 | 23.291667 | 96 | 0.714408 | 3.810458 | false | false | false | false |
akane/Gaikan | GaikanTests/UIKit/Renderer/ConstraintRendererSpec.swift | 1 | 1905 | //
// ConstraintRendererSpec.swift
// Gaikan
//
// Created by pjechris on 10/09/16.
// Copyright © 2016 fr.akane. All rights reserved.
//
import Foundation
import Nimble
import Quick
@testable import Gaikan
class ConstraintRendererSpec : QuickSpec {
override func spec() {
var view: UIView!
beforeEach {
view = UIView()
}
describe("render") {
var style: StyleRule!
context("style") {
beforeEach {
style = StyleRule()
style.width = 42
ConstraintRenderer.render(view, styleRule: style)
}
it("adds constraint") {
expect(view.constraints.count) == 1
}
context("changed") {
var newStyle = StyleRule()
beforeEach {
newStyle.width = 32
ConstraintRenderer.render(view, styleRule: newStyle)
}
it("keeps constraint") {
expect(view.constraints.count) == 1
}
it("applies changed constraint") {
expect(view.constraints.first?.constant) == CGFloat(newStyle.width!.constant)
}
}
context("removed") {
beforeEach {
ConstraintRenderer.render(view, styleRule: StyleRule())
}
it("removes constraint") {
expect(view.constraints.count) == 0
}
}
}
context("removed constraint") {
beforeEach {
style = StyleRule()
style.width = 50
}
}
}
}
}
| mit | a303e4a3ef0095161f4846e14707b0f4 | 23.410256 | 101 | 0.428046 | 5.700599 | false | false | false | false |
manavgabhawala/swift | test/Parse/invalid.swift | 4 | 8219 | // RUN: %target-typecheck-verify-swift
func foo(_ a: Int) {
// expected-error @+1 {{invalid character in source file}} {{8-9= }}
foo(<\a\>) // expected-error {{invalid character in source file}} {{10-11= }}
// expected-error @-1 {{'<' is not a prefix unary operator}}
// expected-error @-2 {{'>' is not a postfix unary operator}}
}
// rdar://15946844
func test1(inout var x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}}
// expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{12-17=}} {{26-26=inout }}
func test2(inout let x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}}
// expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{12-17=}} {{26-26=inout }}
func test3(f : (inout _ x : Int) -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}
func test3() {
undeclared_func( // expected-error {{use of unresolved identifier 'undeclared_func'}}
} // expected-error {{expected expression in list of expressions}}
func runAction() {} // expected-note {{did you mean 'runAction'?}}
// rdar://16601779
func foo() {
runAction(SKAction.sequence() // expected-error {{use of unresolved identifier 'SKAction'}} expected-error {{expected ',' separator}} {{32-32=,}}
skview!
// expected-error @-1 {{use of unresolved identifier 'skview'}}
}
super.init() // expected-error {{'super' cannot be used outside of class members}}
switch state { // expected-error {{use of unresolved identifier 'state'}}
let duration : Int = 0 // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}}
case 1:
break
}
func testNotCoveredCase(x: Int) {
switch x {
let y = "foo" // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}}
switch y {
case "bar":
blah blah // ignored
}
case "baz": // expected-error {{expression pattern of type 'String' cannot match values of type 'Int'}}
break
case 1:
break
default:
break
}
switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}}
#if true // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}}
case 1:
break
case "foobar": // ignored
break
default:
break
#endif
}
}
// rdar://18926814
func test4() {
let abc = 123
_ = " >> \( abc } ) << " // expected-error {{expected ',' separator}} {{18-18=,}} expected-error {{expected expression in list of expressions}} expected-error {{extra tokens after interpolated string expression}}
}
// rdar://problem/18507467
func d(_ b: String -> <T>() -> T) {} // expected-error {{expected type for function result}}
// <rdar://problem/22143680> QoI: terrible diagnostic when trying to form a generic protocol
protocol Animal<Food> { // expected-error {{protocols do not allow generic parameters; use associated types instead}}
func feed(_ food: Food) // expected-error {{use of undeclared type 'Food'}}
}
// SR-573 - Crash with invalid parameter declaration
class Starfish {}
struct Salmon {}
func f573(s Starfish, // expected-error {{parameter requires an explicit type}}
_ ss: Salmon) -> [Int] {}
func g573() { f573(Starfish(), Salmon()) }
func SR698(_ a: Int, b: Int) {}
SR698(1, b: 2,) // expected-error {{unexpected ',' separator}}
// SR-979 - Two inout crash compiler
func SR979a(a : inout inout Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}}
func SR979b(inout inout b: Int) {} // expected-error {{inout' before a parameter name is not allowed, place it before the parameter type instead}} {{13-18=}} {{28-28=inout }}
// expected-error@-1 {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{19-25=}}
func SR979c(let a: inout Int) {} // expected-error {{'let' as a parameter attribute is not allowed}} {{13-16=}}
func SR979d(let let a: Int) {} // expected-error {{'let' as a parameter attribute is not allowed}} {{13-16=}}
// expected-error @-1 {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-21=}}
func SR979e(inout x: inout String) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{13-18=}}
func SR979f(var inout x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}}
// expected-error @-1 {{parameters may not have the 'var' specifier}} {{13-16=}}{{3-3=var x = x\n }}
x += 10
}
func SR979g(inout i: inout Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{13-18=}}
func SR979h(let inout x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}}
// expected-error @-1 {{'let' as a parameter attribute is not allowed}}
class VarTester {
init(var a: Int, var b: Int) {} // expected-error {{parameters may not have the 'var' specifier}} {{8-11=}} {{33-33= var a = a }}
// expected-error @-1 {{parameters may not have the 'var' specifier}} {{20-24=}} {{33-33= var b = b }}
func x(var b: Int) { //expected-error {{parameters may not have the 'var' specifier}} {{12-15=}} {{9-9=var b = b\n }}
b += 10
}
}
func repeat() {}
// expected-error @-1 {{keyword 'repeat' cannot be used as an identifier here}}
// expected-note @-2 {{if this name is unavoidable, use backticks to escape it}} {{6-12=`repeat`}}
let for = 2
// expected-error @-1 {{keyword 'for' cannot be used as an identifier here}}
// expected-note @-2 {{if this name is unavoidable, use backticks to escape it}} {{5-8=`for`}}
func dog cow() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}}
// expected-note@-1 {{join the identifiers together}} {{6-13=dogcow}}
// expected-note@-2 {{join the identifiers together with camel-case}} {{6-13=dogCow}}
func cat Mouse() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}}
// expected-note@-1 {{join the identifiers together}} {{6-15=catMouse}}
func friend ship<T>(x: T) {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}}
// expected-note@-1 {{join the identifiers together}} {{6-17=friendship}}
// expected-note@-2 {{join the identifiers together with camel-case}} {{6-17=friendShip}}
func were
wolf() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}}
// expected-note@-1 {{join the identifiers together}} {{6-5=werewolf}}
// expected-note@-2 {{join the identifiers together with camel-case}} {{6-5=wereWolf}}
func hammer
leavings<T>(x: T) {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}}
// expected-note@-1 {{join the identifiers together}} {{6-9=hammerleavings}}
// expected-note@-2 {{join the identifiers together with camel-case}} {{6-9=hammerLeavings}}
prefix operator %
prefix func %<T>(x: T) -> T { return x } // No error expected - the < is considered an identifier but is peeled off by the parser.
struct Weak<T: class> { // expected-error {{'class' constraint can only appear on protocol declarations}}
// expected-note@-1 {{did you mean to constrain 'T' with the 'AnyObject' protocol?}} {{16-21=AnyObject}}
weak var value: T // expected-error {{'weak' may not be applied to non-class-bound 'T'; consider adding a protocol conformance that has a class bound}}
}
let x: () = ()
!() // expected-error {{missing argument for parameter #1 in call}}
!(()) // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}}
!(x) // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}}
!x // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}}
| apache-2.0 | e03b7bb22cfcf6cb575b1cc466df6466 | 52.37013 | 216 | 0.671128 | 3.679051 | false | false | false | false |
kzin/swift-testing | swift-testing/Pods/Mockingjay/Mockingjay/Builders.swift | 7 | 1719 | //
// Builders.swift
// Mockingjay
//
// Created by Kyle Fuller on 01/03/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import Foundation
// Collection of generic builders
/// Generic builder for returning a failure
public func failure(_ error: NSError) -> (_ request: URLRequest) -> Response {
return { _ in return .failure(error) }
}
public func http(_ status:Int = 200, headers:[String:String]? = nil, download:Download=nil) -> (_ request: URLRequest) -> Response {
return { (request:URLRequest) in
if let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: headers) {
return Response.success(response, download)
}
return .failure(NSError(domain: NSExceptionName.internalInconsistencyException.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to construct response for stub."]))
}
}
public func json(_ body: Any, status:Int = 200, headers:[String:String]? = nil) -> (_ request: URLRequest) -> Response {
return { (request:URLRequest) in
do {
let data = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions())
return jsonData(data, status: status, headers: headers)(request)
} catch {
return .failure(error as NSError)
}
}
}
public func jsonData(_ data: Data, status: Int = 200, headers: [String:String]? = nil) -> (_ request: URLRequest) -> Response {
return { (request:URLRequest) in
var headers = headers ?? [String:String]()
if headers["Content-Type"] == nil {
headers["Content-Type"] = "application/json; charset=utf-8"
}
return http(status, headers: headers, download: .content(data))(request)
}
}
| mit | a67beac880512804fb7bd10a1a4f4dda | 34.8125 | 183 | 0.685282 | 4.016355 | false | false | false | false |
everald/JetPack | Sources/Extensions/UIKit/UITableViewCell.swift | 1 | 8908 | import UIKit
/*
UITableViewCell's default layout is a bit inconsistent.
By default UITableView's cells are 44 point high (with and without separator).
But UITableViewCell's sizeThatFits(_:) returns a cell height of 44 (without separator) and 45 (with separator).
So as soon as you set the UITableView's .estimatedRowHeight the cells will become 1 point higher if they have a separator because sizeThatFits(_:) will now be used.
The separator is 0.5 point high on 2x scale and 0.3~ point high on 3x scale - yet sizeThatFits(_:) always returns an additional 1 point.
*/
public extension UITableViewCell {
fileprivate struct AssociatedKeys {
fileprivate static var predictedConfiguration = UInt8()
}
@objc(JetPack_contentHeightThatFitsWidth:defaultHeight:)
internal func contentHeightThatFitsWidth(_ width: CGFloat, defaultHeight: CGFloat) -> CGFloat {
return defaultHeight
}
@nonobjc
fileprivate func fallbackSizeThatFitsSize(_ maximumSize: CGSize) -> CGSize {
// Private API has changed :(
// So in the worst case we have to provide an acceptable fallback until the issue is resolved.
// @Apple, please make this easier to implement! We don't want to make our own UITableView just to implement manual layouting of UITableViewCells correctly…
layoutIfNeeded()
let contentFrame = contentView.frame
return sizeThatFitsContentWidth(contentFrame.width, cellWidth: maximumSize.width, defaultContentHeight: contentFrame.height)
}
@nonobjc
internal final func improvedSizeThatFitsSize(_ maximumSize: CGSize) -> CGSize {
guard let layoutManager = private_layoutManager, layoutManager.responds(to: #selector(LayoutManager.private_contentFrameForCell(_:editing:showingDeleteConfirmation:width:))) else {
// private property -[UITableViewCell layoutManager] was renamed, removed or changed type
return fallbackSizeThatFitsSize(maximumSize)
}
let editing: Bool
if let tableView = (superview as? UITableView) ?? (superview?.superview as? UITableView), let indexPath = tableView.indexPathForCurrentHeightComputation {
editing = tableView.isEditing
predictedConfiguration = PredictedConfiguration(
editing: editing,
editingStyle: tableView.delegate?.tableView?(tableView, editingStyleForRowAt: indexPath as IndexPath) ?? .delete,
shouldIndentWhileEditing: tableView.delegate?.tableView?(tableView, shouldIndentWhileEditingRowAt: indexPath as IndexPath) ?? true,
showsReorderControl: showsReorderControl && (tableView.dataSource?.tableView?(tableView, canMoveRowAt: indexPath as IndexPath) ?? false)
)
}
else {
editing = self.swizzled_isEditing
predictedConfiguration = nil
}
var contentFrame = layoutManager.private_contentFrameForCell(self, editing: editing, showingDeleteConfirmation: showingDeleteConfirmation, width: maximumSize.width)
predictedConfiguration = nil
guard !contentFrame.isNull else {
// Private method -[UITableViewCellLayoutManager _contentRectForCell:forEditingState:showingDeleteConfirmation:rowWidth:] was renamed or removed
return fallbackSizeThatFitsSize(maximumSize)
}
// finally we know how wide .contentView will be!
return sizeThatFitsContentWidth(contentFrame.width, cellWidth: maximumSize.width, defaultContentHeight: contentFrame.height)
}
@nonobjc
fileprivate var predictedConfiguration: PredictedConfiguration? {
get { return (objc_getAssociatedObject(self, &AssociatedKeys.predictedConfiguration) as? StrongReference<PredictedConfiguration>)?.value }
set { objc_setAssociatedObject(self, &AssociatedKeys.predictedConfiguration, newValue != nil ? StrongReference(newValue!) : nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
@objc(JetPack_layoutManager)
fileprivate dynamic var private_layoutManager: LayoutManager? {
// called only when private property was renamed or removed
return nil
}
@objc(JetPack_separatorStyle)
fileprivate dynamic var private_separatorStyle: UITableViewCell.SeparatorStyle {
// called only when private property was renamed or removed
return .singleLine
}
@nonobjc
fileprivate func sizeThatFitsContentWidth(_ contentWidth: CGFloat, cellWidth: CGFloat, defaultContentHeight: CGFloat) -> CGSize {
var cellHeight = contentHeightThatFitsWidth(contentWidth, defaultHeight: defaultContentHeight)
if private_separatorStyle != .none {
cellHeight += pointsForPixels(1)
}
cellHeight = ceilToGrid(cellHeight)
return CGSize(width: cellWidth, height: cellHeight)
}
@objc(JetPack_editingStyle)
fileprivate dynamic var swizzled_editingStyle: UITableViewCell.EditingStyle {
if let predictedConfiguration = predictedConfiguration {
return predictedConfiguration.editingStyle
}
return self.swizzled_editingStyle
}
@objc(JetPack_isEditing)
fileprivate dynamic var swizzled_isEditing: Bool {
if let predictedConfiguration = predictedConfiguration {
return predictedConfiguration.editing
}
return self.swizzled_isEditing
}
@objc(JetPack_shouldIndentWhileEditing)
fileprivate dynamic var swizzled_shouldIndentWhileEditing: Bool {
if let predictedConfiguration = predictedConfiguration {
return predictedConfiguration.shouldIndentWhileEditing
}
return self.swizzled_shouldIndentWhileEditing
}
@objc(JetPack_showsReorderControl)
fileprivate dynamic var swizzled_showsReorderControl: Bool {
if let predictedConfiguration = predictedConfiguration {
return predictedConfiguration.showsReorderControl
}
return self.swizzled_showsReorderControl
}
}
private final class LayoutManager: NSObject {
@objc(JetPack_contentFrameForCell:editing:showingDeleteConfirmation:width:)
fileprivate dynamic func private_contentFrameForCell(_ cell: UITableViewCell, editing: Bool, showingDeleteConfirmation: Bool, width: CGFloat) -> CGRect {
// called only when private method was renamed or removed
return .null
}
@nonobjc
fileprivate static func setUp() {
// yep, private API necessary :(
// UIKit doesn't let us properly implement our own sizeThatFits() in UITableViewCell subclasses because we're unable to determine the correct size of .contentView
guard let layoutManagerType = NSClassFromString(["UITableView", "Cell", "Layout", "Manager"].joined(separator: "")) else {
log("Integration with UITableViewCell's layout system does not work anymore.\nReport this at https://github.com/fluidsonic/JetPack/issues?q=contentHeightThatFitsWidth+broken")
return
}
copyMethod(selector: #selector(private_contentFrameForCell(_:editing:showingDeleteConfirmation:width:)), from: self, to: layoutManagerType)
redirectMethod(in: layoutManagerType,
from: #selector(private_contentFrameForCell(_:editing:showingDeleteConfirmation:width:)),
to: obfuscatedSelector("_", "content", "Rect", "For", "Cell:", "for", "Editing", "State:", "showingDeleteConfirmation:", "row", "Width:")
)
}
}
private struct PredictedConfiguration {
fileprivate var editing: Bool
fileprivate var editingStyle: UITableViewCell.EditingStyle
fileprivate var shouldIndentWhileEditing: Bool
fileprivate var showsReorderControl: Bool
}
extension UITableViewCell.EditingStyle: CustomDebugStringConvertible {
public var debugDescription: String {
return "UITableViewCellEditingStyle.\(description)"
}
}
extension UITableViewCell.EditingStyle: CustomStringConvertible {
public var description: String {
switch self {
case .delete: return "Delete"
case .insert: return "Insert"
case .none: return "None"
}
}
}
@objc(_JetPack_Extensions_UIKit_UITableViewCell_Initialization)
private class StaticInitialization: NSObject, StaticInitializable {
static func staticInitialize() {
swizzleMethod(in: UITableViewCell.self, from: #selector(getter: UITextField.isEditing), to: #selector(getter: UITableViewCell.swizzled_isEditing))
swizzleMethod(in: UITableViewCell.self, from: #selector(getter: UITableViewCell.editingStyle), to: #selector(getter: UITableViewCell.swizzled_editingStyle))
swizzleMethod(in: UITableViewCell.self, from: #selector(getter: UITableViewCell.shouldIndentWhileEditing), to: #selector(getter: UITableViewCell.swizzled_shouldIndentWhileEditing))
swizzleMethod(in: UITableViewCell.self, from: #selector(getter: UITableViewCell.showsReorderControl), to: #selector(getter: UITableViewCell.swizzled_showsReorderControl))
// yep, private API necessary :(
// UIKit doesn't let us properly implement our own sizeThatFits() in UITableViewCell subclasses because we're unable to determine the correct size of .contentView
redirectMethod(in: UITableViewCell.self, from: #selector(getter: UITableViewCell.private_layoutManager), to: obfuscatedSelector("layout", "Manager"))
redirectMethod(in: UITableViewCell.self, from: #selector(getter: UITableViewCell.private_separatorStyle), to: obfuscatedSelector("separator", "Style"))
LayoutManager.setUp()
}
}
| mit | 779af79e1969280eda040f65cf4b0de8 | 38.758929 | 182 | 0.782057 | 4.687368 | false | true | false | false |
herrkaefer/CaseAssistant | CaseAssistant/CaseProducts.swift | 1 | 1241 | //
// CaseProducts.swift
// CaseAssistant
//
// Created by HerrKaefer on 2017/5/18.
// Copyright © 2017年 HerrKaefer. All rights reserved.
//
// 内购. IAP products
import Foundation
public struct CaseProducts {
public static let unlimitedPatients = "casenote_unlimited_patients"
public static let maxPatientsForFreeUser = 5
fileprivate static let productIdentifiers: Set<ProductIdentifier> = [CaseProducts.unlimitedPatients]
public static let store = IAPHelper(productIds: CaseProducts.productIdentifiers)
}
func resourceNameForProductIdentifier(_ productIdentifier: String) -> String? {
return productIdentifier.components(separatedBy: ".").last
}
//// IAP
//static let productIDs: [String] = [
// "casenote_remove_ads",
// "casenote_unlimited_patients"
//]
//static let IAPPatientLimitation = 5
//
//static func productIsPurchased(_ productID: String) -> Bool {
// return UserDefaults.standard.bool(forKey: productID)
//}
//
//static var shouldRemoveADs: Bool {
// return UserDefaults.standard.bool(forKey: CaseAssistantApp.productIDs[0])
//}
//
//static var shouldUnlockPatientLimitation: Bool {
// return UserDefaults.standard.bool(forKey: CaseAssistantApp.productIDs[1])
//}
| mpl-2.0 | 92fd3024ea6b6bb9f7ba3e3fc323a3c6 | 26.422222 | 104 | 0.732577 | 3.942492 | false | false | false | false |
ParsePlatform/Parse-SDK-iOS-OSX | ParseStarterProject/tvOS/ParseStarterProject-Swift/ParseStarter/AppDelegate.swift | 1 | 1711 | /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import Parse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// ****************************************************************************
// Initialize Parse SDK
// ****************************************************************************
let configuration = ParseClientConfiguration {
// Add your Parse applicationId:
$0.applicationId = "your_application_id"
// Uncomment and add your clientKey (it's not required if you are using Parse Server):
$0.clientKey = "your_client_key"
// Uncomment the following line and change to your Parse Server address;
$0.server = "https://YOUR_PARSE_SERVER/parse"
}
Parse.initialize(with: configuration)
PFUser.enableAutomaticUser()
let defaultACL = PFACL()
defaultACL.getPublicReadAccess = true // If you would like all objects to be private by default, remove this line.
PFACL.setDefault(defaultACL, withAccessForCurrentUser: true)
return true
}
}
| bsd-3-clause | 752e4fede1077d0872950c58d21b28dd | 34.645833 | 144 | 0.579193 | 5.591503 | false | true | false | false |
cao903775389/MRCBaseLibrary | MRCBaseLibrary/Classes/MRCExtension/WebViewExtensions.swift | 1 | 1038 | //
// WebViewExtensions.swift
// Pods
//
// Created by 逢阳曹 on 2017/5/31.
//
//
import Foundation
import WebKit
//WebView设置请求头信息
extension WKWebView {
public func loadRequest(_ request: URL, requestHeaders: [String: String]? = nil) {
var muRequest = URLRequest(url: request)
guard requestHeaders != nil else {
self.load(muRequest)
return
}
for (key, value) in requestHeaders! {
muRequest.addValue(value, forHTTPHeaderField: key)
}
self.load(muRequest)
}
}
extension UIWebView {
public func loadRequest(_ request: URL, requestHeaders: [String: String]?) {
var muRequest = URLRequest(url: request)
guard requestHeaders != nil else {
self.loadRequest(muRequest)
return
}
for (key, value) in requestHeaders! {
muRequest.addValue(value, forHTTPHeaderField: key)
}
self.loadRequest(muRequest)
}
}
| mit | e1aeebd1244187329544ff18382060e5 | 21.622222 | 86 | 0.581532 | 4.387931 | false | false | false | false |
jessesquires/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0014.xcplaygroundpage/Contents.swift | 2 | 3264 | /*:
# Constraining `AnySequence.init`
* Proposal: [SE-0014](0014-constrained-AnySequence.md)
* Author: [Max Moiseev](https://github.com/moiseev)
* Review Manager: [Doug Gregor](https://github.com/DougGregor)
* Status: **Implemented (Swift 2.2)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-January/000008.html)
* Bug: [SR-474](https://bugs.swift.org/browse/SR-474)
## Introduction
In order to allow `AnySequence` delegate calls to the underlying sequence,
its initializer should have extra constraints.
[Swift Evolution Discussion](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/000910.html)
## Motivation
At the moment `AnySequence` does not delegate calls to `SequenceType` protocol
methods to the underlying base sequence, which results in dynamic downcasts in
places where this behavior is needed (see default implementations of
`SequenceType.dropFirst` or `SequenceType.prefix`). Besides, and this is even
more important, customized implementations of `SequenceType` methods would be
ignored without delegation.
## Proposed solution
See the implementation in [this PR](https://github.com/apple/swift/pull/220).
In order for this kind of delegation to become possible, `_SequenceBox` needs to
be able to 'wrap' not only the base sequence but also its associated
`SubSequence`. So instead of being declared like this:
~~~~Swift
internal class _SequenceBox<S : SequenceType>
: _AnySequenceBox<S.Generator.Element> { ... }
~~~~
it would become this:
~~~~Swift
internal class _SequenceBox<
S : SequenceType
where
S.SubSequence : SequenceType,
S.SubSequence.Generator.Element == S.Generator.Element,
S.SubSequence.SubSequence == S.SubSequence
> : _AnySequenceBox<S.Generator.Element> { ... }
~~~~
Which, in its turn, will lead to `AnySequence.init` getting a new set of
constraints as follows.
Before the change:
~~~~Swift
public struct AnySequence<Element> : SequenceType {
public init<
S: SequenceType
where
S.Generator.Element == Element
>(_ base: S) { ... }
}
~~~~
After the change:
~~~~Swift
public struct AnySequence<Element> : SequenceType {
public init<
S: SequenceType
where
S.Generator.Element == Element,
S.SubSequence : SequenceType,
S.SubSequence.Generator.Element == Element,
S.SubSequence.SubSequence == S.SubSequence
>(_ base: S) { ... }
}
~~~~
These constraints, in fact, should be applied to `SequenceType` protocol itself
(although, that is not currently possible), as we expect every `SequenceType`
implementation to satisfy them already. Worth mentioning that technically
`S.SubSequence.SubSequence == S.SubSequence` does not have to be this strict,
as any sequence with the same element type would do, but that is currently not
representable.
## Impact on existing code
New constraints do not affect any built-in types that conform to
`SequenceType` protocol as they are essentially constructed like this
(`SubSequence.SubSequence == SubSequence`). 3rd party collections, if they use
the default `SubSequence` (i.e. `Slice`), should also be fine. Those having
custom `SubSequence`s may stop conforming to the protocol.
----------
[Previous](@previous) | [Next](@next)
*/
| mit | 067fd115ff0fdb8a5d34bbe63f92d197 | 31 | 114 | 0.741115 | 4.009828 | false | false | false | false |
AlvinL33/TownHunt | TownHunt/DatabaseInteraction.swift | 2 | 2266 | //
// DatabaseInteraction.swift
// TownHunt
//
// Created by Alvin Lee on 15/02/2017.
// Copyright © 2017 LeeTech. All rights reserved.
//
import UIKit
import SystemConfiguration
class DatabaseInteraction: NSObject {
let mainSQLServerURLStem = "http://alvinlee.london/TownHunt/api"
func connectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
func postToDatabase(apiName :String, postData: String, completion: @escaping (NSDictionary)->Void){
let apiURL = URL(string: mainSQLServerURLStem + "/" + apiName + "/")
var request = URLRequest(url: apiURL!)
request.httpMethod = "POST"
print(postData)
request.httpBody = postData.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
print("response = \(response)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let jsonDicationary = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
completion(jsonDicationary!)
}
catch {
print(error)
}
}
task.resume()
}
}
| apache-2.0 | 75b5c9c3434d31995bdd0aaafa30fa9a | 31.357143 | 129 | 0.579249 | 5.055804 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/PollutedGarden/Plant/Abstract/MOptionPollutedGardenPlant.swift | 1 | 3311 | import UIKit
class MOptionPollutedGardenPlant:MGameUpdate<MOptionPollutedGarden>
{
private var items:[MOptionPollutedGardenPlantItem]
private var collect:[MOptionPollutedGardenPlantCollect]
private var poison:[MOptionPollutedGardenPlantPoison]
private let animations:MOptionPollutedGardenPlantAnimations
private let position:MOptionPollutedGardenPlantPosition
override init()
{
position = MOptionPollutedGardenPlantPosition()
animations = MOptionPollutedGardenPlantAnimations()
items = []
collect = []
poison = []
super.init()
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionPollutedGarden>)
{
for item:MOptionPollutedGardenPlantItem in items
{
item.update(
elapsedTime:elapsedTime,
scene:scene)
}
for item:MOptionPollutedGardenPlantCollect in collect
{
item.update(
elapsedTime:elapsedTime,
scene:scene)
}
for item:MOptionPollutedGardenPlantPoison in poison
{
item.update(
elapsedTime:elapsedTime,
scene:scene)
}
}
//MARK: public
func factoryAnimations(
actions:MOptionPollutedGardenActions,
textures:MOptionPollutedGardenTextures)
{
animations.factoryAnimations(
actions:actions,
textures:textures)
}
func restart()
{
let positions:[CGFloat] = position.randomPositions()
var items:[MOptionPollutedGardenPlantItem] = []
for position:CGFloat in positions
{
let item:MOptionPollutedGardenPlantItem = MOptionPollutedGardenPlantItem(
animations:animations,
positionX:position)
items.append(item)
}
self.items = items
poison = []
collect = []
}
func collectStart(plantItem:MOptionPollutedGardenPlantItem)
{
let collectItem:MOptionPollutedGardenPlantCollect = MOptionPollutedGardenPlantCollect(
plantItem:plantItem)
collect.append(collectItem)
}
func collectFinished(collectItem:MOptionPollutedGardenPlantCollect)
{
var items:[MOptionPollutedGardenPlantCollect] = []
for item:MOptionPollutedGardenPlantCollect in collect
{
if item !== collectItem
{
items.append(item)
}
}
collect = items
}
func poisonStart(plantItem:MOptionPollutedGardenPlantItem)
{
let poisonItem:MOptionPollutedGardenPlantPoison = MOptionPollutedGardenPlantPoison(
plantItem:plantItem)
poison.append(poisonItem)
plantItem.polluted()
}
func poisonFinished(poisonItem:MOptionPollutedGardenPlantPoison)
{
var items:[MOptionPollutedGardenPlantPoison] = []
for item:MOptionPollutedGardenPlantPoison in poison
{
if item !== poisonItem
{
items.append(item)
}
}
poison = items
}
}
| mit | 46e0a03305c03643aa171de59362facc | 26.139344 | 94 | 0.596497 | 5.738302 | false | false | false | false |
csujedihy/Flicks | Pods/Cosmos/Cosmos/CosmosDefaultSettings.swift | 3 | 2685 | import UIKit
/**
Defaults setting values.
*/
struct CosmosDefaultSettings {
init() {}
static let defaultColor = UIColor(red: 1, green: 149/255, blue: 0, alpha: 1)
// MARK: - Star settings
// -----------------------------
/// Border color of an empty star.
static let borderColorEmpty = defaultColor
/// Width of the border for the empty star.
static let borderWidthEmpty: Double = 1 / Double(UIScreen.mainScreen().scale)
/// Background color of an empty star.
static let colorEmpty = UIColor.clearColor()
/// Background color of a filled star.
static let colorFilled = defaultColor
/**
Defines how the star is filled when the rating value is not an integer value. It can either show full stars, half stars or stars partially filled according to the rating value.
*/
static let fillMode = StarFillMode.Full
/// Rating value that is shown in the storyboard by default.
static let rating: Double = 2.718281828
/// Distance between stars.
static let starMargin: Double = 5
/**
Array of points for drawing the star with size of 100 by 100 pixels. Supply your points if you need to draw a different shape.
*/
static let starPoints: [CGPoint] = [
CGPoint(x: 49.5, y: 0.0),
CGPoint(x: 60.5, y: 35.0),
CGPoint(x: 99.0, y: 35.0),
CGPoint(x: 67.5, y: 58.0),
CGPoint(x: 78.5, y: 92.0),
CGPoint(x: 49.5, y: 71.0),
CGPoint(x: 20.5, y: 92.0),
CGPoint(x: 31.5, y: 58.0),
CGPoint(x: 0.0, y: 35.0),
CGPoint(x: 38.5, y: 35.0)
]
/// Size of a single star.
static var starSize: Double = 20
/// The total number of stars to be shown.
static let totalStars = 5
// MARK: - Text settings
// -----------------------------
/// Color of the text.
static let textColor = UIColor(red: 127/255, green: 127/255, blue: 127/255, alpha: 1)
/// Font for the text.
static let textFont = UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote)
/// Distance between the text and the stars.
static let textMargin: Double = 5
/// Calculates the size of the default text font. It is used for making the text size configurable from the storyboard.
static var textSize: Double {
get {
return Double(textFont.pointSize)
}
}
// MARK: - Touch settings
// -----------------------------
/// The lowest rating that user can set by touching the stars.
static let minTouchRating: Double = 1
/// When `true` the star fill level is updated when user touches the cosmos view. When `false` the Cosmos view only shows the rating and does not act as the input control.
static let updateOnTouch = true
}
| gpl-3.0 | 2ef3ffb8870dfb243dbc24a032fa9522 | 26.680412 | 178 | 0.636499 | 3.989599 | false | false | false | false |
UnivexDont/UDCornerTagView | UDCornerTagView/UDTableViewCell.swift | 1 | 1445 | //
// UDTableViewCell.swift
// UDCornerTagView
//
// Created by JMan on 01/08/2017.
// Copyright © 2017 UnivexDont. All rights reserved.
//
import UIKit
class UDTableViewCell: UITableViewCell {
let leftCornerView = UDCornerTagView.init(maxX: 100, lableHeight: 30)
let rightCornerView = UDCornerTagView.init(maxX: 100, lableHeight: 30 , style: .right)
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(leftCornerView)
contentView.addSubview(rightCornerView)
leftCornerView.text = "Left"
rightCornerView.text = "Right"
leftCornerView.textColor = .white
rightCornerView.textColor = .white
leftCornerView.backgroundColor = UIColor.magenta
leftCornerView.lableBackgroudColor = UIColor.green
rightCornerView.backgroundColor = UIColor.orange
rightCornerView.lableBackgroudColor = UIColor.brown
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 1c1e846de57a77d0ee7178d3dd5a8466 | 29.083333 | 90 | 0.677285 | 4.781457 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV2/Models/ProjectDetails.swift | 1 | 2694 | /**
* (C) Copyright IBM Corp. 2020.
*
* 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
/**
Detailed information about the specified project.
*/
public struct ProjectDetails: Codable, Equatable {
/**
The type of project.
The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom*
project.
The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and
installed deployments only.
*/
public enum TypeEnum: String {
case documentRetrieval = "document_retrieval"
case conversationalSearch = "conversational_search"
case contentMining = "content_mining"
case contentIntelligence = "content_intelligence"
case other = "other"
}
/**
The unique identifier of this project.
*/
public var projectID: String?
/**
The human readable name of this project.
*/
public var name: String?
/**
The type of project.
The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom*
project.
The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and
installed deployments only.
*/
public var type: String?
/**
Relevancy training status information for this project.
*/
public var relevancyTrainingStatus: ProjectListDetailsRelevancyTrainingStatus?
/**
The number of collections configured in this project.
*/
public var collectionCount: Int?
/**
Default query parameters for this project.
*/
public var defaultQueryParameters: DefaultQueryParams?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case projectID = "project_id"
case name = "name"
case type = "type"
case relevancyTrainingStatus = "relevancy_training_status"
case collectionCount = "collection_count"
case defaultQueryParameters = "default_query_parameters"
}
}
| apache-2.0 | c6ae5a33fb5fbd34d213fa7ebf7faeb8 | 31.457831 | 119 | 0.691908 | 4.535354 | false | false | false | false |
JRG-Developer/ObservableType | ObservableType/Library/Observable+Equatable.swift | 1 | 5120 | //
// Observable+Equatable.swift
// ObservableType
//
// Created by Joshua Greene on 8/22/16.
// Copyright © 2016 Joshua Greene. 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.
// MARK: - Equatable
extension Observable where Type: Equatable {
/// Use this property to get the underlying value in a thread-safe manner.
public var value: Type {
return synchronizedValue.get()
}
/// Use this function to set the value in a thread-safe manner.
///
/// - Parameter closure: The closure to provide the new value
/// - Returns: `true` if the value is different (not equatable) and was set or `false` otherwise
@discardableResult public func setValue(closure: () -> (Type)) -> Bool {
var valueChanged = false
synchronizedValue.set { backingValue in
let newValue = closure()
guard newValue != backingValue else { return }
setUnsafeValue(backingValue: &backingValue, oldValue: backingValue, newValue: newValue)
valueChanged = true
}
return valueChanged
}
}
// MARK: - Optional Equatable
extension Observable where Type: OptionalConvertible, Type.WrappedValueType: Equatable {
/// Use this property to get the underlying value in a thread-safe manner.
public var value: Type {
return synchronizedValue.get()
}
/// Use this function to set the value in a thread-safe manner.
///
/// - Parameter closure: The closure to provide the new value
/// - Returns: `true` if the value is different (not equatable) and was set or `false` otherwise
@discardableResult public func setValue(closure: () -> (Type)) -> Bool {
var valueChanged = false
synchronizedValue.set { backingValue in
let newValue = closure()
guard newValue.optionalValue != backingValue.optionalValue else { return }
setUnsafeValue(backingValue: &backingValue, oldValue: backingValue, newValue: newValue)
valueChanged = true
}
return valueChanged
}
}
// MARK: - Equatable Array
extension Observable where Type: ObservableCollectionArray, Type.Element: Equatable {
/// Use this property to get the underlying value in a thread-safe manner.
public var value: Type {
return synchronizedValue.get()
}
/// Use this function to set the value in a thread-safe manner.
///
/// - Parameter closure: The closure to provide the new value
/// - Returns: `true` if the value is different (not equatable) and was set or `false` otherwise
@discardableResult public func setValue(closure: () -> (Type)) -> Bool {
var valueChanged = false
synchronizedValue.set { backingValue in
let newValue = closure()
guard newValue.array != backingValue.array else { return }
setUnsafeValue(backingValue: &backingValue, oldValue: backingValue, newValue: newValue)
valueChanged = true
}
return valueChanged
}
}
// MARK: - Optional Equatable Array
extension Observable where Type: OptionalConvertible,
Type.WrappedValueType: ObservableCollectionArray,
Type.WrappedValueType.Element: Equatable {
/// Use this property to get the underlying value in a thread-safe manner.
public var value: Type {
return synchronizedValue.get()
}
/// Use this function to set the value in a thread-safe manner.
///
/// - Parameter closure: The closure to provide the new value
/// - Returns: `true` if the value is different (not equatable) and was set or `false` otherwise
@discardableResult public func setValue(closure: () -> (Type)) -> Bool {
var valueChanged = false
synchronizedValue.set { backingValue in
let newValue = closure()
if let newValue = newValue.optionalValue, let value = backingValue.optionalValue {
guard newValue.array != value.array else { return }
} else if newValue.isNilValue() && backingValue.isNilValue() {
return
}
setUnsafeValue(backingValue: &backingValue, oldValue: backingValue, newValue: newValue)
valueChanged = true
}
return valueChanged
}
}
| mit | f4f0076e95b8b1aa264166e0773b5d00 | 38.992188 | 98 | 0.702481 | 4.586918 | false | false | false | false |
IDLabs-Gate/enVision | enVision/FaceNet.swift | 2 | 4778 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 ID Labs L.L.C.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class FaceNet {
private var tfFacenet : tfWrap?
func load(){
clean()
tfFacenet = tfWrap()
tfFacenet?.loadModel("facenet-inf-opt.pb", labels: nil, memMapped: true, optEnv: true)
tfFacenet?.setInputLayer("input", outputLayer: "embeddings")
}
func run(image: CIImage)-> [Double]{
guard let tfFacenet = tfFacenet else { return [] }
let inputEdge = 160
let input = CIImage(cgImage: resizeImage(image, newWidth: CGFloat(inputEdge), newHeight: CGFloat(inputEdge)).cgImage!)
var buffer : CVPixelBuffer?
CVPixelBufferCreate(kCFAllocatorDefault, inputEdge, inputEdge, kCVPixelFormatType_32BGRA, [String(kCVPixelBufferIOSurfacePropertiesKey) : [:]] as CFDictionary, &buffer)
if let buffer = buffer { CIContext().render(input, to: buffer) }
//neural network forward run
guard let network_output = tfFacenet.run(onFrame: buffer) else { return [] }
let output = network_output.flatMap{ ($0 as? NSNumber)?.doubleValue }
//print("embeddings", output.count)
return output
}
static func l2distance(_ feat1: [Double], _ feat2: [Double])-> Double{
//dist = np.sqrt(np.sum(np.square(np.subtract(emb[i,:], emb[j,:]))))
return sqrt(zip(feat1,feat2).map { f1, f2 in pow(f2-f1,2) }.reduce(0, +))
}
func clean(){
tfFacenet?.clean()
tfFacenet = nil
}
}
typealias FaceOutput = [(face:CIImage, box: CGRect, smile: Bool)]
class FaceDetector {
private let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [ CIDetectorAccuracy : CIDetectorAccuracyLow ])
func extractFaces(frame: CIImage)-> FaceOutput {
guard let features = faceDetector?.features(in: frame, options: [CIDetectorSmile : true]) as? [CIFaceFeature] else { return [] }
return features.map { f -> (face: CIImage, box: CGRect, smile: Bool) in
let rect = f.bounds
let cropped = frame.cropping(to: rect)
let face = cropped.applying(CGAffineTransform(translationX: -rect.origin.x, y: -rect.origin.y))
let box = rect.applying(transformToScreen(frame.extent))
return (face,box, f.hasSmile)
}
}
func transformToScreen(_ frame: CGRect)-> CGAffineTransform {
let frameWidth = frame.width
let frameHeight = frame.height
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
//compensate for previewing video frame in AVLayerVideoGravityResizeAspect
let horizontal = frameWidth/frameHeight > screenWidth/screenHeight
let seenWidth = horizontal ? screenWidth : screenHeight*frameWidth/frameHeight
let seenHeight = horizontal ? screenWidth*frameHeight/frameWidth : screenHeight
let biasX = horizontal ? 0 : (screenWidth-seenWidth)/2
let biasY = horizontal ? (screenHeight-seenHeight)/2 : 0
let transRatio = frameHeight/seenHeight
//translate CoreImage coordinates to UIKit coordinates
//also compensate for transRatio of conforming to video frame height
var transform = CGAffineTransform(scaleX: 1/transRatio, y: -1/transRatio)
transform = transform.translatedBy(x: (0+biasX)*transRatio, y: (-screenHeight+biasY)*transRatio)
return transform
}
}
| mit | 17667281a433a870bbd44bbb813036ad | 39.837607 | 176 | 0.651319 | 4.432282 | false | false | false | false |
SkrewEverything/Web-Tracker | Web Tracker/Web Tracker/SQLight/CustomTypes.swift | 1 | 2149 | //
// CustomTypes.swift
//
// SQLight
//
// Created by Skrew Everything on 29/06/17.
// Copyright © 2017 SkrewEverything. All rights reserved.
//
import Foundation
/* https://stackoverflow.com/questions/26883131/sqlite-transient-undefined-in-swift/26884081#26884081
*/
internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
///Callback closure type
public typealias SQLiteExecCallBack = @convention(c) (_ void: UnsafeMutableRawPointer?, _ columnCount: Int32, _ values: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?, _ columns:UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?) -> Int32
/// Specifies what type of DataBase to use
///
/// There are 2 possible values.
/// * **DBType.inMemory**: Creates Database in RAM
/// * **DBType.file(String)**: Creates or opens Database file specified by name as an argument
public enum DBType
{
case inMemory
case file(String)
}
/**
Required to cast to appropriate data type while using "select" query.
Taken from -> https://sqlite.org/c3ref/c_blob.html
#define SQLITE_INTEGER 1
#define SQLITE_FLOAT 2
#define SQLITE_BLOB 4
#define SQLITE_NULL 5
#ifdef SQLITE_TEXT
# undef SQLITE_TEXT
#else
# define SQLITE_TEXT 3
#endif
#define SQLITE3_TEXT 3
*/
internal enum SQLiteDataType: Int32
{
case integer = 1, float, text, blob, null
}
/// Error thrown by SQLight
public struct DBError: Error
{
let message: String
let errorCode: Int32
init(db: SQLight, ec: Int32, customMessage: String? = nil)
{
self.errorCode = ec
if let cm = customMessage
{
self.message = cm
}
else if String(cString: sqlite3_errmsg(db.dbPointer)) == "not an error"
{
self.message = String(cString: sqlite3_errstr(ec))
}
else
{
self.message = String(cString: sqlite3_errmsg(db.dbPointer))
}
}
}
extension DBError: LocalizedError
{
public var errorDescription: String? {
return self.message
}
}
| mit | ac7e9a56789731e9d8509f3d716c975e | 21.14433 | 242 | 0.666667 | 3.815275 | false | false | false | false |
m-schmidt/Refracto | Refracto/RefractometerDisplay.swift | 1 | 7371 | // RefractometerDisplay.swift
import UIKit
fileprivate let displayHeight: CGFloat = 180.0
class RefractometerDisplay: ReadableWidthView {
private let vLT = ValueDisplay()
private let vLB = ValueDisplay()
private let vMT = ValueDisplay()
private let vMB = ValueDisplay()
private let vRT = ValueDisplay()
private let vRB = ValueDisplay()
init() {
super.init(frame: .zero)
setup()
registerForUpdateNotifications()
update()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
unregisterUpdateNotifications()
}
override var intrinsicContentSize: CGSize {
return CGSize(width: FormulaInput.noIntrinsicMetric, height: displayHeight)
}
}
// MARK: - Content Updates
extension RefractometerDisplay {
private func registerForUpdateNotifications() {
let notification = Settings.updateNotification
let main = OperationQueue.main
NotificationCenter.default.addObserver(forName: notification, object: nil, queue: main) { [weak self] _ in
self?.update()
}
}
private func unregisterUpdateNotifications() {
NotificationCenter.default.removeObserver(self)
}
func update() {
switch Settings.shared.displayScheme {
case .Modern:
vLT.setLabel("Original Gravity".localized)
vLT.setValue(RefractometerModel.originalExtract, formattedWith: Formatter.plato, accessibilityFormatter: Formatter.accessiblePlato)
vLB.setLabel("Final Gravity".localized)
vLB.setValue(RefractometerModel.apparentExtract, formattedWith: Formatter.plato, accessibilityFormatter: Formatter.accessiblePlato)
vMT.setLabel("Original Gravity".localized)
vMT.setValue(RefractometerModel.originalGravity, formattedWith: Formatter.SG)
vMB.setLabel("Final Gravity".localized)
vMB.setValue(RefractometerModel.apparentGravity, formattedWith: Formatter.SG)
vRT.setLabel("Attenuation".localized)
vRT.setValue(RefractometerModel.apparentAttenuation, formattedWith: Formatter.attenuation)
vRB.setLabel("Alcohol %vol".localized)
vRB.setValue(RefractometerModel.alcohol, formattedWith: Formatter.abv)
case .ClassicPlato:
vLT.setLabel("Original Gravity".localized)
vLT.setValue(RefractometerModel.originalExtract, formattedWith: Formatter.plato, accessibilityFormatter: Formatter.accessiblePlato)
vLB.setLabel("Alcohol %vol".localized)
vLB.setValue(RefractometerModel.alcohol, formattedWith: Formatter.abv)
vMT.setLabel("Final Gravity".localized)
vMT.setValue(RefractometerModel.apparentExtract, formattedWith: Formatter.plato, accessibilityFormatter: Formatter.accessiblePlato)
vMB.setLabel("(actual)".localized)
vMB.setValue(RefractometerModel.actualExtract, formattedWith: Formatter.plato, accessibilityFormatter: Formatter.accessiblePlato)
vRT.setLabel("Attenuation".localized)
vRT.setValue(RefractometerModel.apparentAttenuation, formattedWith: Formatter.attenuation)
vRB.setLabel("(real)".localized)
vRB.setValue(RefractometerModel.actualAttenuation, formattedWith: Formatter.attenuation)
case .ClassicSG:
vLT.setLabel("Original Gravity".localized)
vLT.setValue(RefractometerModel.originalGravity, formattedWith: Formatter.SG)
vLB.setLabel("Alcohol %vol".localized)
vLB.setValue(RefractometerModel.alcohol, formattedWith: Formatter.abv)
vMT.setLabel("Final Gravity".localized)
vMT.setValue(RefractometerModel.apparentGravity, formattedWith: Formatter.SG)
vMB.setLabel("(actual)".localized)
vMB.setValue(RefractometerModel.actualGravity, formattedWith: Formatter.SG)
vRT.setLabel("Attenuation".localized)
vRT.setValue(RefractometerModel.apparentAttenuation, formattedWith: Formatter.attenuation)
vRB.setLabel("(real)".localized)
vRB.setValue(RefractometerModel.actualAttenuation, formattedWith: Formatter.attenuation)
}
}
}
// MARK: - View Setup
extension RefractometerDisplay {
private func setup() {
backgroundColor = Colors.displayBackground
setContentHuggingPriority(.defaultHigh+1, for: .vertical)
let display = wrapRow(wrapColumn(vLT, vLB), wrapColumn(vMT, vMB), wrapColumn(vRT, vRB))
embedd(readableSubview: display)
}
func wrapColumn(_ topView: UIView, _ bottomView: UIView) -> UIView {
let wrapper = UIView()
wrapper.translatesAutoresizingMaskIntoConstraints = false
wrapper.setContentHuggingPriority(.defaultLow, for: .horizontal)
wrapper.setContentHuggingPriority(.defaultLow, for: .vertical)
wrapper.backgroundColor = Colors.displayBackground
var constraints: [NSLayoutConstraint] = [
bottomView.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
topView.heightAnchor.constraint(equalTo: bottomView.heightAnchor) ]
let _ = [ topView,
SeparatorLine(color: Colors.displaySeparator, direction: .horizontal, size: .small),
bottomView ]
.reduce(wrapper.topAnchor) { anchor, view in
wrapper.addSubview(view)
constraints += [
view.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
view.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
view.topAnchor.constraint(equalTo: anchor)]
return view.bottomAnchor
}
NSLayoutConstraint.activate(constraints)
return wrapper
}
func wrapRow(_ leadingView: UIView, _ midView: UIView, _ trailingView: UIView) -> UIView {
let wrapper = UIView()
wrapper.translatesAutoresizingMaskIntoConstraints = false
wrapper.setContentHuggingPriority(.defaultLow, for: .horizontal)
wrapper.setContentHuggingPriority(.defaultLow, for: .vertical)
wrapper.backgroundColor = Colors.displayBackground
var constraints: [NSLayoutConstraint] = [
trailingView.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
leadingView.widthAnchor.constraint(equalTo: midView.widthAnchor),
leadingView.widthAnchor.constraint(equalTo: trailingView.widthAnchor) ]
let _ = [ leadingView,
SeparatorLine(color: Colors.displaySeparator, direction: .vertical, size: .medium),
midView,
SeparatorLine(color: Colors.displaySeparator, direction: .vertical, size: .medium),
trailingView]
.reduce(wrapper.leadingAnchor) { anchor, view in
wrapper.addSubview(view)
constraints += [
view.topAnchor.constraint(equalTo: wrapper.topAnchor),
view.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
view.leadingAnchor.constraint(equalTo: anchor)]
return view.trailingAnchor
}
NSLayoutConstraint.activate(constraints)
return wrapper
}
}
| bsd-3-clause | ab9377ccb6bccb51cf5c23f9eb56f25c | 39.723757 | 143 | 0.675214 | 4.897674 | false | false | false | false |
chicio/RangeUISlider | Source/UI/RangeUISlider.swift | 1 | 27035 | //
// RangeUISlider.swift
//
// Created by Fabrizio Duroni on 25/03/2017.
// 2017 Fabrizio Duroni.
//
// swiftlint:disable type_body_length
// swiftlint:disable identifier_name
// swiftlint:disable file_length
import Foundation
import UIKit
/**
A custom slider with two knobs that allow the user to select a range.
RangeUISlider has been created using Autolayout. It is an IBDesignable UIVIew and all its properties are IBInspectable.
RangeUISlider support RTL (right to left) languages automatically out of the box.
*/
@IBDesignable
open class RangeUISlider: UIView, ProgrammaticKnobChangeDelegate, RangeUpdaterDelegate {
/// Slider identifier.
@IBInspectable public var identifier: Int = 0
/// Step increment value. If different from 0 RangeUISlider will let the user drag by step increment.
@IBInspectable public var stepIncrement: CGFloat = 0.0
/// Show knobs labels.
@IBInspectable public var showKnobsLabels: Bool = false {
didSet {
components.knobs.showLabels(shouldShow: showKnobsLabels, topPosition: knobsLabelTopPosition)
}
}
/// Show knobs labels at the top or at the bottom of knobs.
@IBInspectable public var knobsLabelTopPosition: Bool = true {
didSet {
components.knobs.showLabels(shouldShow: showKnobsLabels, topPosition: knobsLabelTopPosition)
}
}
/// Default left knob starting value.
@IBInspectable public var defaultValueLeftKnob: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
/// Default right knob starting value.
@IBInspectable public var defaultValueRightKnob: CGFloat = 1.0 {
didSet {
setNeedsLayout()
}
}
/// Scale minimum value.
@IBInspectable public var scaleMinValue: CGFloat = 0.0 {
didSet {
setScale()
}
}
/// Scale maximum value.
@IBInspectable public var scaleMaxValue: CGFloat = 1.0 {
didSet {
setScale()
}
}
/// Selected range color.
@IBInspectable public var rangeSelectedColor: UIColor = UIColor.blue {
didSet {
components.progressViews.selectedProgressView.backgroundColor = rangeSelectedColor
}
}
/// Background range selected strechable image.
@IBInspectable public var rangeSelectedBackgroundImage: UIImage? {
didSet {
addBackgroundToRangeSelected()
}
}
/// Background range selected top edge insect for background image.
@IBInspectable public var rangeSelectedBackgroundEdgeInsetTop: CGFloat = 0.0 {
didSet {
addBackgroundToRangeSelected()
}
}
/// Background range selected left edge insect for background image.
@IBInspectable public var rangeSelectedBackgroundEdgeInsetLeft: CGFloat = 5.0 {
didSet {
addBackgroundToRangeSelected()
}
}
/// Background range selected bottom edge insect for background image.
@IBInspectable public var rangeSelectedBackgroundEdgeInsetBottom: CGFloat = 0.0 {
didSet {
addBackgroundToRangeSelected()
}
}
/// Background range selected right edge insect for background image.
@IBInspectable public var rangeSelectedBackgroundEdgeInsetRight: CGFloat = 5.0 {
didSet {
addBackgroundToRangeSelected()
}
}
/// Gradient color 1 for range selected.
@IBInspectable public var rangeSelectedGradientColor1: UIColor? {
didSet {
components.progressViews.selectedProgressView.addGradient(properties: selectedRangeGradientProperties())
}
}
/// Gradient color 2 for range selected.
@IBInspectable public var rangeSelectedGradientColor2: UIColor? {
didSet {
components.progressViews.selectedProgressView.addGradient(properties: selectedRangeGradientProperties())
}
}
/// Gradient start point for selected range.
@IBInspectable public var rangeSelectedGradientStartPoint: CGPoint = CGPoint() {
didSet {
components.progressViews.selectedProgressView.addGradient(properties: selectedRangeGradientProperties())
}
}
/// Gradient end point for selected range.
@IBInspectable public var rangeSelectedGradientEndPoint: CGPoint = CGPoint() {
didSet {
components.progressViews.selectedProgressView.addGradient(properties: selectedRangeGradientProperties())
}
}
/// Not selected range color.
@IBInspectable public var rangeNotSelectedColor: UIColor = UIColor.lightGray {
didSet {
components.progressViews.addBackgroundColorToNotSelectedProgressView(
rangeNotSelectedColor: rangeNotSelectedColor
)
}
}
/// Background range selected strechable image.
@IBInspectable public var rangeNotSelectedBackgroundImage: UIImage? {
didSet {
addBackgroundToRangeNotSelectedIfNeeded()
}
}
/// Background range selected top edge insect for background image.
@IBInspectable public var rangeNotSelectedBackgroundEdgeInsetTop: CGFloat = 0.0 {
didSet {
addBackgroundToRangeNotSelectedIfNeeded()
}
}
/// Background range selected left edge insect for background image.
@IBInspectable public var rangeNotSelectedBackgroundEdgeInsetLeft: CGFloat = 5.0 {
didSet {
addBackgroundToRangeNotSelectedIfNeeded()
}
}
/// Background range selected bottom edge insect for background image.
@IBInspectable public var rangeNotSelectedBackgroundEdgeInsetBottom: CGFloat = 0.0 {
didSet {
addBackgroundToRangeNotSelectedIfNeeded()
}
}
/// Background range selected right edge insect for background image.
@IBInspectable public var rangeNotSelectedBackgroundEdgeInsetRight: CGFloat = 5.0 {
didSet {
addBackgroundToRangeNotSelectedIfNeeded()
}
}
/// Gradient color 1 for range not selected.
@IBInspectable public var rangeNotSelectedGradientColor1: UIColor? {
didSet {
addGradientToNotSelectedRange()
}
}
/// Gradient color 2 for range not selected.
@IBInspectable public var rangeNotSelectedGradientColor2: UIColor? {
didSet {
addGradientToNotSelectedRange()
}
}
/// Gradient start point for not selected range.
@IBInspectable public var rangeNotSelectedGradientStartPoint: CGPoint = CGPoint() {
didSet {
addGradientToNotSelectedRange()
}
}
/// Gradient end point for not selected range.
@IBInspectable public var rangeNotSelectedGradientEndPoint: CGPoint = CGPoint() {
didSet {
addGradientToNotSelectedRange()
}
}
/// Left knob width.
@IBInspectable public var leftKnobWidth: CGFloat = 30.0 {
didSet {
components.knobs.leftKnob.widthConstraint.constant = leftKnobWidth
}
}
/// Left knob height.
@IBInspectable public var leftKnobHeight: CGFloat = 30.0 {
didSet {
components.knobs.leftKnob.heightConstraint.constant = leftKnobHeight
}
}
/// Left knob corners.
@IBInspectable public var leftKnobCorners: CGFloat = 15.0 {
didSet {
components.knobs.addCornersToLeftKnob(leftKnobCorners: leftKnobCorners)
}
}
/// Left knob image.
@IBInspectable public var leftKnobImage: UIImage? {
didSet {
components.knobs.leftKnob.add(image: leftKnobImage)
}
}
/// Left knob color.
@IBInspectable public var leftKnobColor: UIColor = UIColor.gray {
didSet {
components.knobs.leftKnob.components.backgroundView.backgroundColor = leftKnobColor
}
}
/// Left knob shadow opacity.
@IBInspectable public var leftShadowOpacity: Float = 0.0 {
didSet {
components.knobs.leftKnob.components.backgroundView.layer.shadowOpacity = leftShadowOpacity
}
}
/// Left knob shadow color.
@IBInspectable public var leftShadowColor: UIColor = UIColor.clear {
didSet {
components.knobs.leftKnob.components.backgroundView.layer.shadowColor = leftShadowColor.cgColor
}
}
/// Left knob shadow offset.
@IBInspectable public var leftShadowOffset: CGSize = CGSize() {
didSet {
components.knobs.leftKnob.components.backgroundView.layer.shadowOffset = leftShadowOffset
}
}
/// Left knob shadow radius.
@IBInspectable public var leftShadowRadius: CGFloat = 0 {
didSet {
components.knobs.leftKnob.components.backgroundView.layer.shadowRadius = leftShadowRadius
}
}
/// Gradient color 1 for range not selected.
@IBInspectable public var leftKnobGradientColor1: UIColor? {
didSet {
components.knobs.leftKnob.addGradient(properties: leftKnobGradientProperties())
}
}
/// Gradient color 2 for range not selected.
@IBInspectable public var leftKnobGradientColor2: UIColor? {
didSet {
components.knobs.leftKnob.addGradient(properties: leftKnobGradientProperties())
}
}
/// Gradient start point for not selected range.
@IBInspectable public var leftKnobGradientStartPoint: CGPoint = CGPoint() {
didSet {
components.knobs.leftKnob.addGradient(properties: leftKnobGradientProperties())
}
}
/// Gradient end point for not selected range.
@IBInspectable public var leftKnobGradientEndPoint: CGPoint = CGPoint() {
didSet {
components.knobs.leftKnob.addGradient(properties: leftKnobGradientProperties())
}
}
/// Left knob border width.
@IBInspectable public var leftKnobBorderWidth: CGFloat = 0.0 {
didSet {
components.knobs.leftKnob.addBorders(
usingColor: leftKnobBorderColor,
andWidth: leftKnobBorderWidth,
andCorners: leftKnobCorners
)
}
}
/// Left knob border color.
@IBInspectable public var leftKnobBorderColor: UIColor = UIColor.clear {
didSet {
components.knobs.leftKnob.addBorders(
usingColor: leftKnobBorderColor,
andWidth: leftKnobBorderWidth,
andCorners: leftKnobCorners
)
}
}
/// Right knob width.
@IBInspectable public var rightKnobWidth: CGFloat = 30.0 {
didSet {
components.knobs.rightKnob.widthConstraint.constant = rightKnobWidth
}
}
/// Right knob height.
@IBInspectable public var rightKnobHeight: CGFloat = 30.0 {
didSet {
components.knobs.rightKnob.heightConstraint.constant = rightKnobHeight
}
}
/// Right knob corners.
@IBInspectable public var rightKnobCorners: CGFloat = 15.0 {
didSet {
components.knobs.addCornersToRightKnob(rightKnobCorners: rightKnobCorners)
}
}
/// Right knob image.
@IBInspectable public var rightKnobImage: UIImage? {
didSet {
components.knobs.rightKnob.add(image: rightKnobImage)
}
}
/// Right knob color.
@IBInspectable public var rightKnobColor: UIColor = UIColor.gray {
didSet {
components.knobs.rightKnob.components.backgroundView.backgroundColor = rightKnobColor
}
}
/// Right knob shadow opacity.
@IBInspectable public var rightShadowOpacity: Float = 0.0 {
didSet {
components.knobs.rightKnob.components.backgroundView.layer.shadowOpacity = rightShadowOpacity
}
}
/// Right knob shadow color.
@IBInspectable public var rightShadowColor: UIColor = UIColor.clear {
didSet {
components.knobs.rightKnob.components.backgroundView.layer.shadowColor = rightShadowColor.cgColor
}
}
/// Right knob shadow offset.
@IBInspectable public var rightShadowOffset: CGSize = CGSize() {
didSet {
components.knobs.rightKnob.components.backgroundView.layer.shadowOffset = rightShadowOffset
}
}
/// Right knob shadow radius.
@IBInspectable public var rightShadowRadius: CGFloat = 0 {
didSet {
components.knobs.rightKnob.components.backgroundView.layer.shadowRadius = rightShadowRadius
}
}
/// Gradient color 1 for range not selected.
@IBInspectable public var rightKnobGradientColor1: UIColor? {
didSet {
components.knobs.rightKnob.addGradient(properties: rightKnobGradientProperties())
}
}
/// Gradient color 2 for range not selected.
@IBInspectable public var rightKnobGradientColor2: UIColor? {
didSet {
components.knobs.rightKnob.addGradient(properties: rightKnobGradientProperties())
}
}
/// Gradient start point for not selected range.
@IBInspectable public var rightKnobGradientStartPoint: CGPoint = CGPoint() {
didSet {
components.knobs.rightKnob.addGradient(properties: rightKnobGradientProperties())
}
}
/// Gradient end point for not selected range.
@IBInspectable public var rightKnobGradientEndPoint: CGPoint = CGPoint() {
didSet {
components.knobs.rightKnob.addGradient(properties: rightKnobGradientProperties())
}
}
/// Right knob border width.
@IBInspectable public var rightKnobBorderWidth: CGFloat = 0.0 {
didSet {
components.knobs.rightKnob.addBorders(
usingColor: rightKnobBorderColor,
andWidth: rightKnobBorderWidth,
andCorners: rightKnobCorners
)
}
}
/// Right knob border color.
@IBInspectable public var rightKnobBorderColor: UIColor = UIColor.clear {
didSet {
components.knobs.rightKnob.addBorders(
usingColor: rightKnobBorderColor,
andWidth: rightKnobBorderWidth,
andCorners: rightKnobCorners
)
}
}
/// Knobs labels font size.
@IBInspectable public var knobsLabelFontSize: CGFloat = 14 {
didSet {
components.knobs.setKnobsLabelsFontSize(size: knobsLabelFontSize)
}
}
/// Knobs label font color.
@IBInspectable public var knobsLabelFontColor: UIColor = UIColor.black {
didSet {
components.knobs.setKnobsLabelsColor(color: knobsLabelFontColor)
}
}
/// Knobs labels number of decimal.
@IBInspectable public var knobsLabelNumberOfDecimal: Int = 2
/// Bar height.
@IBInspectable public var barHeight: CGFloat = 15.0 {
didSet {
components.bar.heightConstraint.constant = barHeight
}
}
/// Bar leading offset.
@IBInspectable public var barLeading: CGFloat = 20.0 {
didSet {
components.bar.leadingConstraint.constant = barLeading
}
}
/// Bar trailing offset.
@IBInspectable public var barTrailing: CGFloat = 20.0 {
didSet {
components.bar.trailingConstraint.constant = -barTrailing
}
}
/// Bar corners.
@IBInspectable public var barCorners: CGFloat = 0.0 {
didSet {
components.progressViews.addBarCornersToNotSelectedProgressView(barCorners: barCorners)
addGradientToNotSelectedRange()
addBackgroundToRangeNotSelectedIfNeeded()
}
}
/// Bar shadow opacity.
@IBInspectable public var barShadowOpacity: Float = 0.0 {
didSet {
components.bar.layer.shadowOpacity = barShadowOpacity
}
}
/// Bar shadow color.
@IBInspectable public var barShadowColor: UIColor = UIColor.clear {
didSet {
components.bar.layer.shadowColor = barShadowColor.cgColor
}
}
/// Bar shadow offset.
@IBInspectable public var barShadowOffset: CGSize = CGSize() {
didSet {
components.bar.layer.shadowOffset = barShadowOffset
}
}
/// Bar shadow radius.
@IBInspectable public var barShadowRadius: CGFloat = 0.0 {
didSet {
components.bar.layer.shadowRadius = barShadowRadius
}
}
/// Bar border color.
@IBInspectable public var barBorderWidth: CGFloat = 0.0 {
didSet {
components.progressViews.addBordersWidth(borderWidth: barBorderWidth)
}
}
/// Bar border color.
@IBInspectable public var barBorderColor: UIColor = UIColor.clear {
didSet {
components.progressViews.addBorderColor(borderColor: barBorderColor)
}
}
/// Slider delegate.
public weak var delegate: RangeUISliderDelegate?
/// The UI components of RangeUISlider: knobs, bar, and prosgress views.
public let components = RangeUISliderComponents()
internal lazy var properties = RangeUISliderProperties(
scale: Scale(scaleMinValue: scaleMinValue, scaleMaxValue: scaleMaxValue),
previousRangeSelected: RangeSelected(minValue: defaultValueLeftKnob, maxValue: defaultValueRightKnob)
)
private lazy var programmaticKnobChange: ProgrammaticKnobChange = ProgrammaticKnobChange(
bar: components.bar,
knobs: components.knobs,
delegate: self
)
private lazy var rangeUpdater = RangeUpdater(
properties: properties,
components: components,
delegate: self
)
private lazy var knobGestureManager = KnobGestureManager(
bar: components.bar,
knobs: components.knobs,
knobGestureManagerDelegate: rangeUpdater
)
// MARK: init
/**
Standard init using coder.
- parameter aDecoder: the decoder used to init the sliders.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Standard init using a CGRect.
- parameter frame: the frame used to init the slider.
*/
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
// MARK: views lifecycle
/**
Prepare RangeUISlider to be drawn in Interface Builder.
*/
open override func prepareForInterfaceBuilder() {
// Fake values for interface builder.
// Used to make visible the progress views.
components.knobs.leftKnob.xPositionConstraint.constant = 40
components.knobs.rightKnob.xPositionConstraint.constant = -40
}
/**
Custom layout subviews to set the default values for the know of RangeUISlider
*/
public override func layoutSubviews() {
super.layoutSubviews()
changeLeftKnob(value: defaultValueLeftKnob)
changeRightKnob(value: defaultValueRightKnob)
}
// MARK: programmatic api
/**
Change the value of the left knob programmatically.
- parameter value: the new value to be assigned to the left knob
*/
public func changeLeftKnob(value: CGFloat) {
properties.updateRangeSelectedCalculator(
knobsHorizontalPosition: components.knobs.horizontalPositions(),
barWidth: components.bar.frame.width
)
programmaticKnobChange.programmaticallyChangeLeftKnob(value: value)
}
/**
Change the value of the right knob programmatically.
- parameter value: the new value to be assigned to the right knob
*/
public func changeRightKnob(value: CGFloat) {
properties.updateRangeSelectedCalculator(
knobsHorizontalPosition: components.knobs.horizontalPositions(),
barWidth: components.bar.frame.width
)
programmaticKnobChange.programmaticallyChangeRightKnob(value: value)
}
internal func programmaticChangeCompleted() {
rangeUpdater.rangeSelectionFinished(userInteraction: false)
}
// MARK: setup
private func setup() {
addViews()
RangeUISliderSetup(components: components)
.execute(
barProperties: barProperties(),
knobsProperties: knobsProperties(),
progressViewsProperties: progressViewsProperties()
)
}
private func addViews() {
addSubview(components.bar)
components.bar.addSubview(components.progressViews.selectedProgressView)
components.bar.addSubview(components.progressViews.leftProgressView)
components.bar.addSubview(components.progressViews.rightProgressView)
components.bar.addSubview(components.knobs.leftKnob)
components.bar.addSubview(components.knobs.rightKnob)
}
private func barProperties() -> BarProperties {
return BarProperties(
height: barHeight,
leading: barLeading,
trailing: barTrailing
)
}
private func knobsProperties() -> KnobsProperties {
return KnobsPropertiesBuilder(
target: self,
leftKnobSelector: #selector(moveLeftKnob),
rightKnobSelector: #selector(moveRightKnob)
)
.leftKnobHeight(leftKnobHeight)
.leftKnobWidth(leftKnobWidth)
.rightKnobHeight(rightKnobHeight)
.rightKnobWidth(rightKnobWidth)
.build()
}
private func progressViewsProperties() -> ProgressViewsProperties {
return ProgressViewsPropertiesFactory.make(
rangeSelectedColor: rangeSelectedColor,
rangeNotSelectedColor: rangeNotSelectedColor
)
}
// MARK: gradient
private func addGradientToNotSelectedRange() {
let properties = GradientProperties(
colors: GradientColors(
firstColor: rangeNotSelectedGradientColor1,
secondColor: rangeNotSelectedGradientColor2
),
points: GradientPoints(
startPoint: rangeNotSelectedGradientStartPoint,
endPoint: rangeNotSelectedGradientEndPoint
),
cornerRadius: barCorners
)
components.progressViews.addGradientToNotSelectedProgressView(properties: properties)
}
private func selectedRangeGradientProperties() -> GradientProperties {
return GradientProperties(
colors: GradientColors(
firstColor: rangeSelectedGradientColor1,
secondColor: rangeSelectedGradientColor2
),
points: GradientPoints(
startPoint: rangeSelectedGradientStartPoint,
endPoint: rangeSelectedGradientEndPoint
),
cornerRadius: 0.0
)
}
private func leftKnobGradientProperties() -> GradientProperties {
return GradientProperties(
colors: GradientColors(
firstColor: leftKnobGradientColor1,
secondColor: leftKnobGradientColor2
),
points: GradientPoints(
startPoint: leftKnobGradientStartPoint,
endPoint: leftKnobGradientEndPoint
),
cornerRadius: leftKnobCorners
)
}
private func rightKnobGradientProperties() -> GradientProperties {
return GradientProperties(
colors: GradientColors(
firstColor: rightKnobGradientColor1,
secondColor: rightKnobGradientColor2
),
points: GradientPoints(
startPoint: rightKnobGradientStartPoint,
endPoint: rightKnobGradientEndPoint
),
cornerRadius: rightKnobCorners
)
}
// MARK: background
private func addBackgroundToRangeNotSelectedIfNeeded() {
components.progressViews.addBackgroundToNotSelectedProgressViews(
image: rangeNotSelectedBackgroundImage,
edgeInset: UIEdgeInsets(
top: rangeNotSelectedBackgroundEdgeInsetTop,
left: rangeNotSelectedBackgroundEdgeInsetLeft,
bottom: rangeNotSelectedBackgroundEdgeInsetBottom,
right: rangeNotSelectedBackgroundEdgeInsetRight
),
barCorners: barCorners
)
}
private func addBackgroundToRangeSelected() {
components.progressViews.addBackgroundToSelectedProgressViews(
image: rangeSelectedBackgroundImage,
edgeInset: UIEdgeInsets(
top: rangeSelectedBackgroundEdgeInsetTop,
left: rangeSelectedBackgroundEdgeInsetLeft,
bottom: rangeSelectedBackgroundEdgeInsetBottom,
right: rangeSelectedBackgroundEdgeInsetRight
),
barCorners: barCorners
)
}
// MARK: scale
private func setScale() {
properties.scale = Scale(scaleMinValue: scaleMinValue, scaleMaxValue: scaleMaxValue)
}
// MARK: gesture
@objc final func moveLeftKnob(gestureRecognizer: UIPanGestureRecognizer) {
knobGestureManager.moveLeftKnob(gesture: getGestureData(gestureRecognizer: gestureRecognizer))
}
@objc final func moveRightKnob(gestureRecognizer: UIPanGestureRecognizer) {
knobGestureManager.moveRightKnob(gesture: getGestureData(gestureRecognizer: gestureRecognizer))
}
private func getGestureData(gestureRecognizer: UIPanGestureRecognizer) -> GestureData {
return GestureData(
gestureRecognizer: gestureRecognizer,
scale: properties.scale,
stepIncrement: stepIncrement,
semanticContentAttribute: self.semanticContentAttribute
)
}
// MARK: delegate
internal func rangeChangeStarted() {
delegate?.rangeChangeStarted?()
}
internal func rangeIsChanging(minValueSelected: CGFloat, maxValueSelected: CGFloat) {
components.knobs.animateLabels(shouldShow: showKnobsLabels)
components.knobs.updateLabels(
minValueSelected: minValueSelected,
maxValueSelected: maxValueSelected,
knobsLabelNumberOfDecimal: knobsLabelNumberOfDecimal
)
delegate?.rangeIsChanging?(
event: RangeUISliderChangeEvent(
minValueSelected: minValueSelected,
maxValueSelected: maxValueSelected,
slider: self
)
)
}
internal func rangeChangeFinished(minValueSelected: CGFloat, maxValueSelected: CGFloat, userInteraction: Bool) {
components.knobs.animateLabels(shouldShow: showKnobsLabels)
components.knobs.updateLabels(
minValueSelected: minValueSelected,
maxValueSelected: maxValueSelected,
knobsLabelNumberOfDecimal: knobsLabelNumberOfDecimal
)
delegate?.rangeChangeFinished(
event: RangeUISliderChangeFinishedEvent(
minValueSelected: minValueSelected,
maxValueSelected: maxValueSelected,
slider: self,
userInteraction: userInteraction
)
)
}
}
| mit | 7b90cca306a5dfdfec9b23a70c29f1b4 | 34.760582 | 120 | 0.653597 | 5.30202 | false | false | false | false |
airbnb/lottie-ios | Sources/Public/iOS/BundleImageProvider.swift | 3 | 2928 | //
// LottieBundleImageProvider.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/25/19.
//
import CoreGraphics
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst)
import UIKit
/// An `AnimationImageProvider` that provides images by name from a specific bundle.
/// The BundleImageProvider is initialized with a bundle and an optional searchPath.
public class BundleImageProvider: AnimationImageProvider {
// MARK: Lifecycle
/// Initializes an image provider with a bundle and an optional subpath.
///
/// Provides images for an animation from a bundle. Additionally the provider can
/// search a specific subpath for the images.
///
/// - Parameter bundle: The bundle containing images for the provider.
/// - Parameter searchPath: The subpath is a path within the bundle to search for image assets.
///
public init(bundle: Bundle, searchPath: String?) {
self.bundle = bundle
self.searchPath = searchPath
}
// MARK: Public
public func imageForAsset(asset: ImageAsset) -> CGImage? {
if
let data = Data(imageAsset: asset),
let image = UIImage(data: data)
{
return image.cgImage
}
let imagePath: String?
/// Try to find the image in the bundle.
if let searchPath = searchPath {
/// Search in the provided search path for the image
var directoryPath = URL(fileURLWithPath: searchPath)
directoryPath.appendPathComponent(asset.directory)
if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: directoryPath.path) {
/// First search for the image in the asset provided sub directory.
imagePath = path
} else if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: searchPath) {
/// Try finding the image in the search path.
imagePath = path
} else {
imagePath = bundle.path(forResource: asset.name, ofType: nil)
}
} else {
if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: asset.directory) {
/// First search for the image in the asset provided sub directory.
imagePath = path
} else {
/// First search for the image in bundle.
imagePath = bundle.path(forResource: asset.name, ofType: nil)
}
}
if imagePath == nil {
guard let image = UIImage(named: asset.name, in: bundle, compatibleWith: nil) else {
LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle")
return nil
}
return image.cgImage
}
guard let foundPath = imagePath, let image = UIImage(contentsOfFile: foundPath) else {
/// No image found.
LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle")
return nil
}
return image.cgImage
}
// MARK: Internal
let bundle: Bundle
let searchPath: String?
}
#endif
| apache-2.0 | 59c69562f196961473470f21a771d857 | 31.898876 | 104 | 0.670423 | 4.470229 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch05-CollectionViews/CollectionViewDemo/CollectionViewDemo/MKViewController.swift | 1 | 6176 | //
// MKViewController.swift
// CollectionViewDemo
//
// Created by wj on 15/9/22.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
private enum PhotoOrientation{
case photoOrientationLandscape
case photoOrientationPortrait
}
class MKViewController: UICollectionViewController ,UIAdaptivePresentationControllerDelegate{
var photoList:[String]?
fileprivate var photoOrientation = [PhotoOrientation]()
fileprivate var photosCache = [String:UIImage]()
func photoDirectory()->String{
return Bundle.main.resourcePath! + "/Photos"
}
override func viewDidLoad() {
super.viewDidLoad()
var photosArray:[String]!
do{
try photosArray = FileManager.default.contentsOfDirectory(atPath: photoDirectory())
}catch(let error){
print("There is an error when init photos: \(error.localizedDescription)")
return;
}
DispatchQueue.global(qos: .default).async { () -> Void in
photosArray.forEach({ (obj) in
let path = self.photoDirectory() + "/" + obj
if let image = UIImage(contentsOfFile: path){
let size = image.size
if size.width>size.height{
self.photoOrientation.append(.photoOrientationLandscape)
}else{
self.photoOrientation.append(.photoOrientationPortrait)
}
}
})
DispatchQueue.main.async{ () -> Void in
self.photoList = photosArray
self.collectionView?.reloadData()
};
}
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.all
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MainSegue"{
let selectedIndexPath = sender as! IndexPath
let photoName = photoList![selectedIndexPath.row]
let controller = segue.destination as! MKDetailsViewController
controller.photoPath = photoDirectory()+"/"+photoName
if let pc = controller.presentationController{
pc.delegate=self
}
}
}
//MARK: -AdaptivePresentationControllerDelegate
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photoList?.count ?? 0
}
fileprivate struct cellReuseIdentifier{
static let landscape = "MKPhotoCellLandscape"
static let portrait = "MKPhotoCellPortrait"
static let Supplementary = "SupplementaryViewIdentifier"
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let orientation = self.photoOrientation[indexPath.row]
let identifier = (orientation==PhotoOrientation.photoOrientationLandscape) ? cellReuseIdentifier.landscape : cellReuseIdentifier.portrait
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! MKCollectionViewCell
let photoName = self.photoList?[(indexPath as NSIndexPath).row] ?? ""
let photoFilePath = self.photoDirectory()+"/"+photoName
cell.nameLabel.text = NSString(string: photoName).deletingPathExtension
var thumbImage = self.photosCache[photoName]
cell.photoView.image = thumbImage
if thumbImage == nil{
DispatchQueue.global(qos:.default).async{ () -> Void in
if let image = UIImage(contentsOfFile: photoFilePath){
if orientation == PhotoOrientation.photoOrientationPortrait{
UIGraphicsBeginImageContext(CGSize(width: 180.0, height: 120.0))
image.draw(in: CGRect(x: 0, y: 0, width: 180.0, height: 120.0))
thumbImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}else{
UIGraphicsBeginImageContext(CGSize(width: 120.0, height: 180.0))
image.draw(in: CGRect(x: 0, y: 0, width: 120.0, height: 180.0))
thumbImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
DispatchQueue.main.async{ () -> Void in
self.photosCache[photoName] = thumbImage
cell.photoView.image=thumbImage
}
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "MainSegue", sender: indexPath)
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: cellReuseIdentifier.Supplementary, for: indexPath)
}
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
}
| mit | 26ae61750c9be43fbdae1eaed58418dc | 37.58125 | 171 | 0.631298 | 5.918504 | false | false | false | false |
eduarenas80/MarvelClient | Source/RequestBuilders/ComicRequestBuilder.swift | 2 | 8672 | //
// ComicRequestBuilder.swift
// MarvelClient
//
// Copyright (c) 2016 Eduardo Arenas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class ComicRequestBuilder: MarvelRequestBuilder {
private let entityTypeString = "comics"
public var format: ComicFormat?
public var formatType: ComicFormatType?
public var noVariants: Bool?
public var dateDescriptor: ComicDateDescriptor?
public var dateRange: DateRange?
public var title: String?
public var titleStartsWith: String?
public var startYear: Int?
public var issueNumber: Int?
public var diamondCode: String?
public var digitalId: Int?
public var upc: String?
public var isbn: String?
public var ean: String?
public var issn: String?
public var hasDigitalIssue: Bool?
public var creators: [Int]?
public var characters: [Int]?
public var series: [Int]?
public var events: [Int]?
public var stories: [Int]?
public var sharedAppearances: [Int]?
public var collaborators: [Int]?
public var orderBy: [ComicOrder]?
init(keys: MarvelAPIKeys) {
super.init(entityType: self.entityTypeString, keys: keys)
}
public func fetch(completionHandler: Wrapper<Comic> -> Void) {
super.fetchResults(completionHandler)
}
public func format(format: ComicFormat) -> Self {
self.format = format
return self
}
public func formatType(formatType: ComicFormatType) -> Self {
self.formatType = formatType
return self
}
public func noVariants(noVariants: Bool) -> Self {
self.noVariants = noVariants
return self
}
public func dateDescriptor(dateDescriptor: ComicDateDescriptor) -> Self {
self.dateDescriptor = dateDescriptor
return self
}
public func dateRange(dateRange: DateRange) -> Self {
self.dateRange = dateRange
return self
}
public func title(title: String) -> Self {
self.title = title
return self
}
public func titleStartsWith(titleStartsWith: String) -> Self {
self.titleStartsWith = titleStartsWith
return self
}
public func startYear(startYear: Int) -> Self {
self.startYear = startYear
return self
}
public func issueNumber(issueNumber: Int) -> Self {
self.issueNumber = issueNumber
return self
}
public func diamondCode(diamondCode: String) -> Self {
self.diamondCode = diamondCode
return self
}
public func digitalId(digitalId: Int) -> Self {
self.digitalId = digitalId
return self
}
public func upc(upc: String) -> Self {
self.upc = upc
return self
}
public func isbn(isbn: String) -> Self {
self.isbn = isbn
return self
}
public func ean(ean: String) -> Self {
self.ean = ean
return self
}
public func issn(issn: String) -> Self {
self.issn = issn
return self
}
public func hasDigitalIssue(hasDigitalIssue: Bool) -> Self {
self.hasDigitalIssue = hasDigitalIssue
return self
}
public func creators(creators: [Int]) -> Self {
self.creators = creators
return self
}
public func characters(characters: [Int]) -> Self {
self.characters = characters
return self
}
public func series(series: [Int]) -> Self {
self.series = series
return self
}
public func events(events: [Int]) -> Self {
self.events = events
return self
}
public func stories(stories: [Int]) -> Self {
self.stories = stories
return self
}
public func sharedAppearances(sharedAppearances: [Int]) -> Self {
self.sharedAppearances = sharedAppearances
return self
}
public func collaborators(collaborators: [Int]) -> Self {
self.collaborators = collaborators
return self
}
public func orderBy(orderBy: [ComicOrder]) -> Self {
self.orderBy = orderBy
return self
}
override func buildQueryParameters() -> [String : AnyObject] {
var queryParameters = super.buildQueryParameters()
if let format = self.format {
queryParameters["format"] = format.rawValue
}
if let formatType = self.formatType {
queryParameters["formatType"] = formatType.rawValue
}
if let noVariants = self.noVariants {
queryParameters["noVariants"] = noVariants
}
if let dateDescriptor = self.dateDescriptor {
queryParameters["dateDescriptor"] = dateDescriptor.rawValue
}
if let dateRange = self.dateRange {
queryParameters["dateRange"] = dateRange.description
}
if let title = self.title {
queryParameters["title"] = title
}
if let titleStartsWith = self.titleStartsWith {
queryParameters["titleStartsWith"] = titleStartsWith
}
if let startYear = self.startYear {
queryParameters["startYear"] = startYear
}
if let issueNumber = self.issueNumber {
queryParameters["issueNumber"] = issueNumber
}
if let diamondCode = self.diamondCode {
queryParameters["diamondCode"] = diamondCode
}
if let digitalId = self.digitalId {
queryParameters["digitalId"] = digitalId
}
if let upc = self.upc {
queryParameters["upc"] = upc
}
if let isbn = self.isbn {
queryParameters["isbn"] = isbn
}
if let ean = self.ean {
queryParameters["ean"] = ean
}
if let issn = self.issn {
queryParameters["issn"] = issn
}
if let hasDigitalIssue = self.hasDigitalIssue {
queryParameters["hasDigitalIssue"] = hasDigitalIssue
}
if let creators = self.creators {
queryParameters["creators"] = creators.joinDescriptionsWithSeparator(",")
}
if let characters = self.characters {
queryParameters["characters"] = characters.joinDescriptionsWithSeparator(",")
}
if let series = self.series {
queryParameters["series"] = series.joinDescriptionsWithSeparator(",")
}
if let events = self.events {
queryParameters["events"] = events.joinDescriptionsWithSeparator(",")
}
if let stories = self.stories {
queryParameters["stories"] = stories.joinDescriptionsWithSeparator(",")
}
if let sharedAppearances = self.sharedAppearances {
queryParameters["sharedAppearances"] = sharedAppearances.joinDescriptionsWithSeparator(",")
}
if let collaborators = self.collaborators {
queryParameters["collaborators"] = collaborators.joinDescriptionsWithSeparator(",")
}
if let orderBy = self.orderBy {
queryParameters["orderBy"] = orderBy.joinDescriptionsWithSeparator(",")
}
return queryParameters
}
}
public enum ComicFormat: String, CustomStringConvertible {
case Comic = "comic"
case Magazine = "magazine"
case TradePaperback = "trade paperback"
case Hardcover = "hardcover"
case Digest = "digest"
case GraphicNovel = "graphic novel"
case DigitalComic = "digital comic"
case InfiniteComic = "infinite comic"
public var description: String {
return self.rawValue
}
}
public enum ComicFormatType: String {
case Comic = "comic"
case Collection = "collection"
}
public enum ComicDateDescriptor: String {
case LastWeek = "lastWeek"
case ThisWeek = "thisWeek"
case NextWeek = "nextWeek"
case ThisMonth = "thisMonth"
}
public enum ComicOrder: String, CustomStringConvertible {
case FocDate = "focDate"
case OnsaleDate = "onsaleDate"
case Title = "title"
case IssueNumber = "issueNumber"
case Modified = "modified"
case FocDateDescending = "-focDate"
case OnsaleDateDescending = "-onsaleDate"
case TitleDescending = "-title"
case IssueNumberDescending = "-issueNumber"
case ModifiedDescending = "-modified"
public var description: String {
return self.rawValue
}
}
| mit | 547dbeedb2f8b4bce10299c1f0b0aaa8 | 27.247557 | 97 | 0.692574 | 4.236444 | false | false | false | false |
PodRepo/firefox-ios | FxAClient/Frontend/SignIn/FxAContentViewController.swift | 2 | 6233 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SnapKit
import UIKit
import WebKit
protocol FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void
func contentViewControllerDidCancel(viewController: FxAContentViewController)
}
/**
* A controller that manages a single web view connected to the Firefox
* Accounts (Desktop) Sync postMessage interface.
*
* The postMessage interface is not really documented, but it is simple
* enough. I reverse engineered it from the Desktop Firefox code and the
* fxa-content-server git repository.
*/
class FxAContentViewController: SettingsContentViewController, WKScriptMessageHandler {
private enum RemoteCommand: String {
case CanLinkAccount = "can_link_account"
case Loaded = "loaded"
case Login = "login"
case SessionStatus = "session_status"
case SignOut = "sign_out"
}
var delegate: FxAContentViewControllerDelegate?
init() {
super.init(backgroundColor: UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0), title: NSAttributedString(string: "Firefox Accounts"))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func makeWebView() -> WKWebView {
// Inject our setup code after the page loads.
let source = getJS()
let userScript = WKUserScript(
source: source,
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true
)
// Handle messages from the content server (via our user script).
let contentController = WKUserContentController()
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(
self,
name: "accountsCommandHandler"
)
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(
frame: CGRect(x: 0, y: 0, width: 1, height: 1),
configuration: config
)
webView.navigationDelegate = self
// Don't allow overscrolling.
webView.scrollView.bounces = false
return webView
}
// Send a message to the content server.
func injectData(type: String, content: [String: AnyObject]) {
NSLog("injectData: " + type)
let data = [
"type": type,
"content": content,
]
let json = JSON(data).toString(false)
let script = "window.postMessage(\(json), '\(self.url)');"
webView.evaluateJavaScript(script, completionHandler: nil)
}
private func onCanLinkAccount(data: JSON) {
// // We need to confirm a relink - see shouldAllowRelink for more
// let ok = shouldAllowRelink(accountData.email);
let ok = true
injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]]);
}
// We're not signed in to a Firefox Account at this time, which we signal by returning an error.
private func onSessionStatus(data: JSON) {
injectData("message", content: ["status": "error"])
}
// We're not signed in to a Firefox Account at this time. We should never get a sign out message!
private func onSignOut(data: JSON) {
injectData("message", content: ["status": "error"])
}
// The user has signed in to a Firefox Account. We're done!
private func onLogin(data: JSON) {
NSLog("onLogin: " + data.toString())
injectData("message", content: ["status": "login"])
self.delegate?.contentViewControllerDidSignIn(self, data: data)
}
// The content server page is ready to be shown.
private func onLoaded() {
NSLog("Handling loaded remote command.");
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
// Handle a message coming from the content server.
func handleRemoteCommand(rawValue: String, data: JSON) {
if let command = RemoteCommand(rawValue: rawValue) {
NSLog("Handling remote command '\(rawValue)' .");
if !isLoaded && command != .Loaded {
// Work around https://github.com/mozilla/fxa-content-server/issues/2137
NSLog("Synthesizing loaded remote command.")
onLoaded()
}
switch (command) {
case .Loaded:
onLoaded()
case .Login:
onLogin(data)
case .CanLinkAccount:
onCanLinkAccount(data)
case .SessionStatus:
onSessionStatus(data)
case .SignOut:
onSignOut(data)
}
} else {
NSLog("Unknown remote command '\(rawValue)'; ignoring.");
}
}
// Dispatch webkit messages originating from our child webview.
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if (message.name == "accountsCommandHandler") {
let body = JSON(message.body)
let detail = body["detail"]
handleRemoteCommand(detail["command"].asString!, data: detail["data"])
} else {
NSLog("Got unrecognized message \(message)")
}
}
private func getJS() -> String {
let fileRoot = NSBundle.mainBundle().pathForResource("FxASignIn", ofType: "js")
return (try! NSString(contentsOfFile: fileRoot!, encoding: NSUTF8StringEncoding)) as String
}
override func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
// Ignore for now.
}
override func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
// Ignore for now.
}
}
| mpl-2.0 | 9bbeb98d39c1504dc8505f64f8819e6d | 35.028902 | 168 | 0.632922 | 4.896308 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/RotateImage.swift | 1 | 762 | //
// RotateImage.swift
// LeetCode
//
// Created by jourhuang on 2021/4/4.
// Copyright © 2021 伯驹 黄. All rights reserved.
//
import Foundation
// https://leetcode-cn.com/problems/rotate-image/
//func rotateImage(_ matrix: inout [[Int]]) {
// let n = matrix.count
// if n <= 1 {
// return
// }
// let mat = matrix
// for i in 0..<n {
// for j in 0..<n {
// matrix[i][j] = mat[n-j-1][i]
// }
// }
//}
func rotateImage(_ matrix: inout [[Int]]) {
let n = matrix.count
matrix.reverse()
for column in 0..<n {
for row in column..<n {
let x = matrix[row][column]
matrix[row][column] = matrix[column][row]
matrix[column][row] = x
}
}
}
| mit | 5c4a692aaa011b6213015922c8ddcbea | 19.405405 | 53 | 0.507285 | 3.119835 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIComponents/QMUIQQEmotionManager.swift | 1 | 12385 | //
// QMUIQQEmotionManager.swift
// QMUI.swift
//
// Created by 黄伯驹 on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
protocol QMUIQQEmotionInputViewProtocol: UITextInput {
var text: String { get set }
var selectedRange: Range<Int> { get }
}
/**
* 提供一个QQ表情面板,能为绑定的`UITextField`或`UITextView`提供表情的相关功能,包括点击表情输入对应的表情名字、点击删除按钮删除表情。由于表情的插入、删除都会受当前输入框的光标所在位置的影响,所以请在适当的时机更新`selectedRangeForBoundTextInput`的值,具体情况请查看属性的注释。
* @warning 由于QQ表情图片较多(文件大小约400K),因此表情图片被以bundle的形式存放在
* @warning 一个`QMUIQQEmotionManager`无法同时绑定`boundTextField`和`boundTextView`,在两者都绑定的情况下,优先使用`boundTextField`。
* @warning 由于`QMUIQQEmotionManager`里面多个地方会调用`boundTextView.text`,而`setText:`并不会触发`UITextViewDelegate`的`textViewDidChange:`或`UITextViewTextDidChangeNotification`,从而在刷新表情面板里的发送按钮的enabled状态时可能不及时,所以`QMUIQQEmotionManager`要求绑定的`QMUITextView`必须打开`shouldResponseToProgrammaticallyTextChanges`属性
*/
class QMUIQQEmotionManager {
/// 要绑定的UITextField
weak var boundTextField: UITextField?
/// 要绑定的UITextView
weak var boundTextView: UITextView?
/**
* `selectedRangeForBoundTextInput`决定了表情将会被插入(删除)的位置,因此使用控件的时候需要及时更新它。
*
* 通常用到的更新时机包括:
* - 降下键盘显示QQ表情面板之前(调用resignFirstResponder、endEditing:之前)
* - <UITextViewDelegate>的`textViewDidChangeSelection:`回调里
* - 输入框里的文字发生变化时,例如点了发送按钮后输入框文字会被清空,此时要重置`selectedRangeForBoundTextInput`为0
*/
var selectedRangeForBoundTextInput: Range<Int> = 0 ..< 0
/**
* 显示QQ表情的表情面板,已被设置了默认的`didSelectEmotionBlock`和`didSelectDeleteButtonBlock`,在`QMUIQQEmotionManager`初始化完后,即可将`emotionView`添加到界面上。
*/
let emotionView: QMUIEmotionView = QMUIEmotionView()
init() {
emotionView.didSelectEmotionClosure = { [weak self] _, emotion in
guard let strongSelf = self else {
return
}
guard let notNilBoundInputView = strongSelf.boundInputView() else {
return
}
var inputText = notNilBoundInputView.text
// 用一个局部变量先保存selectedRangeForBoundTextInput的值,是为了避免在接下来这段代码执行的过程中,外部可能修改了self.selectedRangeForBoundTextInput的值,导致计算错误
var selectedRange = strongSelf.selectedRangeForBoundTextInput
if selectedRange.lowerBound <= inputText.length {
// 在输入框文字的中间插入表情
var mutableText = inputText
mutableText.insert(contentsOf: emotion.displayName, at: mutableText.index(mutableText.startIndex, offsetBy: selectedRange.lowerBound))
notNilBoundInputView.text = mutableText
selectedRange = (mutableText.length + emotion.displayName.length) ..< (mutableText.length + emotion.displayName.length)
} else {
// 在输入框文字的结尾插入表情
inputText = "\(inputText)\(emotion.displayName)"
notNilBoundInputView.text = inputText
selectedRange = inputText.length ..< inputText.length
}
strongSelf.selectedRangeForBoundTextInput = selectedRange
}
emotionView.didSelectDeleteButtonClosure = { [weak self] in
self?.deleteEmotionDisplayNameAtCurrentSelectedRange(force: true)
}
}
private func boundInputView() -> QMUIQQEmotionInputViewProtocol? {
if let notNilBoundTextField = boundTextField as? QMUIQQEmotionInputViewProtocol {
return notNilBoundTextField
} else if let notNilBoundTextView = boundTextView as? QMUIQQEmotionInputViewProtocol {
return notNilBoundTextView
}
return nil
}
/**
* 将当前光标所在位置的表情删除,在调用前请注意更新`selectedRangeForBoundTextInput`
* @param forceDelete 当没有删除掉表情的情况下(可能光标前面并不是一个表情字符),要不要强制删掉光标前的字符。YES表示强制删掉,NO表示不删,交给系统键盘处理
* @return 表示是否成功删除了文字(如果并不是删除表情,而是删除普通字符,也是返回YES)
*/
@discardableResult
func deleteEmotionDisplayNameAtCurrentSelectedRange(force: Bool) -> Bool {
guard let notNilBoundInputView = self.boundInputView() else {
return false
}
let selectedRange = selectedRangeForBoundTextInput
var text = notNilBoundInputView.text
// 没有文字或者光标位置前面没文字
if text.length <= 0 || selectedRange.upperBound == 0 {
return false
}
var hasDeleteEmotionDisplayNameSuccess = false
let emotionDisplayNameMinimumLength = 3 // QQ表情里的最短displayName的长度
let lengthForStringBeforeSelectedRange = selectedRange.lowerBound
let lastCharacterBeforeSelectedRange = text[selectedRange.lowerBound - 1 ..< selectedRange.lowerBound]
if lastCharacterBeforeSelectedRange == "]" && lengthForStringBeforeSelectedRange >= emotionDisplayNameMinimumLength {
let beginIndex = lengthForStringBeforeSelectedRange - (emotionDisplayNameMinimumLength - 1) // 从"]"之前的第n个字符开始查找
let endIndex = max(0, lengthForStringBeforeSelectedRange - 5) // 直到"]"之前的第n个字符结束查找,这里写5只是简单的限定,这个数字只要比所有QQ表情的displayName长度长就行了
for i in (endIndex ... beginIndex).reversed() {
let checkingCharacter = text[i ..< i + 1]
if checkingCharacter == "]" {
// 查找过程中还没遇到"["就已经遇到"]"了,说明是非法的表情字符串,所以直接终止
break
}
if checkingCharacter == "[" {
let deletingDisplayNameRange: Range<Int> = i ..< lengthForStringBeforeSelectedRange - i
notNilBoundInputView.text = text.replace(deletingDisplayNameRange, with: "")
selectedRangeForBoundTextInput = deletingDisplayNameRange.lowerBound ..< deletingDisplayNameRange.lowerBound
hasDeleteEmotionDisplayNameSuccess = true
break
}
}
}
if hasDeleteEmotionDisplayNameSuccess {
return true
}
if force {
if selectedRange.upperBound <= text.length {
if selectedRange.count > 0 {
// 如果选中区域是一段文字,则删掉这段文字
notNilBoundInputView.text = text.replace(selectedRange, with: "")
selectedRangeForBoundTextInput = selectedRange.lowerBound ..< selectedRange.lowerBound
} else if selectedRange.lowerBound > 0 {
// 如果并没有选中一段文字,则删掉光标前一个字符
let textAfterDelete = text.qmui_stringByRemoveCharacter(at: selectedRange.lowerBound - 1)
notNilBoundInputView.text = textAfterDelete
let startIndex = selectedRange.lowerBound - (text.length - textAfterDelete.length)
selectedRangeForBoundTextInput = startIndex ..< startIndex
}
} else {
// 选中区域超过文字长度了,非法数据,则直接删掉最后一个字符
notNilBoundInputView.text = text.qmui_stringByRemoveLastCharacter()
selectedRangeForBoundTextInput = notNilBoundInputView.text.length ..< notNilBoundInputView.text.length
}
return true
}
return false
}
/**
* 在 `UITextViewDelegate` 的 `textView:shouldChangeTextInRange:replacementText:` 或者 `QMUITextFieldDelegate` 的 `textField:shouldChangeTextInRange:replacementText:` 方法里调用,根据返回值来决定是否应该调用 `deleteEmotionDisplayNameAtCurrentSelectedRangeForce:`
@param range 要发生变化的文字所在的range
@param text 要被替换为的文字
@return 是否会接管键盘的删除按钮事件,`YES` 表示接管,可调用 `deleteEmotionDisplayNameAtCurrentSelectedRangeForce:` 方法,`NO` 表示不可接管,应该使用系统自身的删除事件响应。
*/
func shouldTakeOverControlDeleteKeyWithChangeText(in range: Range<Int>, replacementText: String) -> Bool {
let isDeleteKeyPressed = replacementText.length == 0 && (boundInputView()?.text.length ?? 0) - 1 == range.lowerBound
let hasMarkedText = boundInputView()?.markedTextRange != nil
return isDeleteKeyPressed && !hasMarkedText
}
static let QQEmotionString = "0-[微笑];1-[撇嘴];2-[色];3-[发呆];4-[得意];5-[流泪];6-[害羞];7-[闭嘴];8-[睡];9-[大哭];10-[尴尬];11-[发怒];12-[调皮];13-[呲牙];14-[惊讶];15-[难过];16-[酷];17-[冷汗];18-[抓狂];19-[吐];20-[偷笑];21-[可爱];22-[白眼];23-[傲慢];24-[饥饿];25-[困];26-[惊恐];27-[流汗];28-[憨笑];29-[大兵];30-[奋斗];31-[咒骂];32-[疑问];33-[嘘];34-[晕];35-[折磨];36-[衰];37-[骷髅];38-[敲打];39-[再见];40-[擦汗];41-[抠鼻];42-[鼓掌];43-[糗大了];44-[坏笑];45-[左哼哼];46-[右哼哼];47-[哈欠];48-[鄙视];49-[委屈];50-[快哭了];51-[阴险];52-[亲亲];53-[吓];54-[可怜];55-[菜刀];56-[西瓜];57-[啤酒];58-[篮球];59-[乒乓];60-[咖啡];61-[饭];62-[猪头];63-[玫瑰];64-[凋谢];65-[示爱];66-[爱心];67-[心碎];68-[蛋糕];69-[闪电];70-[炸弹];71-[刀];72-[足球];73-[瓢虫];74-[便便];75-[月亮];76-[太阳];77-[礼物];78-[拥抱];79-[强];80-[弱];81-[握手];82-[胜利];83-[抱拳];84-[勾引];85-[拳头];86-[差劲];87-[爱你];88-[NO];89-[OK];90-[爱情];91-[飞吻];92-[跳跳];93-[发抖];94-[怄火];95-[转圈];96-[磕头];97-[回头];98-[跳绳];99-[挥手];100-[激动];101-[街舞];102-[献吻];103-[左太极];104-[右太极];105-[嘿哈];106-[捂脸];107-[奸笑];108-[机智];109-[皱眉];110-[耶];111-[红包];112-[鸡]"
static var QQEmotionArray = [QMUIEmotion]()
/**
* QQ表情的数组,会做缓存,图片只会加载一次
*/
static func emotionsForQQ() -> [QMUIEmotion] {
if QQEmotionArray.count > 0 {
return QQEmotionArray
}
var emotions = [QMUIEmotion]()
let emotionStringArray = QQEmotionString.split(separator: ";").map { String($0) }
for emotionString in emotionStringArray {
let emotionItem = emotionString.split(separator: "-").map { String($0) }
let identifier = "smiley_\(emotionItem.first!)"
let emotion = QMUIEmotion(identifier: identifier, displayName: emotionItem.last!)
emotions.append(emotion)
}
QQEmotionArray = emotions
asyncLoadImages(emotions)
return QQEmotionArray
}
// 子线程预加载
static func asyncLoadImages(_ emotions: [QMUIEmotion]) {
DispatchQueue.global().async {
emotions.forEach { e in
_ = e.image
}
}
}
}
extension String {
mutating func replace(_ range: Range<Int>, with str: String) -> String {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound, limitedBy: self.endIndex) ?? self.startIndex
let endIndex = index(self.startIndex, offsetBy: range.upperBound, limitedBy: self.endIndex) ?? self.startIndex
replaceSubrange(startIndex ..< endIndex, with: str)
return self
}
}
| mit | 4056f8406421ce0bb6b2cb98914c2707 | 46.413953 | 932 | 0.649304 | 3.648533 | false | false | false | false |
omarojo/MyC4FW | Pods/C4/C4/UI/Star.swift | 2 | 2513 | // Copyright © 2014 C4
//
// 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 CoreGraphics
/// Star is a concrete subclass of Polygon that defines a star shape.
public class Star: Polygon {
/// Initializes a new Star shape.
///
/// ````
/// let star = Star(
/// center: canvas.center,
/// pointCount: 5,
/// innerRadius: 50,
/// outerRadius: 100)
/// canvas.add(star)
/// ````
///
/// - parameter center: The center of the star
/// - parameter pointCount: The number of points on the star
/// - parameter innerRadius: The radial distance from the center of the star to the inner points
/// - parameter outerRadius: The radial distance from the center of the start to the outer points
convenience public init(center: Point, pointCount: Int, innerRadius: Double, outerRadius: Double) {
let wedgeAngle = 2.0 * M_PI / Double(pointCount)
var angle = M_PI/Double(pointCount)-M_PI_2
var pointArray = [Point]()
for i in 0..<pointCount * 2 {
angle += wedgeAngle / 2.0
if i % 2 != 0 {
pointArray.append(Point(innerRadius * cos(angle), innerRadius * sin(angle)))
} else {
pointArray.append(Point(outerRadius * cos(angle), outerRadius * sin(angle)))
}
}
self.init(pointArray)
self.close()
self.fillColor = C4Blue
self.center = center
}
}
| mit | c1a5c24717dc779055b7ae48f7ce5964 | 40.180328 | 103 | 0.664411 | 4.446018 | false | false | false | false |
CoderLala/DouYZBTest | DouYZB/DouYZB/Classes/Home/View/RecommendGameView.swift | 1 | 2554 | //
// RecommendGameView.swift
// DouYZB
//
// Created by 黄金英 on 17/2/9.
// Copyright © 2017年 黄金英. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin : CGFloat = 10
class RecommendGameView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
// MARK: 定义数据的属性
var groups : [AnchorGroup]? {
didSet {
//1. 移除前两组数据
groups?.removeFirst()
groups?.removeFirst()
//添加更多组
let moreGroup = AnchorGroup()
moreGroup.tag_name = "更多"
groups?.append(moreGroup)
// 刷新表格
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// 让控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
// 注册Cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 给collectionView添加内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: 80.0, height: 90.0)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.showsHorizontalScrollIndicator = false
}
}
//MARK:- 提供快速创建的类方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = groups![(indexPath as NSIndexPath).item]
return cell
}
}
| mit | b1111d88d7eb592898d1739657f1d1f3 | 28.716049 | 126 | 0.647279 | 5.495434 | false | false | false | false |
jamy0801/LGWeChatKit | LGWeChatKit/LGChatKit/Extension/CGRectEx.swift | 1 | 2238 | //
// CGRectEx.swift
// LGChatViewController
//
// Created by gujianming on 15/10/8.
// Copyright © 2015年 jamy. All rights reserved.
//
import UIKit
extension CGRect {
var x: CGFloat {
get {
return self.origin.x
}
set {
self = CGRectMake(newValue, self.minY, self.width, self.height)
}
}
var y: CGFloat {
get {
return self.origin.y
}
set {
self = CGRectMake(self.x, newValue, self.width, self.height)
}
}
var width: CGFloat {
get {
return self.size.width
}
set {
self = CGRectMake(self.x, self.width, newValue, self.height)
}
}
var height: CGFloat {
get {
return self.size.height
}
set {
self = CGRectMake(self.x, self.minY, self.width, newValue)
}
}
var top: CGFloat {
get {
return self.origin.y
}
set {
y = newValue
}
}
var bottom: CGFloat {
get {
return self.origin.y + self.size.height
}
set {
self = CGRectMake(x, newValue - height, width, height)
}
}
var left: CGFloat {
get {
return self.origin.x
}
set {
self.x = newValue
}
}
var right: CGFloat {
get {
return x + width
}
set {
self = CGRectMake(newValue - width, y, width, height)
}
}
var midX: CGFloat {
get {
return self.x + self.width / 2
}
set {
self = CGRectMake(newValue - width / 2, y, width, height)
}
}
var midY: CGFloat {
get {
return self.y + self.height / 2
}
set {
self = CGRectMake(x, newValue - height / 2, width, height)
}
}
var center: CGPoint {
get {
return CGPointMake(self.midX, self.midY)
}
set {
self = CGRectMake(newValue.x - width / 2, newValue.y - height / 2, width, height)
}
}
} | mit | ec3c58735694fa699bbd34c8f971ef7d | 18.787611 | 93 | 0.442953 | 4.273423 | false | false | false | false |
cloudmine/android-gcm-example | ios/gcm/GcmServerDemo/MasterViewController.swift | 46 | 4116 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AppKit
import Cocoa
class MasterViewController: NSViewController, NSTextFieldDelegate {
let sendUrl = "https://android.googleapis.com/gcm/send"
let subscriptionTopic = "/topics/global"
@IBOutlet weak var apiKeyTextField: NSTextField!
@IBOutlet weak var regIdTextField: NSTextField!
@IBOutlet weak var sendNotificationButton: NSButton!
@IBOutlet weak var displayCurlButton: NSButton!
@IBOutlet weak var curlCommandTextView: NSScrollView!
@IBOutlet weak var sendToTopicButton: NSButton!
override func controlTextDidChange(obj: NSNotification) {
// Length checks just to ensure that the text fields don't contain just a couple of chars
if count(apiKeyTextField.stringValue.utf16) >= 30 {
sendToTopicButton.enabled = true
if count(regIdTextField.stringValue.utf16) >= 30 {
sendNotificationButton.enabled = true
displayCurlButton.enabled = true
} else {
sendNotificationButton.enabled = false
displayCurlButton.enabled = false
}
} else {
sendToTopicButton.enabled = false
}
}
@IBAction func didClickSendNotification(sender: NSButton) {
sendMessage(getRegToken())
}
@IBAction func didClickDisplaycURL(sender: NSButton) {
let message = getMessage(getRegToken())
var jsonError:NSError?
let jsonBody = NSJSONSerialization.dataWithJSONObject(message, options: nil, error: &jsonError)
if (jsonError == nil) {
let payload = NSString(data: jsonBody!, encoding: NSUTF8StringEncoding)
let escapedPayload = payload?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
let command = "curl --header \"Authorization: key=\(getApiKey())\"" +
" --header Content-Type:\"application/json\" \(sendUrl) -d \"\(escapedPayload!)\""
curlCommandTextView.documentView!.setString(command)
} else {
NSAlert(error: jsonError!).runModal()
}
}
@IBAction func didClickSendToTopic(sender: NSButton) {
sendMessage(subscriptionTopic)
}
func sendMessage(to: String) {
// Create the request.
var request = NSMutableURLRequest(URL: NSURL(string: sendUrl)!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=\(getApiKey())", forHTTPHeaderField: "Authorization")
request.timeoutInterval = 60
// prepare the payload
let message = getMessage(to)
var jsonError:NSError?
let jsonBody = NSJSONSerialization.dataWithJSONObject(message, options: nil, error: &jsonError)
if (jsonError == nil) {
request.HTTPBody = jsonBody
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(),
completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error != nil {
NSAlert(error: error).runModal()
} else {
println("Success! Response from the GCM server:")
println(response)
}
})
} else {
NSAlert(error: jsonError!).runModal()
}
}
func getMessage(to: String) -> NSDictionary {
// [START notification_format]
return ["to": to, "notification": ["body": "Hello from GCM"]]
// [END notification_format]
}
func getApiKey() -> String {
return apiKeyTextField.stringValue.stringByReplacingOccurrencesOfString("\n", withString: "")
}
func getRegToken() -> String {
return regIdTextField.stringValue.stringByReplacingOccurrencesOfString("\n", withString: "")
}
}
| apache-2.0 | 53edcb1a5ff64759b39a3434c9eaf2e2 | 35.424779 | 100 | 0.699466 | 4.583519 | false | false | false | false |
pollarm/XCGLogger | Tests/XCGLoggerTests/XCGLoggerTests.swift | 6 | 57559 | //
// XCGLoggerTests.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2014-06-09.
// Copyright © 2014 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import XCTest
@testable import XCGLogger
/// Tests
class XCGLoggerTests: XCTestCase {
/// This file's fileName for use in testing expected log messages
let fileName = { return (#file as NSString).lastPathComponent }()
/// Calculate a base identifier to use for the giving function name.
///
/// - Parameters:
/// - functionName: Normally omitted **Default:** *#function*.
///
/// - Returns: A string to use as the base identifier for objects in the test
///
func functionIdentifier(_ functionName: StaticString = #function) -> String {
return "\(XCGLogger.Constants.baseIdentifier).\(functionName)"
}
/// Set up prior to each test
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
/// Tear down after each test
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func testExample() {
// // This is an example of a functional test case.
// XCTAssert(true, "Pass")
// }
//
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measureBlock() {
// // Put the code you want to measure the time of here.
// }
// }
/// Test that if we request the default instance multiple times, we always get the same instance
func test_00010_defaultInstance() {
let defaultInstance1: XCGLogger = XCGLogger.default
let defaultInstance2: XCGLogger = XCGLogger.default
XCTAssert(defaultInstance1 === defaultInstance2, "Fail: default is not returning a common instance")
}
/// Test that if we request the multiple instances, we get different instances
func test_00020_distinctInstances() {
let instance1: XCGLogger = XCGLogger()
instance1.identifier = "instance1"
let instance2: XCGLogger = XCGLogger()
instance2.identifier = "instance2" // this should not affect instance1
XCTAssert(instance1.identifier != instance2.identifier, "Fail: same instance is being returned")
}
/// Test our default instance starts with the correct default destinations
func test_00022_defaultInstanceDestinations() {
let defaultInstance: XCGLogger = XCGLogger.default
let consoleDestination: ConsoleDestination? = defaultInstance.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination
XCTAssert(consoleDestination != nil, "Fail: default console destination not attached to our default instance")
XCTAssert(defaultInstance.destinations.count == 1, "Fail: Incorrect number of destinations on our default instance")
let log = XCGLogger(identifier: functionIdentifier(), includeDefaultDestinations: false)
XCTAssert(log.destinations.count == 0, "Fail: Logger included default destinations when it shouldn't have")
}
/// Test that we can add additional destinations
func test_00030_addDestination() {
let log = XCGLogger(identifier: functionIdentifier())
let destinationCountAtStart = log.destinations.count
let additionalConsoleLogger = ConsoleDestination(identifier: log.identifier + ".second.console")
let additionSuccess = log.add(destination: additionalConsoleLogger)
let destinationCountAfterAddition = log.destinations.count
XCTAssert(additionSuccess, "Fail: didn't add additional destination")
XCTAssert(destinationCountAtStart == (destinationCountAfterAddition - 1), "Fail: didn't add additional destination")
}
/// Test we can remove existing destinations
func test_00040_removeDestination() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let destinationCountAtStart = log.destinations.count
let removeSuccess = log.remove(destinationWithIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier)
let destinationCountAfterRemoval = log.destinations.count
XCTAssert(removeSuccess, "Fail: didn't remove destination")
XCTAssert(destinationCountAtStart == (destinationCountAfterRemoval + 1), "Fail: didn't remove destination")
let nonExistantDestination: DestinationProtocol? = log.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier)
XCTAssert(nonExistantDestination == nil, "Fail: didn't remove specified destination")
}
/// Test that we can not add a destination with a duplicate identifier
func test_00050_denyAdditionOfDestinationWithDuplicateIdentifier() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testIdentifier = log.identifier + ".testIdentifier"
let additionalConsoleLogger = ConsoleDestination(identifier: testIdentifier)
let additionalConsoleLogger2 = ConsoleDestination(identifier: testIdentifier)
let additionSuccess = log.add(destination: additionalConsoleLogger)
let destinationCountAfterAddition = log.destinations.count
let additionSuccess2 = log.add(destination: additionalConsoleLogger2)
let destinationCountAfterAddition2 = log.destinations.count
XCTAssert(additionSuccess, "Fail: didn't add additional destination")
XCTAssert(!additionSuccess2, "Fail: didn't prevent adding additional destination with a duplicate identifier")
XCTAssert(destinationCountAfterAddition == destinationCountAfterAddition2, "Fail: didn't prevent adding additional destination with a duplicate identifier")
}
/// Test a destination has it's owner set correctly when added to or removed from a logger
func test_00052_checkDestinationOwner() {
let log1: XCGLogger = XCGLogger(identifier: functionIdentifier() + ".1")
XCTAssert(log1.destinations.count == 1, "Fail: Logger didn't include the correct default destinations")
let log2: XCGLogger = XCGLogger(identifier: functionIdentifier() + ".2", includeDefaultDestinations: false)
XCTAssert(log2.destinations.count == 0, "Fail: Logger included default destinations when it shouldn't have")
let consoleDestination: ConsoleDestination! = log1.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination
XCTAssert(consoleDestination != nil, "Fail: Didn't add our default destination")
XCTAssert(consoleDestination.owner === log1, "Fail: default destination did not have the correct owner set")
log1.remove(destination: consoleDestination)
XCTAssert(consoleDestination.owner == nil, "Fail: removed destination didn't have it's owner cleared")
log1.add(destination: consoleDestination)
XCTAssert(consoleDestination.owner === log1, "Fail: added destination didn't have it's owner set correctly")
log2.add(destination: consoleDestination)
XCTAssert(consoleDestination.owner === log2, "Fail: moved destination didn't have it's owner set correctly")
}
/// Test a file destination correctly opens a file
func test_00054_fileDestinationOpenedFile() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let logPath: String = NSTemporaryDirectory().appending("XCGLogger_\(UUID().uuidString).log")
var fileDestination: FileDestination = FileDestination(writeToFile: logPath, identifier: log.identifier + ".fileDestination.1", shouldAppend: true)
XCTAssert(fileDestination.owner == nil, "Fail: newly created FileDestination has an owner set when it should be nil")
XCTAssert(fileDestination.logFileHandle == nil, "Fail: FileDestination has opened a file before it was assigned to a logger")
log.add(destination: fileDestination)
XCTAssert(fileDestination.owner === log, "Fail: file destination did not have the correct owner set")
XCTAssert(fileDestination.logFileHandle != nil, "Fail: FileDestination been assigned to a logger, but no file has been opened")
log.remove(destination: fileDestination)
fileDestination = FileDestination(owner: log, writeToFile: logPath, identifier: log.identifier + ".fileDestination.2", shouldAppend: true)
XCTAssert(fileDestination.owner === log, "Fail: file destination did not have the correct owner set")
XCTAssert(fileDestination.logFileHandle != nil, "Fail: FileDestination been assigned to a logger, but no file has been opened")
}
func test_00055_checkExtendedFileAttributeURLExtensions() {
let fileManager: FileManager = FileManager.default
let testFileURL: URL = URL(fileURLWithPath: NSTemporaryDirectory().appending("XCGLogger_\(UUID().uuidString).txt"))
let sampleData: Data = functionIdentifier().data(using: .utf8) ?? "\(Date())".data(using: .utf8)!
let testKey: String = XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey
fileManager.createFile(atPath: testFileURL.path, contents: sampleData)
var extendedAttributes: [String] = try! testFileURL.listExtendedAttributes()
XCTAssert(extendedAttributes.count == 0, "Fail: new file should have no extended attributes")
var attributeData: Data? = try! testFileURL.extendedAttribute(forName: testKey)
XCTAssert(attributeData == nil, "Fail: new file should not have a specific extended attribute")
try? testFileURL.setExtendedAttribute(data: sampleData, forName: testKey)
attributeData = try! testFileURL.extendedAttribute(forName: testKey)
XCTAssert(attributeData == sampleData, "Fail: write, then read of sample data resulted in mismatched data")
extendedAttributes = try! testFileURL.listExtendedAttributes()
XCTAssert(extendedAttributes.count == 1 && extendedAttributes.first ?? "" == testKey, "Fail: test file should have 1 extended attribute that we just set")
try? testFileURL.removeExtendedAttribute(forName: testKey)
extendedAttributes = try! testFileURL.listExtendedAttributes()
XCTAssert(extendedAttributes.count == 0, "Fail: file should have no extended attributes once we remove the one we set")
try? fileManager.removeItem(at: testFileURL)
}
/// Test that log destination correctly rotates file
func test_00056_checkAutoRotatingFileDestinationBehavesAsExpected() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
if var logConsoleDestination = log.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) {
logConsoleDestination.outputLevel = .info
}
let logFileURL: URL = URL(fileURLWithPath: NSTemporaryDirectory().appending("XCGLogger_\(UUID().uuidString).log"))
let autoRotatingFileDestination: AutoRotatingFileDestination = AutoRotatingFileDestination(writeToFile: logFileURL, identifier: log.identifier + ".autoRotatingFileDestination.\(UUID().uuidString)")
log.add(destination: autoRotatingFileDestination)
var autoRotationClosureExecuted: Bool = false
autoRotatingFileDestination.autoRotationCompletion = { (success: Bool) -> Void in
autoRotationClosureExecuted = true
}
var archivedLogURLs: [URL] = autoRotatingFileDestination.archivedFileURLs()
XCTAssert(archivedLogURLs.count == 0, "Fail: new logger should not have any archived files")
// Test auto rotation by file size
autoRotatingFileDestination.targetMaxFileSize = 2048
autoRotatingFileDestination.targetMaxLogFiles = 3
autoRotatingFileDestination.targetMaxTimeInterval = 3600
for _ in 0 ... 512 {
log.debug("\(autoRotatingFileDestination.identifier)")
Thread.sleep(forTimeInterval: 0.05)
}
archivedLogURLs = autoRotatingFileDestination.archivedFileURLs()
XCTAssert(archivedLogURLs.count > 0, "Fail: logger should have rotated log files")
XCTAssert(archivedLogURLs.count < Int(autoRotatingFileDestination.targetMaxLogFiles) * 2, "Fail: logger should have removed some archived log files")
XCTAssert(autoRotationClosureExecuted, "Fail: logger hasn't executed the auto rotation closure")
// Test our archivedLogURLs are sorted
// - Note: sorting by filename here works because we're using a known date formatter that includes the date in a sortable order.
// - If using a custom date formatter, sorting by filename may or may not work, which is why we're using the extended attributes,
// - they allow us to sort correctly regardless of filename.
let archivedLogURLsSortedByName: [URL] = archivedLogURLs.sorted { (lhs: URL, rhs: URL) -> Bool in
return lhs.path > rhs.path
}
XCTAssert(archivedLogURLs == archivedLogURLsSortedByName, "Fail: archivedLogURLs not sorted correctly")
autoRotatingFileDestination.rotateFile()
autoRotatingFileDestination.purgeArchivedLogFiles()
archivedLogURLs = autoRotatingFileDestination.archivedFileURLs()
XCTAssert(archivedLogURLs.count == 0, "Fail: logger should not have any archived files after purging")
// Test auto rotation by time interval
autoRotatingFileDestination.targetMaxFileSize = .max
autoRotatingFileDestination.targetMaxLogFiles = 3
autoRotatingFileDestination.targetMaxTimeInterval = 2
for _ in 0 ... 30 {
log.debug("\(autoRotatingFileDestination.identifier)")
Thread.sleep(forTimeInterval: 0.25)
}
archivedLogURLs = autoRotatingFileDestination.archivedFileURLs()
XCTAssert(archivedLogURLs.count > 0, "Fail: logger should have rotated log files")
XCTAssert(archivedLogURLs.count < Int(autoRotatingFileDestination.targetMaxLogFiles) * 2, "Fail: logger should have removed some archived log files")
autoRotatingFileDestination.purgeArchivedLogFiles()
// Test storing archives in an alternate folder
let alternateArchiveFolderURL: URL = URL(fileURLWithPath: NSTemporaryDirectory().appending("XCGLogger_Archives"))
autoRotatingFileDestination.archiveFolderURL = alternateArchiveFolderURL
log.debug("\(autoRotatingFileDestination.identifier)")
autoRotatingFileDestination.rotateFile()
archivedLogURLs = autoRotatingFileDestination.archivedFileURLs()
if let archivedLogURL = archivedLogURLs.first {
XCTAssert(archivedLogURL.resolvingSymlinksInPath().deletingLastPathComponent().path == alternateArchiveFolderURL.resolvingSymlinksInPath().path, "Fail: archived logs are not in the alternate archived log folder")
}
else {
XCTAssert(false, "Fail: should have been an archived log file to test it's path")
}
autoRotatingFileDestination.purgeArchivedLogFiles()
}
/// Test that closures for a log aren't executed via string interpolation if they aren't needed
func test_00060_avoidStringInterpolationWithAutoclosure() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
class ObjectWithExpensiveDescription: CustomStringConvertible {
var descriptionInvoked = false
var description: String {
descriptionInvoked = true
return "expensive"
}
}
let thisObject = ObjectWithExpensiveDescription()
log.verbose("The description of \(thisObject) is really expensive to create")
XCTAssert(!thisObject.descriptionInvoked, "Fail: String was interpolated when it shouldn't have been")
}
/// Test that closures for a log execute when required
func test_00070_execExecutes() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
var numberOfTimes: Int = 0
log.debug {
numberOfTimes += 1
return "executed closure correctly"
}
log.debug("executed: \(numberOfTimes) time(s)")
XCTAssert(numberOfTimes == 1, "Fail: Didn't execute the closure when it should have")
}
/// Test that closures execute exactly once, even when being logged to multiple destinations, and even if they return nil
func test_00080_execExecutesExactlyOnceWithNilReturnAndMultipleDestinations() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
let logPath: String = NSTemporaryDirectory().appending("XCGLogger_\(UUID().uuidString).log")
log.setup(level: .debug, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath)
var numberOfTimes: Int = 0
log.debug {
numberOfTimes += 1
return nil
}
log.debug("executed: \(numberOfTimes) time(s)")
XCTAssert(numberOfTimes == 1, "Fail: Didn't execute the closure exactly once")
}
/// Test that closures for a log aren't executed if they aren't needed
func test_00090_execDoesntExecute() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .error
var numberOfTimes: Int = 0
log.debug {
numberOfTimes += 1
return "executed closure incorrectly"
}
log.outputLevel = .debug
log.debug("executed: \(numberOfTimes) time(s)")
XCTAssert(numberOfTimes == 0, "Fail: Didn't execute the closure when it should have")
}
/// Test that we correctly cache date formatter objects, and don't create new ones each time
func test_00100_dateFormatterIsCached() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
let dateFormatter1 = log.dateFormatter
let dateFormatter2 = log.dateFormatter
XCTAssert(dateFormatter1 === dateFormatter2, "Fail: Received two different date formatter objects")
}
/// Test our custom date formatter works
func test_00110_customDateFormatter() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let defaultDateFormatter = log.dateFormatter
let alternateDateFormat = "MM/dd/yyyy h:mma"
let alternateDateFormatter = DateFormatter()
alternateDateFormatter.dateFormat = alternateDateFormat
log.dateFormatter = alternateDateFormatter
log.debug("Test date format is different than our default")
XCTAssertNotNil(log.dateFormatter, "Fail: date formatter is nil")
XCTAssertEqual(log.dateFormatter!.dateFormat, alternateDateFormat, "Fail: date format doesn't match our custom date format")
XCTAssert(defaultDateFormatter != alternateDateFormatter, "Fail: Did not assign a custom date formatter")
// We add this destination after the normal log.debug() call above (that's for humans to look at), because
// there's a chance when the test runs, that we could cross time boundaries (ie, second [or even the year])
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = true
log.add(destination: testDestination)
// We force the date for this part of the test to ensure a change of date as the test runs doesn't break the test
let knownDate = Date(timeIntervalSince1970: 0)
let message = "Testing date format output matches what we expect"
testDestination.add(expectedLogMessage: "\(alternateDateFormatter.string(from: knownDate)) [\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(message)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
let knownLogDetails = LogDetails(level: .debug, date: knownDate, message: message, functionName: #function, fileName: #file, lineNumber: #line)
testDestination.process(logDetails: knownLogDetails)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test that we can log a variety of different object types
func test_00120_variousParameters() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.setup(level: .verbose, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil)
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.outputLevel = .verbose
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.info)] [\(fileName)] \(#function) > testVariousParameters starting")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.info("testVariousParameters starting")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.verbose)] [\(fileName)] \(#function) > ")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.verbose()
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
// Should not log anything, so there are no expected log messages
log.verbose { return nil }
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > 1.2")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug(1.2)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.info)] [\(fileName)] \(#function) > true")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.info(true)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.warning)] [\(fileName)] \(#function) > [\"a\", \"b\", \"c\"]")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.warning(["a", "b", "c"])
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
let knownDate = Date(timeIntervalSince1970: 0)
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.error)] [\(fileName)] \(#function) > \(knownDate)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.error { return knownDate }
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
let optionalString: String? = "text"
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.severe)] [\(fileName)] \(#function) > \(optionalString ?? "")")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.severe(optionalString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test our noMessageClosure works as expected
func test_00130_noMessageClosure() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let checkDefault = String(describing: log.noMessageClosure() ?? "__unexpected__")
XCTAssert(checkDefault == "", "Fail: Default noMessageClosure doesn't return expected value")
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > ")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug()
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
log.noMessageClosure = { return "***" }
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > ***")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug()
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
let knownDate = Date(timeIntervalSince1970: 0)
log.noMessageClosure = { return knownDate }
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(knownDate)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug()
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
log.noMessageClosure = { return nil }
// Should not log anything, so there are no expected log messages
log.debug()
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
func test_00140_queueName() {
let logQueue = DispatchQueue(label: functionIdentifier() + ".serialQueue.😆")
let labelDirectlyRead: String = logQueue.label
var labelExtracted: String? = nil
logQueue.sync {
labelExtracted = DispatchQueue.currentQueueLabel
}
XCTAssert(labelExtracted != nil, "Fail: Didn't get a label for the current queue")
print("labelDirectlyRead: `\(labelDirectlyRead)`")
print("labelExtracted: `\(labelExtracted!)`")
XCTAssert(labelDirectlyRead == labelExtracted!, "Fail: Didn't get the correct queue label")
}
func test_00150_extractTypeName() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let className: String = extractTypeName(log)
let stringName: String = extractTypeName(className)
let intName: String = extractTypeName(4)
let optionalString: String? = nil
let optionalName: String = extractTypeName(optionalString as Any)
log.debug("className: \(className)")
log.debug("stringName: \(stringName)")
log.debug("intName: \(intName)")
log.debug("optionalName: \(optionalName)")
XCTAssert(className == "XCGLogger", "Fail: Didn't extract the correct class name")
XCTAssert(stringName == "String", "Fail: Didn't extract the correct class name")
XCTAssert(intName == "Int", "Fail: Didn't extract the correct class name")
XCTAssert(optionalName == "Optional<String>", "Fail: Didn't extract the correct class name")
}
func test_00160_testLogFormattersAreApplied() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let testString: String = "Black on Blue"
let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter()
ansiColorLogFormatter.colorize(level: .debug, with: .blue, on: .black, options: [.bold])
log.formatters = [ansiColorLogFormatter]
testDestination.add(expectedLogMessage: "\(ANSIColorLogFormatter.escape)34;40;1m[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(testString)\(ANSIColorLogFormatter.reset)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
let xcodeColorsLogFormatter: XcodeColorsLogFormatter = XcodeColorsLogFormatter()
xcodeColorsLogFormatter.colorize(level: .debug, with: .black, on: .blue)
log.formatters = [xcodeColorsLogFormatter]
testDestination.add(expectedLogMessage: "\(XcodeColorsLogFormatter.escape)fg0,0,0;\(XcodeColorsLogFormatter.escape)bg0,0,255;[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(testString)\(XcodeColorsLogFormatter.reset)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
let base64LogFormatter: Base64LogFormatter = Base64LogFormatter()
log.formatters = [base64LogFormatter]
// "[Debug] [XCGLoggerTests.swift] test_00160_testLogFormattersAreApplied() > Black on Blue" base64 encoded
testDestination.add(expectedLogMessage: "W0RlYnVnXSBbWENHTG9nZ2VyVGVzdHMuc3dpZnRdIHRlc3RfMDAxNjBfdGVzdExvZ0Zvcm1hdHRlcnNBcmVBcHBsaWVkKCkgPiBCbGFjayBvbiBCbHVl")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test log level override strings work
func test_00170_levelDescriptionOverrides() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let testString = "Every human being has a basic instinct: to help each other out."
// Override at the logger level
log.levelDescriptions[.severe] = "❌"
testDestination.add(expectedLogMessage: "[❌] [\(fileName)] \(#function) > \(testString)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.severe(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
// Override at the destination level
testDestination.levelDescriptions[.severe] = "❌❌❌"
testDestination.add(expectedLogMessage: "[❌❌❌] [\(fileName)] \(#function) > \(testString)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.severe(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test prefix/postfix formatter works
func test_00180_prePostFixLogFormatter() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .verbose
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
testDestination.outputLevel = .verbose
log.add(destination: testDestination)
let testString = "Everything is awesome!"
let prePostFixLogFormatter = PrePostFixLogFormatter()
// Set a specific level
prePostFixLogFormatter.apply(prefix: "🗯🗯🗯", postfix: "🗯🗯🗯", to: .verbose)
prePostFixLogFormatter.apply(prefix: "🔹🔹🔹", postfix: "🔹🔹🔹", to: .debug)
prePostFixLogFormatter.apply(prefix: "ℹ️ℹ️ℹ️", postfix: "ℹ️ℹ️ℹ️", to: .info)
prePostFixLogFormatter.apply(prefix: "⚠️⚠️⚠️", postfix: "⚠️⚠️⚠️", to: .warning)
prePostFixLogFormatter.apply(prefix: "‼️‼️‼️", postfix: "‼️‼️‼️", to: .error)
prePostFixLogFormatter.apply(prefix: "💣💣💣", postfix: "💣💣💣", to: .severe)
log.formatters = [prePostFixLogFormatter]
testDestination.add(expectedLogMessage: "🗯🗯🗯[\(XCGLogger.Level.verbose)] [\(fileName)] \(#function) > \(testString)🗯🗯🗯")
testDestination.add(expectedLogMessage: "🔹🔹🔹[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(testString)🔹🔹🔹")
testDestination.add(expectedLogMessage: "ℹ️ℹ️ℹ️[\(XCGLogger.Level.info)] [\(fileName)] \(#function) > \(testString)ℹ️ℹ️ℹ️")
testDestination.add(expectedLogMessage: "⚠️⚠️⚠️[\(XCGLogger.Level.warning)] [\(fileName)] \(#function) > \(testString)⚠️⚠️⚠️")
testDestination.add(expectedLogMessage: "‼️‼️‼️[\(XCGLogger.Level.error)] [\(fileName)] \(#function) > \(testString)‼️‼️‼️")
testDestination.add(expectedLogMessage: "💣💣💣[\(XCGLogger.Level.severe)] [\(fileName)] \(#function) > \(testString)💣💣💣")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 6, "Fail: Didn't correctly load all of the expected log messages")
log.verbose(testString)
log.debug(testString)
log.info(testString)
log.warning(testString)
log.error(testString)
log.severe(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
// Set no prefix, no postfix, and no level, should clear everything
prePostFixLogFormatter.apply()
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.info)] [\(fileName)] \(#function) > \(testString)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.info(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
// Set with no level specified, so it should be applied to all levels
prePostFixLogFormatter.apply(prefix: ">>> ", postfix: " <<<")
testDestination.add(expectedLogMessage: ">>> [\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(testString) <<<")
testDestination.add(expectedLogMessage: ">>> [\(XCGLogger.Level.warning)] [\(fileName)] \(#function) > \(testString) <<<")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 2, "Fail: Didn't correctly load all of the expected log messages")
log.debug(testString)
log.warning(testString)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
func test_00200_testLogFiltersAreApplied() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let message = "Filters are more powerful than they first appear, since they can also change the content of log messages"
let exclusiveFileNameFilter: FileNameFilter = FileNameFilter(excludeFrom: [fileName])
log.filters = [exclusiveFileNameFilter]
// Should not log anything, so there are no expected log messages
log.debug(message)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
let inclusiveFileNameFilter: FileNameFilter = FileNameFilter(includeFrom: [fileName])
log.filters = [inclusiveFileNameFilter]
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(message)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug(message)
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
func test_00210_testTagFilter() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let normalMessage = "The WiFi SSID is: strange"
let sensitiveMessage = "The WiFi password is: shamballa"
let sensitiveTag = "Sensitive"
// No filter
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(normalMessage)")
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(sensitiveMessage)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 2, "Fail: Didn't correctly load all of the expected log messages")
log.debug(normalMessage)
log.debug(sensitiveMessage, userInfo: [XCGLogger.Constants.userInfoKeyTags: sensitiveTag])
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
// Exclude messages tagged as sensitive
let exclusiveTagFilter: TagFilter = TagFilter(excludeFrom: [sensitiveTag])
log.filters = [exclusiveTagFilter]
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(normalMessage)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug(normalMessage)
log.debug(sensitiveMessage, userInfo: [XCGLogger.Constants.userInfoKeyTags: [sensitiveTag]])
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
// Include only messages that are sensitive
let inclusiveTagFilter: TagFilter = TagFilter(includeFrom: [sensitiveTag])
log.filters = [inclusiveTagFilter]
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(sensitiveMessage)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.debug(normalMessage)
log.debug(sensitiveMessage, userInfo: [XCGLogger.Constants.userInfoKeyTags: Set<String>([sensitiveTag])])
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
func test_00220_testDevFilter() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let daveMessage = "Hmm, checking this thing, and that thing, and then this other thing..."
let sabbyMessage = "Yeah it works...Moving on..."
let dave = "DW"
let sabby = "SW"
let chatterBoxCount = 2
// No filter
for _ in 0 ..< chatterBoxCount {
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(daveMessage)")
}
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(sabbyMessage)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == chatterBoxCount + 1, "Fail: Didn't correctly load all of the expected log messages")
log.logAppDetails() // adds two unexpected log messages, since we haven't added these to the expected list above
for _ in 0 ..< chatterBoxCount {
log.debug(daveMessage, userInfo: [XCGLogger.Constants.userInfoKeyDevs: dave])
}
log.debug(sabbyMessage, userInfo: [XCGLogger.Constants.userInfoKeyDevs: sabby])
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 2, "Fail: Received an unexpected log line")
testDestination.reset()
// Exclude log messages added by a chatter box developer
let exclusiveDevFilter: DevFilter = DevFilter(excludeFrom: [dave])
log.filters = [exclusiveDevFilter]
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(sabbyMessage)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.logAppDetails() // adds two unexpected log messages, since we haven't added these to the expected list above
for _ in 0 ..< chatterBoxCount {
log.debug(daveMessage, userInfo: [XCGLogger.Constants.userInfoKeyDevs: dave])
}
log.debug(sabbyMessage, userInfo: [XCGLogger.Constants.userInfoKeyDevs: sabby])
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 2, "Fail: Received an unexpected log line")
testDestination.reset()
// Include only messages by one developer (lets them focus on only their info)
let inclusiveDevFilter: DevFilter = DevFilter(includeFrom: [sabby])
inclusiveDevFilter.applyFilterToInternalMessages = true // This will mean internal (ie appDetails etc) messages will be subject to the same filter rules as normal messages
log.filters = [inclusiveDevFilter]
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(sabbyMessage)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
log.logAppDetails() // this time this shouldn't add additional unexpected messages, since these should be filtered because they weren't logged by sabby
for _ in 0 ..< chatterBoxCount {
log.debug(daveMessage, userInfo: [XCGLogger.Constants.userInfoKeyDevs: dave])
}
log.debug(sabbyMessage, userInfo: [XCGLogger.Constants.userInfoKeyDevs: sabby])
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test Objective-C Exception Handling
func test_00300_objectiveCExceptionHandling() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.outputLevel = .debug
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let exceptionMessage: String = "Objective-C Exception"
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(exceptionMessage)")
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 1, "Fail: Didn't correctly load all of the expected log messages")
_try({
_throw(name: exceptionMessage)
},
catch: { (exception: NSException) in
log.debug(exception)
})
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test logging works correctly when logs are generated from multiple threads
func test_01010_multiThreaded() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil)
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
testDestination.logQueue = DispatchQueue(label: log.identifier + ".serialQueue")
log.add(destination: testDestination)
let linesToLog = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
for lineToLog in linesToLog {
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(lineToLog)")
}
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == linesToLog.count, "Fail: Didn't correctly load all of the expected log messages")
let myConcurrentQueue = DispatchQueue(label: log.identifier + ".concurrentQueue", attributes: .concurrent)
myConcurrentQueue.sync {
DispatchQueue.concurrentPerform(iterations: linesToLog.count) { (index: Int) -> () in
log.debug(linesToLog[index])
}
}
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test logging with closures works correctly when generated from multiple threads
func test_01020_multiThreaded2() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier())
log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil)
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
testDestination.logQueue = DispatchQueue(label: log.identifier + ".serialQueue")
log.add(destination: testDestination)
let linesToLog = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
for lineToLog in linesToLog {
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(lineToLog)")
}
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == linesToLog.count, "Fail: Didn't correctly load all of the expected log messages")
let myConcurrentQueue = DispatchQueue(label: log.identifier + ".concurrentQueue", attributes: .concurrent)
myConcurrentQueue.sync {
DispatchQueue.concurrentPerform(iterations: linesToLog.count) { (index: Int) -> () in
log.debug {
return "\(linesToLog[index])"
}
}
}
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
/// Test that our background processing works
func test_01030_backgroundLogging() {
let log: XCGLogger = XCGLogger(identifier: functionIdentifier(), includeDefaultDestinations: false)
let systemDestination = AppleSystemLogDestination(identifier: log.identifier + ".systemDestination")
systemDestination.outputLevel = .debug
systemDestination.showThreadName = true
// Note: The thread name included in the log message should be "main" even though the log is processed in a background thread. This is because
// it uses the thread name of the thread the log function is called in, not the thread used to do the output.
systemDestination.logQueue = DispatchQueue.global(qos: .background)
log.add(destination: systemDestination)
let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
testDestination.showThreadName = false
testDestination.showLevel = true
testDestination.showFileName = true
testDestination.showLineNumber = false
testDestination.showDate = false
log.add(destination: testDestination)
let linesToLog = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
for lineToLog in linesToLog {
testDestination.add(expectedLogMessage: "[\(XCGLogger.Level.debug)] [\(fileName)] \(#function) > \(lineToLog)")
}
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == linesToLog.count, "Fail: Didn't correctly load all of the expected log messages")
for line in linesToLog {
log.debug(line)
}
XCTAssert(testDestination.remainingNumberOfExpectedLogMessages == 0, "Fail: Didn't receive all expected log lines")
XCTAssert(testDestination.numberOfUnexpectedLogMessages == 0, "Fail: Received an unexpected log line")
}
// Performance Testing
// func test_80000_BasicPerformanceTest() {
// let log: XCGLogger = XCGLogger(identifier: functionIdentifier(), includeDefaultDestinations: false)
// log.outputLevel = .debug
//
// let testDestination: TestDestination = TestDestination(identifier: log.identifier + ".testDestination")
// testDestination.showLogIdentifier = true
// testDestination.showFunctionName = true
// testDestination.showThreadName = true
// testDestination.showFileName = true
// testDestination.showLineNumber = true
// testDestination.showLevel = true
// testDestination.showDate = true
// log.add(destination: testDestination)
//
// self.measure() {
// for _ in 1 ..< 100 {
// for _ in 1 ..< 1000 {
// log.debug("Thanks for all the fish!")
// }
// testDestination.reset()
// }
// }
// // 2.224, relative standard deviation: 2.820%, values: [2.361247, 2.271706, 2.268338, 2.179494, 2.182855, 2.177256, 2.187814, 2.191347, 2.148568, 2.272234]
// // 2.281, relative standard deviation: 3.712%, values: [2.393395, 2.443988, 2.328165, 2.206496, 2.160873, 2.304157, 2.256671, 2.273773, 2.252598, 2.189970]
// // 2.301, relative standard deviation: 2.122%, values: [2.377062, 2.386740, 2.347364, 2.262827, 2.289801, 2.294484, 2.272225, 2.252910, 2.240331, 2.290241]
// }
func test_99999_lastTest() {
// Add a final test that just waits a second, so any tests using the background can finish outputting results
Thread.sleep(forTimeInterval: 1.0)
}
}
| mit | c8c3a9fc646c786df17a9a7d19fe202d | 55.888779 | 236 | 0.704523 | 5.283316 | false | true | false | false |
BalestraPatrick/TweetsCounter | Carthage/Checkouts/Swifter/SwifterDemoiOS/AuthViewController.swift | 2 | 4578 | //
// AuthViewController.swift
// SwifterDemoiOS
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import Accounts
import Social
import SwifteriOS
import SafariServices
class AuthViewController: UIViewController, SFSafariViewControllerDelegate {
var swifter: Swifter
// Default to using the iOS account framework for handling twitter auth
let useACAccount = false
required init?(coder aDecoder: NSCoder) {
self.swifter = Swifter(consumerKey: "nLl1mNYc25avPPF4oIzMyQzft",
consumerSecret: "Qm3e5JTXDhbbLl44cq6WdK00tSUwa17tWlO8Bf70douE4dcJe2")
super.init(coder: aDecoder)
}
@IBAction func didTouchUpInsideLoginButton(_ sender: AnyObject) {
let failureHandler: (Error) -> Void = { error in
self.alert(title: "Error", message: error.localizedDescription)
}
if useACAccount {
let accountStore = ACAccountStore()
let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
// Prompt the user for permission to their twitter account stored in the phone's settings
accountStore.requestAccessToAccounts(with: accountType, options: nil) { granted, error in
guard granted else {
self.alert(title: "Error", message: error!.localizedDescription)
return
}
let twitterAccounts = accountStore.accounts(with: accountType)!
if twitterAccounts.isEmpty {
self.alert(title: "Error", message: "There are no Twitter accounts configured. You can add or create a Twitter account in Settings.")
} else {
let twitterAccount = twitterAccounts[0] as! ACAccount
self.swifter = Swifter(account: twitterAccount)
self.fetchTwitterHomeStream()
}
}
} else {
let url = URL(string: "swifter://success")!
swifter.authorize(withCallback: url, presentingFrom: self, success: { _, _ in
self.fetchTwitterHomeStream()
}, failure: failureHandler)
}
}
func fetchTwitterHomeStream() {
let failureHandler: (Error) -> Void = { error in
self.alert(title: "Error", message: error.localizedDescription)
}
self.swifter.getHomeTimeline(count: 20, success: { json in
// Successfully fetched timeline, so lets create and push the table view
let tweetsViewController = self.storyboard!.instantiateViewController(withIdentifier: "TweetsViewController") as! TweetsViewController
guard let tweets = json.array else { return }
tweetsViewController.tweets = tweets
self.navigationController?.pushViewController(tweetsViewController, animated: true)
}, failure: failureHandler)
}
func alert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@available(iOS 9.0, *)
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
| mit | 1a48123eeca984c35d55b79d2e8410a5 | 41.388889 | 153 | 0.662298 | 4.949189 | false | false | false | false |
PJayRushton/stats | Stats/SwipeTransitionAnimator.swift | 2 | 5378 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
class SwipeTransitionAnimator: NSObject {
var targetEdge: UIRectEdge
var presentingCornerRadius: CGFloat
var dimmingBackgroundColor: UIColor?
fileprivate static let dimmingTag = -635
init(targetEdge: UIRectEdge, presentingCornerRadius: CGFloat, dimmingBackgroundColor: UIColor? = nil) {
self.targetEdge = targetEdge
self.presentingCornerRadius = presentingCornerRadius
self.dimmingBackgroundColor = dimmingBackgroundColor
super.init()
}
}
// MARK: - View controller animated transitioning
extension SwipeTransitionAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
let defaultDuration: TimeInterval = 0.4
guard let context = transitionContext else { return defaultDuration }
return context.isInteractive ? 0.7 : defaultDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewController(forKey: .from),
let toViewController = transitionContext.viewController(forKey: .to)
else { return }
let containerView = transitionContext.containerView
let fromView = transitionContext.view(forKey: .from)
let toView = transitionContext.view(forKey: .to)
let isPresenting = toViewController.presentingViewController == fromViewController
let fromFrame = transitionContext.initialFrame(for: fromViewController)
let toFrame = transitionContext.finalFrame(for: toViewController)
if isPresenting {
toView?.clipsToBounds = true
}
let offset: CGVector
switch targetEdge {
case .top:
offset = CGVector(dx: 0, dy: -1)
if #available(iOSApplicationExtension 11.0, *), isPresenting {
toView?.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
}
case .bottom:
offset = CGVector(dx: 0, dy: 1)
if #available(iOSApplicationExtension 11.0, *), isPresenting {
toView?.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
case .left:
offset = CGVector(dx: -1, dy: 0)
if #available(iOSApplicationExtension 11.0, *), isPresenting {
toView?.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
}
case .right:
offset = CGVector(dx: 1, dy: 0)
if #available(iOSApplicationExtension 11.0, *), isPresenting {
toView?.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
}
default:
fatalError("targetEdge must be .top, .bottom, .left, or .right. actual=\(targetEdge)")
}
var adjustedFromFrame = fromFrame
if isPresenting {
toView?.frame = toFrame.offsetBy(dx: toFrame.width * offset.dx, dy: toFrame.height * offset.dy)
fromView?.frame = fromFrame
} else {
toView?.frame = toFrame
if transitionContext.presentationStyle == .formSheet {
adjustedFromFrame.origin.x = containerView.frame.width / 2 - adjustedFromFrame.width / 2
}
}
let dimmingView = UIView()
if let toView = toView, isPresenting {
dimmingView.backgroundColor = dimmingBackgroundColor ?? UIColor(white: 0, alpha: 0.5)
dimmingView.alpha = 0
dimmingView.frame = containerView.bounds
dimmingView.tag = SwipeTransitionAnimator.dimmingTag
dimmingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
containerView.addSubview(dimmingView)
containerView.addSubview(toView)
} else if let toView = toView, let fromView = fromView {
containerView.insertSubview(toView, belowSubview: fromView)
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
if isPresenting {
toView?.frame = toFrame
toView?.layer.cornerRadius = self.presentingCornerRadius
dimmingView.alpha = 1.0
} else {
fromView?.layer.cornerRadius = 0.0
fromView?.frame = adjustedFromFrame.offsetBy(dx: fromFrame.width * offset.dx, dy: fromFrame.height * offset.dy)
if let dimming = containerView.subviews.first(where: { $0.tag == SwipeTransitionAnimator.dimmingTag }) {
dimming.alpha = 0.0
}
}
}) { _ in
let wasCancelled = transitionContext.transitionWasCancelled
if wasCancelled {
toView?.removeFromSuperview()
} else if !isPresenting {
if let dimming = containerView.subviews.first(where: { $0.tag == SwipeTransitionAnimator.dimmingTag }) {
dimming.removeFromSuperview()
}
}
transitionContext.completeTransition(!wasCancelled)
}
}
}
| mit | bbe0a66a19b3ed32b84939ad63224010 | 40.78125 | 127 | 0.615557 | 5.570833 | false | false | false | false |
miDrive/MDAlert | MDAlert/Classes/MDAlertController.swift | 1 | 7784 | //
// MDAlertController.swift
// miDrive Insurance
//
// Created by Chris Byatt on 08/06/2016.
// Copyright © 2016 miDrive. All rights reserved.
//
import UIKit
open class MDAlertController: NSObject {
fileprivate var alertViewController: MDAlertView!
open var alertBackgroundColour: UIColor = MDAlertViewDefaults.alertBackgroundColour
open var alertCornerRadius: CGFloat = MDAlertViewDefaults.alertCornerRadius
open var titleFont: UIFont = MDAlertViewDefaults.titleFont
open var bodyFont: UIFont = MDAlertViewDefaults.bodyFont
open var titleColour: UIColor = MDAlertViewDefaults.titleColour
open var bodyColour: UIColor = MDAlertViewDefaults.bodyColour
open var actionHeight: CGFloat = MDAlertViewDefaults.alertButtonHeight
open var actionDefaultBackgroundColour: UIColor = MDAlertViewDefaults.actionDefaultBackgroundColour
open var actionCancelBackgroundColour: UIColor = MDAlertViewDefaults.actionCancelBackgroundColour
open var actionDestructiveBackgroundColour: UIColor = MDAlertViewDefaults.actionDestructiveBackgroundColour
open var actionDefaultTitleColour: UIColor = MDAlertViewDefaults.actionDefaultTitleColour
open var actionCancelTitleColour: UIColor = MDAlertViewDefaults.actionCancelTitleColour
open var actionDestructiveTitleColour: UIColor = MDAlertViewDefaults.actionDestructiveTitleColour
open var actionTitleFont: UIFont = MDAlertViewDefaults.actionTitleFont
public init(title: String, message: String? = nil, customView: UIView? = nil, showsCancel: Bool = true) {
super.init()
let podBundle = Bundle(for: self.classForCoder)
if let bundleURL = podBundle.url(forResource: "MDAlert", withExtension: "bundle"), let bundle = Bundle(url: bundleURL) {
let storyboard = UIStoryboard(name: "MDAlert", bundle: bundle)
let alertView = storyboard.instantiateViewController(withIdentifier: "MDAlert") as! MDAlertView
alertView.controller = self
self.alertViewController = alertView
self.alertViewController.titleMessage = title
self.alertViewController.bodyMessage = message
alertViewController.customView = customView
alertViewController.showsCancel = showsCancel
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name:UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name:UIResponder.keyboardWillHideNotification, object: nil)
}
}
public init(image: UIImage, title: String, message: String? = nil, customView: UIView? = nil, showsCancel: Bool = true) {
super.init()
let podBundle = Bundle(for: self.classForCoder)
if let bundleURL = podBundle.url(forResource: "MDAlert", withExtension: "bundle"), let bundle = Bundle(url: bundleURL) {
let storyboard = UIStoryboard(name: "MDAlert", bundle: bundle)
let alertView = storyboard.instantiateViewController(withIdentifier: "MDAlert") as! MDAlertView
alertView.controller = self
alertViewController = alertView
alertViewController.image = image
alertViewController.titleMessage = title
alertViewController.bodyMessage = message
alertViewController.customView = customView
alertViewController.showsCancel = showsCancel
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name:UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name:UIResponder.keyboardWillHideNotification, object: nil)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open func addAction(_ action: MDAlertAction) {
action.controller = self
action.button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
alertViewController.actions.append(action)
}
open func show() {
if let topViewController = UIApplication.topViewController() {
self.alertViewController.modalPresentationStyle = .overCurrentContext
topViewController.present(alertViewController, animated: false, completion: {
self.insertAlert()
})
}
}
func dismiss(_ action: (() -> ())?) {
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseIn, animations: {
self.alertViewController.alertView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.alertViewController.view.alpha = 0.0
}, completion: { finished in
self.alertViewController.dismiss(animated: false, completion: {
if let action = action {
action()
}
})
})
}
@objc fileprivate func buttonPressed(_ button: UIButton) {
if let buttonIndex = self.alertViewController.buttonView.subviews.index(of: button) {
let action = self.alertViewController.actions[buttonIndex]
if let pressedAction = action.action {
if action.dismissAlert {
self.dismiss({
pressedAction(action)
})
} else {
pressedAction(action)
}
} else {
self.dismiss(nil)
}
}
}
fileprivate func insertAlert() {
self.alertViewController.alertView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
self.alertViewController.alertView.center = self.alertViewController.view.center
UIView.animate(withDuration: 0.2, delay: 0.0, animations: {
self.alertViewController.view.alpha = 1.0
self.alertViewController.alertView.alpha = 1.0
self.alertViewController.alertView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}, completion: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
if let info = notification.userInfo {
let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions(), animations: {
if #available(iOS 11.0, *) {
self.alertViewController.viewMidConstraint?.constant = -(keyboardFrame.size.height / 2)
} else {
self.alertViewController.viewMidConstraint?.constant = -(keyboardFrame.size.height / 2)
}
}, completion: nil)
}
}
@objc func keyboardWillHide(_ notification: Notification) {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions(), animations: {
self.alertViewController.viewMidConstraint?.constant = 0
}, completion: nil)
}
}
extension UIApplication {
class func topViewController(_ base: UIViewController? = UIApplication.shared.delegate!.window!!.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
}
| mit | 69b1c20d24014f0f1b41f890e77ae4f3 | 43.729885 | 159 | 0.665296 | 5.408617 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/ContentListingViewController.swift | 1 | 8353 | //
// ViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 01/04/17.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import UIKit
import reddift
import SDWebImage
import PagingMenuController
import MaterialComponents.MaterialSnackbar
class ContentListingViewController: MediaViewController, UITableViewDelegate, UITableViewDataSource {
var baseData: ContributionLoader
var session: Session? = nil
weak var tableView : UITableView!
/* override func previewActionItems() -> [UIPreviewActionItem] {
let regularAction = UIPreviewAction(title: "Regular", style: .Default) { (action: UIPreviewAction, vc: UIViewController) -> Void in
}
let destructiveAction = UIPreviewAction(title: "Destructive", style: .Destructive) { (action: UIPreviewAction, vc: UIViewController) -> Void in
}
let actionGroup = UIPreviewActionGroup(title: "Group...", style: .Default, actions: [regularAction, destructiveAction])
return [regularAction, destructiveAction, actionGroup]
}*/
init(dataSource: ContributionLoader){
baseData = dataSource
super.init(nibName:nil, bundle:nil)
baseData.delegate = self
setBarColors(color: baseData.color)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView(){
self.view = UITableView(frame: CGRect.zero, style: .plain)
self.tableView = self.view as! UITableView
self.tableView.delegate = self
self.tableView.dataSource = self
tableView.backgroundColor = ColorUtil.backgroundColor
tableView.separatorColor = ColorUtil.backgroundColor
tableView.separatorInset = .zero
refreshControl = UIRefreshControl()
self.tableView.contentOffset = CGPoint.init(x: 0, y: -self.refreshControl.frame.size.height)
refreshControl.tintColor = ColorUtil.fontColor
refreshControl.attributedTitle = NSAttributedString(string: "")
refreshControl.addTarget(self, action: #selector(self.drefresh(_:)), for: UIControlEvents.valueChanged)
tableView.addSubview(refreshControl) // not required when using UITableViewController
}
func failed(error: Error){
print(error)
}
func drefresh(_ sender:AnyObject) {
refresh()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 400.0
tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.register(LinkTableViewCell.classForCoder(), forCellReuseIdentifier: "submission")
self.tableView.register(CommentCellView.classForCoder(), forCellReuseIdentifier: "comment")
self.tableView.register(MessageCellView.classForCoder(), forCellReuseIdentifier: "message")
session = (UIApplication.shared.delegate as! AppDelegate).session
refresh()
//todo self.shyNavBarManager.scrollView = self.tableView;
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
var tC: UIViewController?
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return baseData.content.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let thing = baseData.content[indexPath.row]
var cell: UITableViewCell?
if(thing is RSubmission){
let c = tableView.dequeueReusableCell(withIdentifier: "submission", for: indexPath) as! LinkTableViewCell
c.setLink(submission: (thing as! RSubmission), parent: self, nav: self.navigationController, baseSub: "all")
cell = c
} else if thing is RComment {
let c = tableView.dequeueReusableCell(withIdentifier: "comment", for: indexPath) as! CommentCellView
c.setComment(comment: (thing as! RComment), parent: self, nav: self.navigationController, width: self.view.frame.size.width)
cell = c
} else {
let c = tableView.dequeueReusableCell(withIdentifier: "message", for: indexPath) as! MessageCellView
c.setMessage(message: (thing as! RMessage), parent: self, nav: self.navigationController, width: self.view.frame.size.width)
cell = c
}
if indexPath.row == baseData.content.count - 1 && !loading && baseData.canGetMore {
self.loadMore()
}
return cell!
}
var showing = false
func showLoader() {
showing = true
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.frame = CGRect(x: 0, y: 0.0, width: 80.0, height: 80.0)
spinner.center = CGPoint(x: tableView.frame.size.width / 2,
y: tableView.frame.size.height / 2);
tableView.tableFooterView = spinner
spinner.startAnimating()
}
var sort = LinkSortType.hot
var time = TimeFilterWithin.day
func showMenu(){
let actionSheetController: UIAlertController = UIAlertController(title: "Sorting", message: "", preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
for link in LinkSortType.cases {
let saveActionButton: UIAlertAction = UIAlertAction(title: link.description, style: .default)
{ action -> Void in
self.showTimeMenu(s: link)
}
actionSheetController.addAction(saveActionButton)
}
//todo ipad popover controller
self.present(actionSheetController, animated: true, completion: nil)
}
func showTimeMenu(s: LinkSortType){
if(s == .hot || s == .new){
sort = s
refresh()
return
} else {
let actionSheetController: UIAlertController = UIAlertController(title: "Sorting", message: "", preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
for t in TimeFilterWithin.cases {
let saveActionButton: UIAlertAction = UIAlertAction(title: t.param, style: .default)
{ action -> Void in
self.sort = s
self.time = t
self.refresh()
}
actionSheetController.addAction(saveActionButton)
}
//todo iPad popover controller
self.present(actionSheetController, animated: true, completion: nil)
}
}
var refreshControl: UIRefreshControl!
func refresh(){
tableView.reloadData()
refreshControl.beginRefreshing()
loading = true
baseData.getData(reload: true)
}
func loadMore(){
if(!showing){
showLoader()
}
loading = true
baseData.getData(reload: false)
}
var loading: Bool = false
func doneLoading(){
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.loading = false
if(baseData.content.count == 0){
let message = MDCSnackbarMessage()
message.text = "No content found"
MDCSnackbarManager.show(message)
}
}
}
| apache-2.0 | 591c7b30e1133dc3335933480501b152 | 35 | 148 | 0.627275 | 5.340153 | false | false | false | false |
jyothepro/PuzzleNineSwift | Escape/ViewController.swift | 1 | 3035 | //
// ViewController.swift
// Escape
//
// Created by Jyothidhar Pulakunta on 6/6/14.
// Copyright (c) 2014 Jyothidhar Pulakunta. All rights reserved.
//
import UIKit
let PuzzleSize:Int = 60;
let StartX:Int = 60;
let StartY:Int = 100;
let Space:Int = 10;
class ViewController: UIViewController {
var puzzleModel:Model;
var moves:UILabel;
init(coder aDecoder: NSCoder!) {
puzzleModel = Model()
moves = UILabel()
super.init(coder: aDecoder)
}
init(nibName: String!,nibBundle: NSBundle!) {
puzzleModel = Model()
moves = UILabel()
super.init(nibName: nibName, bundle: nibBundle)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.moves = UILabel(frame:CGRectMake(200, 50, 50, 20));
self.moves.text = "0";
var numMoves:UILabel = UILabel(frame:CGRectMake(75, 50, 100, 20));
numMoves.text = "Moves";
self.view.addSubview(numMoves)
self.view.addSubview(moves)
placeViews()
}
func placeViews() {
let postions:Dictionary<Int, CGRect> = self.puzzleModel.positionForTiles(Double(StartX), y: Double(StartY), side: Double(PuzzleSize), space: Double(Space))
for i in reverse(0...postions.count-2) {
var view: UIView = UIView(frame: postions[i]!)
if (i != 8) {
view.backgroundColor = UIColor(red: 52.0/255.0, green: 170.0/255.0, blue: 220.0/255.0, alpha: 1.0)
var label:UILabel = UILabel(frame:CGRectMake(25.0, 20.0, 30.0, 30.0))
label.text = String(i+1)
label.textColor = UIColor(red: 51.0/255.0, green:51.0/255.0, blue:51.0/255.0, alpha:1.0)
label.font = UIFont(name: "DamascusBold", size: 20.0)
view.addSubview(label)
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target:self, action:"handleGesture:")
tap.enabled = true
tap.numberOfTapsRequired = 1
view.tag = i+1
view.addGestureRecognizer(tap)
view.userInteractionEnabled = true
}
self.view.addSubview(view);
}
}
func handleGesture(gestureRecognizer:UIGestureRecognizer ) {
if (gestureRecognizer.view.tag >= 1 && gestureRecognizer.view.tag <= 8) {
//Check if the view can animate
let canAnimate:Bool = self.puzzleModel.isValidMove(gestureRecognizer.view.tag-1, space: Double(Space))
//Animate the view to the new position
if (canAnimate) {
UIView.animateWithDuration(1, animations: {
let temp: CGRect = self.puzzleModel.positionForTile(8)
let oldValue: CGRect = self.puzzleModel.positionForTile(gestureRecognizer.view.tag - 1)
self.puzzleModel.setPositionForTile(gestureRecognizer.view.tag - 1, value: temp)
self.puzzleModel.setPositionForTile(8, value: oldValue)
gestureRecognizer.view.frame = temp
//Update number of moves
self.updateNumMoves()
})
}
}
}
func updateNumMoves() {
let curMoves:String = self.moves.text
self.moves.text = String(curMoves.toInt()! + 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 71dadf8abf11734005feaaf5439bca1c | 27.101852 | 157 | 0.700494 | 3.228723 | false | false | false | false |
tonystone/coherence | Sources/Container/StoreConfiguration+Resolve.swift | 1 | 1488 | ///
/// StoreConfiguration+Extensions.swift
/// Pods
///
/// Created by Tony Stone on 4/23/17.
///
///
import Swift
import CoreData
extension StoreConfiguration {
///
/// Returns a new Configuration resolved against the defaultBundleLocation and bundleName.
///
internal func resolveURL(defaultStorePrefix: String, storeLocation: URL) -> URL? {
///
/// If this is an InMemory type store, assign nil since it should not have a file
/// associated with it. otherwise resolve the path
///
if self.type == NSInMemoryStoreType {
return nil
}
///
/// If the user did not supply a URL, we build a default URL based on the parameter defaults
/// and what is contained in the configuration.
///
if let fileName = self.fileName {
return storeLocation.appendingPathComponent(fileName)
}
return StoreConfiguration.storeURL(prefix: defaultStorePrefix, configuration: self.name, type: self.type, location: storeLocation)
}
internal /// @testable
static func storeURL(prefix: String, configuration: String? = nil, type: String, location: URL) -> URL {
var storeName = prefix
if let configurationName = configuration {
storeName.append(".\(configurationName.lowercased())")
}
storeName.append(".\(type.lowercased())")
return location.appendingPathComponent("\(storeName)")
}
}
| apache-2.0 | c4b0429a17c4d4a6625db3d8834a859a | 29.367347 | 138 | 0.634409 | 5.044068 | false | true | false | false |
OlegNovosad/Sample | iOS/Severenity/Views/Profile/ProfileGridViewController.swift | 2 | 1972 | //
// GridViewControllerCollectionViewController.swift
// severenityProject
//
// Created by Yura Yasinskyy on 12.09.16.
// Copyright © 2016 severenity. All rights reserved.
//
import UIKit
class ProfileGridViewController: UICollectionViewController {
internal var presenter: ProfileGridPresenter?
internal var dataForList = [String]()
// MARK: Init
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
presenter = ProfileGridPresenter()
presenter?.delegate = self
Log.info(message: "ProfileGrid VIPER module init did complete", sender: self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Loading view
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(UINib(nibName: "ProfileGridCell", bundle: nil), forCellWithReuseIdentifier: "ProfileCellInGrid")
collectionView?.backgroundColor = UIColor.black
presenter?.provideProfileGridData()
}
// MARK: UICollectionView data source
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 75
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProfileCellInGrid", for: indexPath)
return cell
}
}
// MARK: ProfileGridPresenter delegate
extension ProfileGridViewController: ProfileGridPresenterDelegate {
func profileGridPresenterDidCallView(withData data: [String]) {
Log.info(message: "ProfileGridPresenter did call ProfileGridViewController", sender: self)
}
}
| apache-2.0 | 730b7290425fc920c856f593637e1469 | 29.323077 | 130 | 0.705733 | 5.355978 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Common/CoachMessages/CoachMarkView.swift | 1 | 4108 | //
// 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 UIKit
import Reusable
/// `CoachMarkView` is used to display an information bubble view with a given text.
@objcMembers
class CoachMarkView: UIView, NibLoadable, Themable {
// MARK: Constants
public static var TopLeftPosition: CGPoint {
if UIDevice.current.orientation.isPortrait {
return CGPoint(x: 16, y: 40)
} else {
return CGPoint(x: 16, y: 32)
}
}
enum MarkPosition: Int {
case topLeft
case topRight
case bottomLeft
case bottomRight
}
// MARK: Private
@IBOutlet private weak var backgroundView: UIImageView!
@IBOutlet private weak var textLabel: UILabel!
@IBOutlet private weak var textLabelTopMargin: NSLayoutConstraint!
@IBOutlet private weak var textLabelBottomMargin: NSLayoutConstraint!
private var text: String? {
didSet {
textLabel.text = text
}
}
private var markPosition: MarkPosition = .topLeft
private var position: CGPoint!
// MARK: Setup
class func instantiate(text: String?, from position: CGPoint, markPosition: MarkPosition) -> Self {
let view = Self.loadFromNib()
view.text = text
view.position = position
view.markPosition = markPosition
return view
}
// MARK: UIView
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
setupView()
if newSuperview != nil {
update(theme: ThemeService.shared().theme)
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = superview else {
return
}
let layoutGuide = superview.safeAreaLayoutGuide
translatesAutoresizingMaskIntoConstraints = false
leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: position.x).isActive = true
topAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: position.y).isActive = true
}
// MARK: Themable
func update(theme: Theme) {
textLabel.textColor = theme.colors.background
textLabel.font = theme.fonts.bodySB
backgroundView.tintColor = theme.colors.accent
}
// MARK: Private
private func setupView() {
let image: UIImage = Asset.Images.coachMark.image
let imageSize = image.size
let center = CGPoint(x: ceil(imageSize.width / 2), y: ceil(imageSize.height / 2))
backgroundView.image = image.resizableImage(withCapInsets: .init(top: center.y - 1, left: center.x - 1, bottom: center.y + 1, right: center.x + 1), resizingMode: .stretch)
switch markPosition {
case .topLeft:
backgroundView.transform = .identity
case .topRight:
backgroundView.transform = .init(scaleX: -1, y: 1)
case .bottomLeft:
backgroundView.transform = .init(scaleX: 1, y: -1)
invertVerticalMargins()
case .bottomRight:
backgroundView.transform = .init(scaleX: -1, y: -1)
invertVerticalMargins()
}
textLabel.text = text
}
private func invertVerticalMargins() {
let temp = self.textLabelTopMargin.constant
self.textLabelTopMargin.constant = self.textLabelBottomMargin.constant
self.textLabelBottomMargin.constant = temp
}
}
| apache-2.0 | 8b4cf321116fb842c7fe6437b7500dd9 | 31.09375 | 179 | 0.639727 | 4.91976 | false | false | false | false |
recurly/recurly-client-ios | RecurlySDK-iOS/Models/REApplePaymentMethod.swift | 1 | 729 | //
// REApplePaymentMethod.swift
// RecurlySDK-iOS
//
// Created by Carlos Landaverde on 22/6/22.
//
import Foundation
public struct REApplePaymentMethod: Codable {
let paymentMethod: REApplePaymentMethodBody
public init(paymentMethod: REApplePaymentMethodBody = REApplePaymentMethodBody()) {
self.paymentMethod = paymentMethod
}
}
public struct REApplePaymentMethodBody: Codable {
let displayName: String
let network: String
let type: String
public init(displayName: String = String(),
network: String = String(),
type: String = String()) {
self.displayName = displayName
self.network = network
self.type = type
}
}
| mit | ebf2c52a6a7988b3e17af55f6defe569 | 23.3 | 87 | 0.66118 | 4.55625 | false | false | false | false |
Jakobeha/lAzR4t | lAzR4t Shared/Code/Play/HeartElemNode.swift | 1 | 3147 | //
// HeartElemNode.swift
// lAzR4t
//
// Created by Jakob Hain on 9/30/17.
// Copyright © 2017 Jakob Hain. All rights reserved.
//
import SpriteKit
class HeartElemNode: ElemShapeNode {
///How light the heart's colors are: 0 for black and 1 for full color.
static let colorLightness: CGFloat = 0.75
static func fillColor(healthRatio: CGFloat, direction: PlayerDirection) -> SKColor {
///Fades from opaque (full health) to clear (no health)
switch direction {
case .left:
return SKColor(
calibratedRed: HeartElemNode.colorLightness,
green: 0,
blue: 0,
alpha: healthRatio
)
case .right:
return SKColor(
calibratedRed: 0,
green: 0,
blue: HeartElemNode.colorLightness,
alpha: healthRatio
)
}
}
static func path(cellFrame: CellFrame, direction: PlayerDirection) -> CGPath {
let curPath = CGMutablePath()
switch direction {
case .left:
curPath.move(to: CellPos(x: cellFrame.left, y: cellFrame.top).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.right - 1, y: cellFrame.top).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.right, y: cellFrame.top - 1).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.right, y: cellFrame.bottom + 1).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.right - 1, y: cellFrame.bottom).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.left, y: cellFrame.bottom).toDisplay)
curPath.closeSubpath()
break
case .right:
curPath.move(to: CellPos(x: cellFrame.right, y: cellFrame.top).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.left + 1, y: cellFrame.top).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.left, y: cellFrame.top - 1).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.left, y: cellFrame.bottom + 1).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.left + 1, y: cellFrame.bottom).toDisplay)
curPath.addLine(to: CellPos(x: cellFrame.right, y: cellFrame.bottom).toDisplay)
curPath.closeSubpath()
break
}
return curPath
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError(
"Can't decode HeartElemNode. " +
"Create it with init(healthRatio: CGFloat, cellFrame: CellFrame, direction: CellDirection)`"
)
}
init(healthRatio: CGFloat, direction: PlayerDirection, cellFrame: CellFrame) {
super.init()
reconfigure(healthRatio: healthRatio, direction: direction, cellFrame: cellFrame)
}
func reconfigure(healthRatio: CGFloat, direction: PlayerDirection, cellFrame: CellFrame) {
path = HeartElemNode.path(cellFrame: cellFrame, direction: direction)
fillColor = HeartElemNode.fillColor(healthRatio: healthRatio, direction: direction)
strokeColor = SKColor.clear
}
}
| mit | 2433ae01b57688e9f12d11635aadc12d | 39.857143 | 104 | 0.619199 | 4.172414 | false | false | false | false |
ulidev/JMButtonLoader | JMButtonLoader/JMButtonLoader/JMButtonLoader.swift | 2 | 4221 | //
// JMButtonLoader.swift
// JMButtonLoader
//
// Created by Joan Molinas on 17/6/15.
// Copyright © 2015 Joan. All rights reserved.
//
import UIKit
protocol ButtonLoaderDelegate {
func buttonTapped()
}
@IBDesignable
class JMButtonLoader: UIButton {
//MARK: Constants
internal let borderLayer = CAShapeLayer()
//MARK: Variables
internal var buttonTitle : String!
var delegate : ButtonLoaderDelegate?
//MARK: Inspectables
@IBInspectable var lineColor : UIColor = UIColor.clearColor() {
didSet {
borderLayer.strokeColor = lineColor.CGColor
setNeedsLayout()
}
}
@IBInspectable var startWithBorder : Bool = false {
didSet {
if(self.startWithBorder) {
borderLayer.opacity = 1
setNeedsLayout()
}
}
}
@IBInspectable var borderWidth : CGFloat = 1 {
didSet {
borderLayer.lineWidth = borderWidth
setNeedsLayout()
}
}
internal var animating = false {
didSet {
updateAnimation()
}
}
@IBInspectable var textLoading : String = "Loading..."{
didSet {
if(animating) {
setTitle(textLoading, forState: UIControlState.Selected)
}
}
}
//MARK: Animations
internal let strokeEndAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.toValue = 1
animation.duration = 0.9
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let group = CAAnimationGroup()
group.duration = 1.2
group.repeatCount = MAXFLOAT
group.animations = [animation]
return group
}()
internal let strokeStartAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "strokeStart")
animation.beginTime = 0.3
animation.fromValue = 0
animation.toValue = 1
animation.duration = 0.9
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let group = CAAnimationGroup()
group.duration = 1.2
group.repeatCount = MAXFLOAT
group.animations = [animation]
return group
}()
//MARK: Inits()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
borderLayer.position = CGPointMake(0, 0)
borderLayer.path = UIBezierPath(rect: bounds).CGPath
}
//External functions
func setup() {
borderLayer.lineWidth = borderWidth
borderLayer.fillColor = nil
borderLayer.strokeColor = lineColor.CGColor
borderLayer.opacity = 0
layer.addSublayer(borderLayer)
buttonTitle = titleLabel?.text
addTarget(self, action: "jmButtonLoader:", forControlEvents: UIControlEvents.TouchUpInside)
}
func updateAnimation() {
if animating {
borderLayer.addAnimation(strokeEndAnimation, forKey: "strokeEnd")
borderLayer.addAnimation(strokeStartAnimation, forKey: "strokeStart")
} else {
borderLayer.removeAnimationForKey("strokeEnd")
borderLayer.removeAnimationForKey("strokeStart")
}
}
internal func jmButtonLoader(sender : UIButton) {
if !animating {
sender.setTitle(textLoading, forState: UIControlState.Normal)
animating = true
enabled = false
delegate?.buttonTapped()
borderLayer.opacity = 1
}
}
func stopButton() {
if animating {
if(!startWithBorder) {borderLayer.opacity = 0}
setTitle(buttonTitle, forState: UIControlState.Normal)
animating = false
enabled = true
}
}
}
| mit | 6e2288aa2d13f8ae7dbed1789569fa7d | 25.878981 | 99 | 0.588152 | 5.52356 | false | false | false | false |
tjw/swift | test/IRGen/abitypes.swift | 2 | 41755 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -emit-ir | %FileCheck -check-prefix=%target-cpu-%target-os %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import gadget
import Foundation
@objc protocol P1 {}
@objc protocol P2 {}
@objc protocol Work {
func doStuff(_ x: Int64)
}
// armv7s-ios: [[ARMV7S_MYRECT:%.*]] = type { float, float, float, float }
// arm64-ios: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// arm64-tvos: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// armv7k-watchos: [[ARMV7K_MYRECT:%.*]] = type { float, float, float, float }
class Foo {
// x86_64-macosx: define hidden swiftcc { i64, i64 } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: define hidden { <2 x float>, <2 x float> } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
// x86_64-ios: define hidden swiftcc { i64, i64 } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-ios: define hidden { <2 x float>, <2 x float> } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
// i386-ios: define hidden swiftcc void @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%TSo6MyRectV* noalias nocapture sret, %T8abitypes3FooC* swiftself) {{.*}} {
// i386-ios: define hidden void @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7-ios: define hidden swiftcc { float, float, float, float } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// armv7-ios: define hidden void @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7s-ios: define hidden swiftcc { float, float, float, float } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// armv7s-ios: define hidden void @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// arm64-ios: define hidden swiftcc { i64, i64 } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// arm64-ios: define hidden [[ARM64_MYRECT]] @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
// x86_64-tvos: define hidden swiftcc { i64, i64 } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-tvos: define hidden { <2 x float>, <2 x float> } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
// arm64-tvos: define hidden swiftcc { i64, i64 } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// arm64-tvos: define hidden [[ARM64_MYRECT]] @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
// i386-watchos: define hidden swiftcc void @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%TSo6MyRectV* noalias nocapture sret, %T8abitypes3FooC* swiftself) {{.*}} {
// i386-watchos: define hidden void @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden swiftcc { float, float, float, float } @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// armv7k-watchos: define hidden [[ARMV7K_MYRECT]] @"$S8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
dynamic func bar() -> MyRect {
return MyRect(x: 1, y: 2, width: 3, height: 4)
}
// x86_64-macosx: define hidden swiftcc double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(double, double, double, double, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: define hidden double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, %TSo6CGRectV* byval align 8) unnamed_addr {{.*}} {
// armv7-ios: define hidden swiftcc double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float, float, float, float, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7-ios: define hidden double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7s-ios: define hidden swiftcc double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float, float, float, float, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7s-ios: define hidden double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden swiftcc double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float, float, float, float, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7k-watchos: define hidden double @"$S8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, [4 x float]) unnamed_addr {{.*}} {
dynamic func getXFromNSRect(_ r: NSRect) -> Double {
return Double(r.origin.x)
}
// x86_64-macosx: define hidden swiftcc float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(i64, i64, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: define hidden float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, <2 x float>, <2 x float>) unnamed_addr {{.*}} {
// armv7-ios: define hidden swiftcc float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float, float, float, float, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7-ios: define hidden float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7s-ios: define hidden swiftcc float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float, float, float, float, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7s-ios: define hidden float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden swiftcc float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float, float, float, float, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7k-watchos: define hidden float @"$S8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, [4 x float]) unnamed_addr {{.*}} {
dynamic func getXFromRect(_ r: MyRect) -> Float {
return r.x
}
// Call from Swift entrypoint with exploded Rect to @objc entrypoint
// with unexploded ABI-coerced type.
// x86_64-macosx: define hidden swiftcc float @"$S8abitypes3FooC17getXFromRectSwift{{.*}}"(i64, i64, [[SELF:%.*]]* swiftself) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 8
// x86_64-macosx: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 8
// x86_64-macosx: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[SELFCAST:%.*]] = bitcast [[SELF]]* %2 to i8*
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, <2 x float>, <2 x float>)*)(i8* [[SELFCAST]], i8* [[SEL]], <2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// armv7-ios: define hidden swiftcc float @"$S8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float, float, float, float, [[SELF:%.*]]* swiftself) {{.*}} {
// armv7-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8*
// armv7-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7s-ios: define hidden swiftcc float @"$S8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float, float, float, float, [[SELF:%.*]]* swiftself) {{.*}} {
// armv7s-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7s-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7s-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7s-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7s-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8*
// armv7s-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7k-watchos: define hidden swiftcc float @"$S8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float, float, float, float, [[SELF:%.*]]* swiftself) {{.*}} {
// armv7k-watchos: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7k-watchos: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7k-watchos: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x float]*
// armv7k-watchos: [[LOADED:%.*]] = load [4 x float], [4 x float]* [[CAST]]
// armv7k-watchos: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8*
// armv7k-watchos: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x float])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x float] [[LOADED]])
func getXFromRectSwift(_ r: MyRect) -> Float {
return getXFromRect(r)
}
// Ensure that MyRect is passed as an indirect-byval on x86_64 because we run out of registers for direct arguments
// x86_64-macosx: define hidden float @"$S8abitypes3FooC25getXFromRectIndirectByVal{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, float, float, float, float, float, float, float, %TSo6MyRectV* byval align 8) unnamed_addr {{.*}} {
dynamic func getXFromRectIndirectByVal(_: Float, second _: Float,
third _: Float, fourth _: Float,
fifth _: Float, sixth _: Float,
seventh _: Float, withRect r: MyRect)
-> Float {
return r.x
}
// Make sure the caller-side from Swift also uses indirect-byval for the argument
// x86_64-macosx: define hidden swiftcc float @"$S8abitypes3FooC25getXFromRectIndirectSwift{{[_0-9a-zA-Z]*}}F"(i64, i64, %T8abitypes3FooC* swiftself) {{.*}} {
func getXFromRectIndirectSwift(_ r: MyRect) -> Float {
let f : Float = 1.0
// x86_64-macosx: [[TEMP:%.*]] = alloca [[TEMPTYPE:%.*]], align 8
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, float, float, float, float, float, float, float, [[TEMPTYPE]]*)*)(i8* %{{.*}}, i8* %{{.*}}, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, [[TEMPTYPE]]* byval align 8 [[TEMP]])
// x86_64-macosx: ret float [[RESULT]]
return getXFromRectIndirectByVal(f, second: f, third: f, fourth: f, fifth: f, sixth: f, seventh: f, withRect: r);
}
// x86_64 returns an HA of four floats directly in two <2 x float>
// x86_64-macosx: define hidden swiftcc float @"$S8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newRect)", align 8
// x86_64-macosx: [[RESULT:%.*]] = call { <2 x float>, <2 x float> } bitcast (void ()* @objc_msgSend
// x86_64-macosx: store { <2 x float>, <2 x float> } [[RESULT]]
// x86_64-macosx: [[CAST:%.*]] = bitcast { <2 x float>, <2 x float> }*
// x86_64-macosx: load { i64, i64 }, { i64, i64 }* [[CAST]]
// x86_64-macosx: ret float
//
// armv7 returns an HA of four floats indirectly
// armv7-ios: define hidden swiftcc float @"$S8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7-ios: ret float [[RETVAL]]
//
// armv7s returns an HA of four floats indirectly
// armv7s-ios: define hidden swiftcc float @"$S8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7s-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7s-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7s-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7s-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7s-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7s-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7s-ios: ret float [[RETVAL]]
//
// armv7k returns an HA of four floats directly
// armv7k-watchos: define hidden swiftcc float @"$S8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7k-watchos: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7k-watchos: [[RESULT:%.*]] = call [[ARMV7K_MYRECT]] bitcast (void ()* @objc_msgSend
// armv7k-watchos: store [[ARMV7K_MYRECT]] [[RESULT]]
// armv7k-watchos: [[CAST:%.*]] = bitcast [[ARMV7K_MYRECT]]*
// armv7k-watchos: load { float, float, float, float }, { float, float, float, float }* [[CAST]]
// armv7k-watchos: ret float
func barc(_ p: StructReturns) -> Float {
return p.newRect().y
}
// x86_64-macosx: define hidden swiftcc { double, double, double } @"$S8abitypes3FooC3baz{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: define hidden void @"$S8abitypes3FooC3baz{{[_0-9a-zA-Z]*}}FTo"(%TSo4TrioV* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
dynamic func baz() -> Trio {
return Trio(i: 1.0, j: 2.0, k: 3.0)
}
// x86_64-macosx: define hidden swiftcc double @"$S8abitypes3FooC4bazc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newTrio)", align 8
// x86_64-macosx: [[CAST:%[0-9]+]] = bitcast {{%.*}}* %0
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend_stret to void (%TSo4TrioV*, [[OPAQUE:.*]]*, i8*)*)
func bazc(_ p: StructReturns) -> Double {
return p.newTrio().j
}
// x86_64-macosx: define hidden swiftcc i64 @"$S8abitypes3FooC7getpair{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: [[RESULT:%.*]] = call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx: [[GEP1:%.*]] = getelementptr inbounds { i64 }, { i64 }* {{.*}}, i32 0, i32 0
// x86_64-macosx: store i64 [[RESULT]], i64* [[GEP1]]
// x86_64-macosx: [[GEP2:%.*]] = getelementptr inbounds { i64 }, { i64 }* {{.*}}, i32 0, i32 0
// x86_64-macosx: load i64, i64* [[GEP2]]
// x86_64-macosx: ret i64
func getpair(_ p: StructReturns) -> IntPair {
return p.newPair()
}
// x86_64-macosx: define hidden i64 @"$S8abitypes3FooC8takepair{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i64) unnamed_addr {{.*}} {
dynamic func takepair(_ p: IntPair) -> IntPair {
return p
}
// x86_64-macosx: define hidden swiftcc i64 @"$S8abitypes3FooC9getnested{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx: bitcast
// x86_64-macosx: call void @llvm.lifetime.start
// x86_64-macosx: store i32 {{.*}}
// x86_64-macosx: store i32 {{.*}}
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { i64 }, { i64 }
// x86_64-macosx: load i64, i64* [[T0]], align 8
// x86_64-macosx: bitcast
// x86_64-macosx: call void @llvm.lifetime.end
// x86_64-macosx: ret i64
func getnested(_ p: StructReturns) -> NestedInts {
return p.newNestedInts()
}
// x86_64-macosx: define hidden i8* @"$S8abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]]* @"$S8abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[T0:%.*]] = call [[OBJC:%objc_class]]* @swift_getObjCClassFromMetadata([[TYPE]]* [[VALUE]])
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[OBJC]]* [[T0]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyClass(_ a: AnyClass) -> AnyClass {
return a
}
// x86_64-macosx: define hidden i8* @"$S8abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]] @"$S8abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyProto(_ a: AnyObject) -> AnyObject {
return a
}
// x86_64-macosx: define hidden i8* @"$S8abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]] @"$S8abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyProtoComp(_ a: P1 & P2) -> P1 & P2 {
return a
}
// x86_64-macosx: define hidden swiftcc i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: define hidden signext i8 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// x86_64-macosx: [[R1:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[R2:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[R3:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[R2]]
// x86_64-macosx: ret i8 [[R3]]
//
// x86_64-ios-fixme: define hidden i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// x86_64-ios-fixme: define internal zeroext i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// x86_64-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$S10ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF"(i1 %2)
// x86_64-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// x86_64-ios-fixme: [[R3:%[0-9]+]] = call i1 @"$S10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]])
// x86_64-ios-fixme: ret i1 [[R3]]
//
// armv7-ios-fixme: define hidden i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// armv7-ios-fixme: define internal signext i8 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// armv7-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$S10ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF"
// armv7-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// armv7-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$S10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]]
// armv7-ios-fixme: ret i8 [[R3]]
//
// armv7s-ios-fixme: define hidden i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// armv7s-ios-fixme: define internal signext i8 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// armv7s-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$S10ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF"
// armv7s-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// armv7s-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$S10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]]
// armv7s-ios-fixme: ret i8 [[R3]]
//
// arm64-ios-fixme: define hidden i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// arm64-ios-fixme: define internal zeroext i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// arm64-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"
// arm64-ios-fixme: ret i1 [[R2]]
//
// i386-ios-fixme: define hidden i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// i386-ios-fixme: define internal signext i8 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// i386-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// i386-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// i386-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[R2]]
// i386-ios-fixme: ret i8 [[R3]]
//
// x86_64-tvos-fixme: define hidden i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// x86_64-tvos-fixme: define internal zeroext i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// x86_64-tvos-fixme: [[R1:%[0-9]+]] = call i1 @"$S10ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF"(i1 %2)
// x86_64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// x86_64-tvos-fixme: [[R3:%[0-9]+]] = call i1 @"$S10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]])
// x86_64-tvos-fixme: ret i1 [[R3]]
//
// arm64-tvos-fixme: define hidden i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// arm64-tvos-fixme: define internal zeroext i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// arm64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"
// arm64-tvos-fixme: ret i1 [[R2]]
// i386-watchos: define hidden swiftcc i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself)
// i386-watchos: define hidden zeroext i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// i386-watchos: [[R1:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBoolySbAA0cD0VF"(i1 %2)
// i386-watchos: [[R2:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// i386-watchos: [[R3:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertBoolToObjCBoolyAA0eF0VSbF"(i1 [[R2]])
// i386-watchos: ret i1 [[R3]]
dynamic func negate(_ b: Bool) -> Bool {
return !b
}
// x86_64-macosx: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-macosx: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// x86_64-macosx: ret i1 [[TOBOOL]]
//
// x86_64-macosx: define hidden signext i8 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext)
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// x86_64-macosx: ret i8 [[TOOBJCBOOL]]
//
// x86_64-ios: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-ios: ret i1 [[NEG]]
//
// x86_64-ios: define hidden zeroext i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i1 zeroext)
// x86_64-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// x86_64-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// x86_64-ios: ret i1 [[TOOBJCBOOL]]
//
// armv7-ios: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// armv7-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// armv7-ios: ret i1 [[TOBOOL]]
//
// armv7-ios: define hidden signext i8 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext)
// armv7-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// armv7-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// armv7-ios: ret i8 [[TOOBJCBOOL]]
//
// armv7s-ios: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// armv7s-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7s-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// armv7s-ios: ret i1 [[TOBOOL]]
//
// armv7s-ios: define hidden signext i8 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext)
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// armv7s-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// armv7s-ios: ret i8 [[TOOBJCBOOL]]
//
// arm64-ios: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// arm64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-ios: ret i1 [[NEG]]
//
// arm64-ios: define hidden zeroext i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i1 zeroext)
// arm64-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// arm64-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// arm64-ios: ret i1 [[TOOBJCBOOL]]
//
// i386-ios: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// i386-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// i386-ios: ret i1 [[TOBOOL]]
//
// i386-ios: define hidden signext i8 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext)
// i386-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// i386-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// i386-ios: ret i8 [[TOOBJCBOOL]]
//
// x86_64-tvos: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-tvos: ret i1 [[NEG]]
//
// x86_64-tvos: define hidden zeroext i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i1 zeroext)
// x86_64-tvos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// x86_64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// x86_64-tvos: ret i1 [[TOOBJCBOOL]]
//
// arm64-tvos: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// arm64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-tvos: ret i1 [[NEG]]
//
// arm64-tvos: define hidden zeroext i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i1 zeroext)
// arm64-tvos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// arm64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// arm64-tvos: ret i1 [[TOOBJCBOOL]]
// i386-watchos: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// i386-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// i386-watchos: ret i1 [[NEG]]
//
// i386-watchos: define hidden zeroext i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i1 zeroext)
// i386-watchos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// i386-watchos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// i386-watchos: ret i1 [[TOOBJCBOOL]]
//
// armv7k-watchos: define hidden swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// armv7k-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7k-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// armv7k-watchos: ret i1 [[NEG]]
//
// armv7k-watchos: define hidden zeroext i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i1 zeroext)
// armv7k-watchos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$S8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// armv7k-watchos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$S10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// armv7k-watchos: ret i1 [[TOOBJCBOOL]]
//
dynamic func negate2(_ b: Bool) -> Bool {
var g = Gadget()
return g.negate(b)
}
// x86_64-macosx: define hidden swiftcc i1 @"$S8abitypes3FooC7negate3yS2bF"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
// x86_64-macosx: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// x86_64-macosx: ret i1 [[NEG]]
// x86_64-macosx: }
// x86_64-ios: define hidden swiftcc i1 @"$S8abitypes3FooC7negate3yS2bF"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
// x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// x86_64-ios: ret i1 [[NEG]]
// x86_64-ios: }
// i386-ios: define hidden swiftcc i1 @"$S8abitypes3FooC7negate3yS2bF"(i1, %T8abitypes3FooC* swiftself) {{.*}} {
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 4
// i386-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// i386-ios: ret i1 [[NEG]]
// i386-ios: }
dynamic func negate3(_ b: Bool) -> Bool {
var g = Gadget()
return g.invert(b)
}
// x86_64-macosx: define hidden swiftcc void @"$S8abitypes3FooC10throwsTestyySbKF"(i1, %T8abitypes3FooC* swiftself, %swift.error** swifterror) {{.*}} {
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
// x86_64-macosx: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
// x86_64-macosx: }
// x86_64-ios: define hidden swiftcc void @"$S8abitypes3FooC10throwsTestyySbKF"(i1, %T8abitypes3FooC* swiftself, %swift.error** swifterror) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
// x86_64-ios: call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext {{%[0-9]+}}, %2** {{%[0-9]+}})
// x86_64-ios: }
// i386-ios: define hidden swiftcc void @"$S8abitypes3FooC10throwsTestyySbKF"(i1, %T8abitypes3FooC* swiftself, %swift.error**) {{.*}} {
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 4
// i386-ios: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
// i386-ios: }
dynamic func throwsTest(_ b: Bool) throws {
var g = Gadget()
try g.negateThrowing(b)
}
// x86_64-macosx: define hidden i32* @"$S8abitypes3FooC24copyUnsafeMutablePointer{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i32*) unnamed_addr {{.*}} {
dynamic func copyUnsafeMutablePointer(_ p: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<Int32> {
return p
}
// x86_64-macosx: define hidden i64 @"$S8abitypes3FooC17returnNSEnumValue{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
dynamic func returnNSEnumValue() -> ByteCountFormatter.CountStyle {
return .file
}
// x86_64-macosx: define hidden zeroext i16 @"$S8abitypes3FooC20returnOtherEnumValue{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i16 zeroext) unnamed_addr {{.*}} {
dynamic func returnOtherEnumValue(_ choice: ChooseTo) -> ChooseTo {
switch choice {
case .takeIt: return .leaveIt
case .leaveIt: return .takeIt
}
}
// x86_64-macosx: define hidden swiftcc i32 @"$S8abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself) {{.*}} {
// x86_64-macosx: define hidden i32 @"$S8abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*) unnamed_addr {{.*}} {
dynamic func getRawEnum() -> RawEnum {
return Intergalactic
}
var work : Work
init (work: Work) {
self.work = work
}
// x86_64-macosx: define hidden void @"$S8abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8*) unnamed_addr {{.*}} {
dynamic func testArchetype(_ work: Work) {
work.doStuff(1)
// x86_64-macosx: [[OBJCPTR:%.*]] = bitcast i8* %2 to %objc_object*
// x86_64-macosx: call swiftcc void @"$S8abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}F"(%objc_object* [[OBJCPTR]], %T8abitypes3FooC* swiftself %{{.*}})
}
dynamic func foo(_ x: @convention(block) (Int) -> Int) -> Int {
// FIXME: calling blocks is currently unimplemented
// return x(5)
return 1
}
// x86_64-macosx: define hidden swiftcc void @"$S8abitypes3FooC20testGenericTypeParam{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T, %T8abitypes3FooC* swiftself) {{.*}} {
func testGenericTypeParam<T: Pasta>(_ x: T) {
// x86_64-macosx: [[CAST:%.*]] = bitcast %objc_object* %0 to i8*
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*)*)(i8* [[CAST]], i8* %{{.*}})
x.alDente()
}
// arm64-ios: define hidden swiftcc { i64, i64, i64, i64 } @"$S8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, i64, i64, i64, i64, %T8abitypes3FooC* swiftself) {{.*}} {
// arm64-ios: define hidden void @"$S8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret, i8*, i8*, [[OPAQUE:.*]]*, %TSo9BigStructV*) unnamed_addr {{.*}} {
//
// arm64-tvos: define hidden swiftcc { i64, i64, i64, i64 } @"$S8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC*, i64, i64, i64, i64, %T8abitypes3FooC* swiftself) {{.*}} {
// arm64-tvos: define hidden void @"$S8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret, i8*, i8*, [[OPAQUE:.*]]*, %TSo9BigStructV*) unnamed_addr {{.*}} {
dynamic func callJustReturn(_ r: StructReturns, with v: BigStruct) -> BigStruct {
return r.justReturn(v)
}
// Test that the makeOne() that we generate somewhere below doesn't
// use arm_aapcscc for armv7.
func callInline() -> Float {
return makeOne(3,5).second
}
}
// armv7-ios: define internal void @makeOne(%struct.One* noalias sret %agg.result, float %f, float %s)
// armv7s-ios: define internal void @makeOne(%struct.One* noalias sret %agg.result, float %f, float %s)
// armv7k-watchos: define internal %struct.One @makeOne(float %f, float %s)
// rdar://17631440 - Expand direct arguments that are coerced to aggregates.
// x86_64-macosx: define{{( protected)?}} swiftcc float @"$S8abitypes13testInlineAggySfSo6MyRectVF"(i64, i64) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca %TSo6MyRectV, align 8
// x86_64-macosx: store i64 %
// x86_64-macosx: store i64 %
// x86_64-macosx: [[CAST:%.*]] = bitcast %TSo6MyRectV* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8
// x86_64-macosx: [[RESULT:%.*]] = call float @MyRect_Area(<2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// x86_64-macosx: ret float [[RESULT]]
public func testInlineAgg(_ rect: MyRect) -> Float {
return MyRect_Area(rect)
}
// We need to allocate enough memory on the stack to hold the argument value we load.
// arm64-ios: define swiftcc void @"$S8abitypes14testBOOLStructyyF"()
// arm64-ios: [[COERCED:%.*]] = alloca i64
// arm64-ios: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %TSo14FiveByteStructV
// arm64-ios: [[PTR0:%.*]] = getelementptr inbounds %TSo14FiveByteStructV, %TSo14FiveByteStructV* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: [[PTR1:%.*]] = getelementptr inbounds %T10ObjectiveC8ObjCBoolV, %T10ObjectiveC8ObjCBoolV* [[PTR0]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: [[PTR2:%.*]] = getelementptr inbounds %TSb, %TSb* [[PTR1]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: store i1 false, i1* [[PTR2]], align 8
// arm64-ios: [[ARG:%.*]] = load i64, i64* [[COERCED]]
// arm64-ios: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]])
public func testBOOLStruct() {
let s = FiveByteStruct()
MyClass.mymethod(s)
}
| apache-2.0 | 66d51faebc7ff477cd10942594d31c82 | 73.5625 | 371 | 0.604598 | 2.75738 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/Views/DisappearingTimerConfigurationView.swift | 1 | 4412 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
public protocol DisappearingTimerConfigurationViewDelegate: class {
func disappearingTimerConfigurationViewWasTapped(_ disappearingTimerView: DisappearingTimerConfigurationView)
}
// DisappearingTimerConfigurationView shows a timer icon and a short label showing the duration
// of disappearing messages for a thread.
//
// If you assign a delegate, it behaves like a button.
@objc
public class DisappearingTimerConfigurationView: UIView {
@objc
public weak var delegate: DisappearingTimerConfigurationViewDelegate? {
didSet {
// gesture recognizer is only enabled when a delegate is assigned.
// This lets us use this view as either an interactive button
// or as a non-interactive status indicator
pressGesture.isEnabled = delegate != nil
}
}
private let imageView: UIImageView
private let label: UILabel
private var pressGesture: UILongPressGestureRecognizer!
public required init?(coder aDecoder: NSCoder) {
notImplemented()
}
@objc
public init(durationSeconds: UInt32) {
self.imageView = UIImageView(image: #imageLiteral(resourceName: "ic_timer"))
imageView.contentMode = .scaleAspectFit
self.label = UILabel()
label.text = NSString.formatDurationSeconds(durationSeconds, useShortFormat: true)
label.font = UIFont.systemFont(ofSize: 10)
label.textAlignment = .center
label.minimumScaleFactor = 0.5
super.init(frame: CGRect.zero)
applyTintColor(self.tintColor)
// Gesture, simulating button touch up inside
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(pressHandler))
gesture.minimumPressDuration = 0
self.pressGesture = gesture
self.addGestureRecognizer(pressGesture)
// disable gesture recognizer until a delegate is assigned
// this lets us use the UI as either an interactive button
// or as a non-interactive status indicator
pressGesture.isEnabled = false
// Accessibility
self.accessibilityLabel = NSLocalizedString("DISAPPEARING_MESSAGES_LABEL", comment: "Accessibility label for disappearing messages")
let hintFormatString = NSLocalizedString("DISAPPEARING_MESSAGES_HINT", comment: "Accessibility hint that contains current timeout information")
let durationString = NSString.formatDurationSeconds(durationSeconds, useShortFormat: false)
self.accessibilityHint = String(format: hintFormatString, durationString)
// Layout
self.addSubview(imageView)
self.addSubview(label)
let kHorizontalPadding: CGFloat = 4
let kVerticalPadding: CGFloat = 6
imageView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: kVerticalPadding, left: kHorizontalPadding, bottom: 0, right: kHorizontalPadding), excludingEdge: .bottom)
label.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: kHorizontalPadding, bottom: kVerticalPadding, right: kHorizontalPadding), excludingEdge: .top)
label.autoPinEdge(.top, to: .bottom, of: imageView)
}
@objc
func pressHandler(_ gestureRecognizer: UILongPressGestureRecognizer) {
Logger.verbose("")
// handle touch down and touch up events separately
if gestureRecognizer.state == .began {
applyTintColor(UIColor.gray)
} else if gestureRecognizer.state == .ended {
applyTintColor(self.tintColor)
let location = gestureRecognizer.location(in: self)
let isTouchUpInside = self.bounds.contains(location)
if (isTouchUpInside) {
// Similar to a UIButton's touch-up-inside
self.delegate?.disappearingTimerConfigurationViewWasTapped(self)
} else {
// Similar to a UIButton's touch-up-outside
// cancel gesture
gestureRecognizer.isEnabled = false
gestureRecognizer.isEnabled = true
}
}
}
override public var tintColor: UIColor! {
didSet {
applyTintColor(tintColor)
}
}
private func applyTintColor(_ color: UIColor) {
imageView.tintColor = color
label.textColor = color
}
}
| gpl-3.0 | 7e0cd3161448eaf2b39094d04312545a | 37.034483 | 177 | 0.68495 | 5.302885 | false | true | false | false |
djwbrown/swift | stdlib/public/SDK/Dispatch/Time.swift | 6 | 6574 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import _SwiftDispatchOverlayShims
public struct DispatchTime : Comparable {
private static let timebaseInfo: mach_timebase_info_data_t = {
var info = mach_timebase_info_data_t(numer: 1, denom: 1)
mach_timebase_info(&info)
return info
}()
public let rawValue: dispatch_time_t
public static func now() -> DispatchTime {
let t = __dispatch_time(0, 0)
return DispatchTime(rawValue: t)
}
public static let distantFuture = DispatchTime(rawValue: ~0)
fileprivate init(rawValue: dispatch_time_t) {
self.rawValue = rawValue
}
/// Creates a `DispatchTime` relative to the system clock that
/// ticks since boot.
///
/// - Parameters:
/// - uptimeNanoseconds: The number of nanoseconds since boot, excluding
/// time the system spent asleep
/// - Returns: A new `DispatchTime`
/// - Discussion: This clock is the same as the value returned by
/// `mach_absolute_time` when converted into nanoseconds.
/// On some platforms, the nanosecond value is rounded up to a
/// multiple of the Mach timebase, using the conversion factors
/// returned by `mach_timebase_info()`. The nanosecond equivalent
/// of the rounded result can be obtained by reading the
/// `uptimeNanoseconds` property.
/// Note that `DispatchTime(uptimeNanoseconds: 0)` is
/// equivalent to `DispatchTime.now()`, that is, its value
/// represents the number of nanoseconds since boot (excluding
/// system sleep time), not zero nanoseconds since boot.
public init(uptimeNanoseconds: UInt64) {
var rawValue = uptimeNanoseconds
if (DispatchTime.timebaseInfo.numer != DispatchTime.timebaseInfo.denom) {
rawValue = (rawValue * UInt64(DispatchTime.timebaseInfo.denom)
+ UInt64(DispatchTime.timebaseInfo.numer - 1)) / UInt64(DispatchTime.timebaseInfo.numer)
}
self.rawValue = dispatch_time_t(rawValue)
}
public var uptimeNanoseconds: UInt64 {
var result = self.rawValue
if (DispatchTime.timebaseInfo.numer != DispatchTime.timebaseInfo.denom) {
result = result * UInt64(DispatchTime.timebaseInfo.numer) / UInt64(DispatchTime.timebaseInfo.denom)
}
return result
}
}
extension DispatchTime {
public static func < (a: DispatchTime, b: DispatchTime) -> Bool {
return a.rawValue < b.rawValue
}
public static func ==(a: DispatchTime, b: DispatchTime) -> Bool {
return a.rawValue == b.rawValue
}
}
public struct DispatchWallTime : Comparable {
public let rawValue: dispatch_time_t
public static func now() -> DispatchWallTime {
return DispatchWallTime(rawValue: __dispatch_walltime(nil, 0))
}
public static let distantFuture = DispatchWallTime(rawValue: ~0)
fileprivate init(rawValue: dispatch_time_t) {
self.rawValue = rawValue
}
public init(timespec: timespec) {
var t = timespec
self.rawValue = __dispatch_walltime(&t, 0)
}
}
extension DispatchWallTime {
public static func <(a: DispatchWallTime, b: DispatchWallTime) -> Bool {
let negativeOne: dispatch_time_t = ~0
if b.rawValue == negativeOne {
return a.rawValue != negativeOne
} else if a.rawValue == negativeOne {
return false
}
return -Int64(bitPattern: a.rawValue) < -Int64(bitPattern: b.rawValue)
}
public static func ==(a: DispatchWallTime, b: DispatchWallTime) -> Bool {
return a.rawValue == b.rawValue
}
}
public enum DispatchTimeInterval : Equatable {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
@_downgrade_exhaustivity_check
case never
internal var rawValue: Int64 {
switch self {
case .seconds(let s): return Int64(s) * Int64(NSEC_PER_SEC)
case .milliseconds(let ms): return Int64(ms) * Int64(NSEC_PER_MSEC)
case .microseconds(let us): return Int64(us) * Int64(NSEC_PER_USEC)
case .nanoseconds(let ns): return Int64(ns)
case .never: return Int64.max
}
}
public static func ==(lhs: DispatchTimeInterval, rhs: DispatchTimeInterval) -> Bool {
switch (lhs, rhs) {
case (.never, .never): return true
case (.never, _): return false
case (_, .never): return false
default: return lhs.rawValue == rhs.rawValue
}
}
}
public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime {
let t = __dispatch_time(time.rawValue, interval.rawValue)
return DispatchTime(rawValue: t)
}
public func -(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime {
let t = __dispatch_time(time.rawValue, -interval.rawValue)
return DispatchTime(rawValue: t)
}
public func +(time: DispatchTime, seconds: Double) -> DispatchTime {
let interval = seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.max : Int64(interval))
return DispatchTime(rawValue: t)
}
public func -(time: DispatchTime, seconds: Double) -> DispatchTime {
let interval = -seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.min : Int64(interval))
return DispatchTime(rawValue: t)
}
public func +(time: DispatchWallTime, interval: DispatchTimeInterval) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, interval.rawValue)
return DispatchWallTime(rawValue: t)
}
public func -(time: DispatchWallTime, interval: DispatchTimeInterval) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, -interval.rawValue)
return DispatchWallTime(rawValue: t)
}
public func +(time: DispatchWallTime, seconds: Double) -> DispatchWallTime {
let interval = seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.max : Int64(interval))
return DispatchWallTime(rawValue: t)
}
public func -(time: DispatchWallTime, seconds: Double) -> DispatchWallTime {
let interval = -seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.min : Int64(interval))
return DispatchWallTime(rawValue: t)
}
| apache-2.0 | a67f305462d27491a433a671b01d98c9 | 33.418848 | 102 | 0.68923 | 3.873895 | false | false | false | false |
alexhillc/AXPhotoViewer | Source/Classes/Views/AXZoomingImageView.swift | 1 | 7190 | //
// ZoomingImageView.swift
// AXPhotoViewer
//
// Created by Alex Hill on 5/21/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
import UIKit
#if os(iOS)
import FLAnimatedImage
#elseif os(tvOS)
import FLAnimatedImage_tvOS
#endif
fileprivate let ZoomScaleEpsilon: CGFloat = 0.01
class AXZoomingImageView: UIScrollView, UIScrollViewDelegate {
#if os(iOS)
/// iOS-only tap gesture recognizer for zooming.
fileprivate(set) var doubleTapGestureRecognizer = UITapGestureRecognizer()
#endif
weak var zoomScaleDelegate: AXZoomingImageViewDelegate?
var image: UIImage? {
set(value) {
self.updateImageView(image: value, animatedImage: nil)
}
get {
return self.imageView.image
}
}
var animatedImage: FLAnimatedImage? {
set(value) {
self.updateImageView(image: nil, animatedImage: value)
}
get {
return self.imageView.animatedImage
}
}
override var frame: CGRect {
didSet {
self.updateZoomScale()
}
}
fileprivate(set) var imageView = FLAnimatedImageView()
fileprivate var needsUpdateImageView = false
init() {
super.init(frame: .zero)
#if os(iOS)
self.doubleTapGestureRecognizer.numberOfTapsRequired = 2
self.doubleTapGestureRecognizer.addTarget(self, action: #selector(doubleTapAction(_:)))
self.doubleTapGestureRecognizer.isEnabled = false
self.addGestureRecognizer(self.doubleTapGestureRecognizer)
#endif
self.imageView.layer.masksToBounds = true
self.imageView.contentMode = .scaleAspectFit
self.addSubview(self.imageView)
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
self.isScrollEnabled = false
self.bouncesZoom = true
self.decelerationRate = .fast
self.delegate = self
if #available(iOS 11.0, tvOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func updateImageView(image: UIImage?, animatedImage: FLAnimatedImage?) {
self.imageView.transform = .identity
var imageSize: CGSize = .zero
if let animatedImage = animatedImage {
if self.imageView.animatedImage != animatedImage {
self.imageView.animatedImage = animatedImage
}
imageSize = animatedImage.size
} else if let image = image {
if self.imageView.image != image {
self.imageView.image = image
}
imageSize = image.size
} else {
self.imageView.animatedImage = nil
self.imageView.image = nil
}
self.imageView.frame = CGRect(origin: .zero, size: imageSize)
self.contentSize = imageSize
self.updateZoomScale()
#if os(iOS)
self.doubleTapGestureRecognizer.isEnabled = (image != nil || animatedImage != nil)
#endif
self.needsUpdateImageView = false
}
override func willRemoveSubview(_ subview: UIView) {
super.willRemoveSubview(subview)
if subview === self.imageView {
self.needsUpdateImageView = true
}
}
override func didAddSubview(_ subview: UIView) {
super.didAddSubview(subview)
if subview === self.imageView && self.needsUpdateImageView {
self.updateImageView(image: self.imageView.image, animatedImage: self.imageView.animatedImage)
}
}
// MARK: - UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollView.isScrollEnabled = true
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width) ?
(scrollView.bounds.size.width - scrollView.contentSize.width) / 2 : 0
let offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height) ?
(scrollView.bounds.size.height - scrollView.contentSize.height) / 2 : 0
self.imageView.center = CGPoint(x: offsetX + (scrollView.contentSize.width / 2), y: offsetY + (scrollView.contentSize.height / 2))
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
guard abs(scale - self.minimumZoomScale) <= ZoomScaleEpsilon else {
return
}
scrollView.isScrollEnabled = false
}
// MARK: - Zoom scale
fileprivate func updateZoomScale() {
let imageSize = self.imageView.image?.size ?? self.imageView.animatedImage?.size ?? CGSize(width: 1, height: 1)
let scaleWidth = self.bounds.size.width / imageSize.width
let scaleHeight = self.bounds.size.height / imageSize.height
self.minimumZoomScale = min(scaleWidth, scaleHeight)
let delegatedMaxZoomScale = self.zoomScaleDelegate?.zoomingImageView(self, maximumZoomScaleFor: imageSize)
if let maximumZoomScale = delegatedMaxZoomScale, (maximumZoomScale - self.minimumZoomScale) >= 0 {
self.maximumZoomScale = maximumZoomScale
} else {
self.maximumZoomScale = self.minimumZoomScale * 3.5
}
// if the zoom scale is the same, change it to force the UIScrollView to
// recompute the scroll view's content frame
if abs(self.zoomScale - self.minimumZoomScale) <= .ulpOfOne {
self.zoomScale = self.minimumZoomScale + 0.1
}
self.zoomScale = self.minimumZoomScale
self.isScrollEnabled = false
}
#if os(iOS)
// MARK: - UITapGestureRecognizer
@objc fileprivate func doubleTapAction(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: self.imageView)
var zoomScale = self.maximumZoomScale
if self.zoomScale >= self.maximumZoomScale || abs(self.zoomScale - self.maximumZoomScale) <= ZoomScaleEpsilon {
zoomScale = self.minimumZoomScale
}
if abs(self.zoomScale - zoomScale) <= .ulpOfOne {
return
}
let width = self.bounds.size.width / zoomScale
let height = self.bounds.size.height / zoomScale
let originX = point.x - (width / 2)
let originY = point.y - (height / 2)
let zoomRect = CGRect(x: originX, y: originY, width: width, height: height)
self.zoom(to: zoomRect, animated: true)
}
#endif
}
protocol AXZoomingImageViewDelegate: class {
func zoomingImageView(_ zoomingImageView: AXZoomingImageView, maximumZoomScaleFor imageSize: CGSize) -> CGFloat
}
| mit | d2f8ea1e62b2e09816fe204a10ab5f56 | 33.07109 | 138 | 0.628738 | 5.094968 | false | false | false | false |
yangboz/SwiftTutorials | CookieCrunch/CookieCrunch/Swap.swift | 1 | 656 | //
// Swap.swift
// CookieCrunch
//
// Created by Matthijs on 19-06-14.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
class Swap: Printable, Hashable {
var cookieA: Cookie
var cookieB: Cookie
init(cookieA: Cookie, cookieB: Cookie) {
self.cookieA = cookieA
self.cookieB = cookieB
}
var description: String {
return "swap \(cookieA) with \(cookieB)"
}
var hashValue: Int {
return cookieA.hashValue ^ cookieB.hashValue
}
}
func ==(lhs: Swap, rhs: Swap) -> Bool {
return (lhs.cookieA == rhs.cookieA && lhs.cookieB == rhs.cookieB) ||
(lhs.cookieB == rhs.cookieA && lhs.cookieA == rhs.cookieB)
}
| mit | da80ba7259a4e4b4dd997b09c5f120d2 | 20.866667 | 70 | 0.641768 | 3.489362 | false | false | false | false |
fabiomassimo/eidolon | Kiosk/Admin/ChooseAuctionViewController.swift | 1 | 1820 | import UIKit
import ORStackView
import Artsy_UIFonts
import Artsy_UIButtons
class ChooseAuctionViewController: UIViewController {
var auctions: [Sale]!
override func viewDidLoad() {
super.viewDidLoad()
stackScrollView.backgroundColor = UIColor.whiteColor()
stackScrollView.bottomMarginHeight = CGFloat(NSNotFound)
stackScrollView.updateConstraints()
let endpoint: ArtsyAPI = ArtsyAPI.ActiveAuctions
XAppRequest(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(Sale.self)
.subscribeNext({ [weak self] (activeSales) -> Void in
self!.auctions = activeSales as! [Sale]
for i in 0 ..< count(self!.auctions) {
let sale = self!.auctions[i]
let title = " \(sale.name) - #\(sale.auctionState) - \(sale.artworkCount)"
let button = ARFlatButton()
button.setTitle(title, forState: .Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.tag = i
button.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) in
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(sale.id, forKey: "KioskAuctionID")
defaults.synchronize()
exit(1)
}
self!.stackScrollView.addSubview(button, withTopMargin: "12", sideMargin: "0")
button.constrainHeight("50")
}
})
}
@IBOutlet weak var stackScrollView: ORStackView!
@IBAction func backButtonTapped(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
}
| mit | b6a2c57c62e9519b59ddcdf906a014a1 | 36.916667 | 98 | 0.593407 | 5.531915 | false | false | false | false |
keyeMyria/edx-app-ios | Source/SpinnerView.swift | 2 | 3133 | //
// SpinnerView.swift
// edX
//
// Created by Akiva Leffert on 6/3/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
private var startTime : NSTimeInterval?
private let animationKey = "org.edx.spin"
public class SpinnerView : UIView {
public enum Size {
case Small
case Large
}
public enum Color {
case Primary
case White
private var value : UIColor {
switch self {
case Primary: return OEXStyles.sharedStyles().primaryBaseColor()
case White: return OEXStyles.sharedStyles().neutralWhite()
}
}
}
private let content = UIImageView()
private let size : Size
private var stopped : Bool = false
public init(size : Size, color : Color) {
self.size = size
super.init(frame : CGRectZero)
addSubview(content)
content.image = Icon.Spinner.imageWithFontSize(30)
content.tintColor = color.value
content.contentMode = .ScaleAspectFit
}
public override class func requiresConstraintBasedLayout() -> Bool {
return true
}
override public func layoutSubviews() {
super.layoutSubviews()
content.frame = self.bounds
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func didMoveToWindow() {
if !stopped {
addSpinAnimation()
}
else {
removeSpinAnimation()
}
}
public override func intrinsicContentSize() -> CGSize {
switch size {
case .Small:
return CGSizeMake(12, 12)
case .Large:
return CGSizeMake(24, 24)
}
}
private func addSpinAnimation() {
if let window = self.window {
let animation = CAKeyframeAnimation(keyPath: "transform.rotation")
let dots = 8
let direction : Double = UIApplication.sharedApplication().userInterfaceLayoutDirection == .LeftToRight ? 1 : -1
animation.keyTimes = Array(count: dots) {
return (Double($0) / Double(dots)) as NSNumber
}
animation.values = Array(count: dots) {
return (direction * Double($0) / Double(dots)) * 2.0 * M_PI as NSNumber
}
animation.repeatCount = Float.infinity
animation.duration = 0.6
animation.additive = true
animation.calculationMode = kCAAnimationDiscrete
/// Set time to zero so they all sync up
animation.beginTime = window.layer.convertTime(0, toLayer: self.layer)
self.content.layer.addAnimation(animation, forKey: animationKey)
}
}
private func removeSpinAnimation() {
self.content.layer.removeAnimationForKey(animationKey)
}
public func startAnimating() {
stopped = false
addSpinAnimation()
}
public func stopAnimating() {
removeSpinAnimation()
stopped = true
}
}
| apache-2.0 | 05082b60d1d31bdb226b2cf1ec6e8433 | 26.973214 | 124 | 0.585381 | 5.086039 | false | false | false | false |
tombuildsstuff/swiftcity | SwiftCity/Entities/Parameters.swift | 1 | 941 | public struct Parameters {
public let count : Int
public let href : String?
public let properties : [Parameter]
init?(dictionary: [String: AnyObject]) {
guard let count = dictionary["count"] as? Int,
let propertiesDictionary = dictionary["property"] as? [[String: AnyObject]] else {
return nil
}
let properties = propertiesDictionary.map { (dictionary: [String : AnyObject]) -> Parameter? in
return Parameter(dictionary: dictionary)
}.filter({ (param: Parameter?) -> Bool in
return param != nil
}).map { (param: Parameter?) -> Parameter in
return param!
}
guard propertiesDictionary.count == properties.count else {
return nil
}
let href = dictionary["href"] as? String
self.count = count
self.href = href
self.properties = properties
}
}
| mit | 74e2cb6a6d8f58348b94aedbfeee004c | 27.515152 | 103 | 0.575983 | 5.005319 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/UIViewController+Push.swift | 1 | 832 | import Foundation
extension UIViewController {
@objc(wmf_pushViewController:animated:)
func push(_ viewController: UIViewController, animated: Bool = true) {
if let navigationController = navigationController {
navigationController.pushViewController(viewController, animated: true)
} else if let presentingViewController = presentingViewController {
presentingViewController.dismiss(animated: true) {
presentingViewController.push(viewController, animated: animated)
}
} else if let parent = parent {
parent.push(viewController, animated: animated)
} else if let navigationController = self as? UINavigationController {
navigationController.pushViewController(viewController, animated: animated)
}
}
}
| mit | 338f66ddaa76386190a1f831dfca7665 | 45.222222 | 87 | 0.698317 | 6.30303 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Views/Shepard Tab/ShepardFlowController.swift | 1 | 1026 | //
// ShepardFlowController.swift
// MEGameTracker
//
// Created by Emily Ivie on 8/9/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import UIKit
class ShepardFlowController: IBIncludedThing {
var appearanceController: ShepardAppearanceController? {
for child in children where !UIWindow.isInterfaceBuilder {
if let appearanceController = child as? ShepardAppearanceController {
return appearanceController
}
}
return nil
}
@IBAction func closeModal(_ sender: AnyObject!) {
dismiss(animated: true, completion: nil)
}
@IBAction func saveCode(_ sender: AnyObject!) {
appearanceController?.save()
if let splitViewController = includedController as? ShepardSplitViewController,
splitViewController.detailPlaceholder?.isHidden == false {
splitViewController.closeDetailStoryboard(sender)
} else {
_ = navigationController?.popViewController(animated: true)
}
}
@IBAction func createGame(_ sender: AnyObject!) {
App.current.addNewGame()
closeModal(sender)
}
}
| mit | 8ff8a6d1d8fd78bdf03344cbff59d300 | 24 | 81 | 0.747317 | 4.083665 | false | false | false | false |
DungntVccorp/Game | game-server/Sources/game-server/ConcurrentOperation.swift | 1 | 2659 | //
// BaseOperation.swift
// P
//
// Created by Nguyen Dung on 4/27/17.
//
//
import Foundation
import LoggerAPI
protocol ConcurrentOperationDelegate {
func finishOperation(_ type : Int,_ replyMsg : GSProtocolMessage?,_ client : TcpClient)
}
open class ConcurrentOperation : Operation{
enum State {
case ready
case executing
case finished
func asKeyPath() -> String {
switch self {
case .ready:
return "isReady"
case .executing:
return "isExecuting"
case .finished:
return "isFinished"
}
}
}
var state: State {
willSet {
// willChangeValue(forKey: newValue.asKeyPath())
// willChangeValue(forKey: state.asKeyPath())
}
didSet {
// didChangeValue(forKey: oldValue.asKeyPath())
// didChangeValue(forKey: state.asKeyPath())
}
}
private var delegate : ConcurrentOperationDelegate!
var clientExcute : TcpClient!
var excuteMessage : GSProtocolMessage!
override init() {
state = .ready
super.init()
}
convenience init(_ delegate : ConcurrentOperationDelegate?,_ client : TcpClient,_ msg : GSProtocolMessage) {
self.init()
if(delegate != nil){
self.delegate = delegate!
}
self.clientExcute = client
self.excuteMessage = msg
}
// MARK: - NSOperation
override open var isReady: Bool {
return state == .ready
}
override open var isExecuting: Bool {
return state == .executing
}
override open var isFinished: Bool {
return state == .finished
}
override open var isAsynchronous: Bool {
return true
}
override open func start() {
if self.isCancelled {
state = .finished
}else{
state = .ready
main()
}
}
open func TcpExcute() -> (Int,replyMsg : GSProtocolMessage?){
return (0,nil)
}
override open func main() {
if self.isCancelled {
state = .finished
}else{
state = .executing
Log.info("Run OP \(excuteMessage.headCodeId) : \(excuteMessage.subCodeId)")
let ex = self.TcpExcute()
if(self.delegate != nil){
self.delegate.finishOperation(ex.0,ex.1,self.clientExcute)
}
state = .finished
}
}
deinit {
Log.info("Finish Operation")
}
}
| mit | 0ca51e6ebb668121ceddd8e4c3ee134e | 22.121739 | 112 | 0.529898 | 4.773788 | false | false | false | false |
benkraus/Operations | Operations/URLSessionTaskOperation.swift | 1 | 3218 | /*
The MIT License (MIT)
Original work Copyright (c) 2015 pluralsight
Modified work Copyright 2016 Ben Kraus
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
private var URLSessionTaskOperationKVOContext = 0
/**
`URLSessionTaskOperation` is an `Operation` that lifts an `NSURLSessionTask`
into an operation.
Note that this operation does not participate in any of the delegate callbacks \
of an `NSURLSession`, but instead uses Key-Value-Observing to know when the
task has been completed. It also does not get notified about any errors that
occurred during execution of the task.
An example usage of `URLSessionTaskOperation` can be seen in the `DownloadEarthquakesOperation`.
*/
public class URLSessionTaskOperation: Operation {
let task: NSURLSessionTask
private var observerRemoved = false
private let stateLock = NSLock()
public init(task: NSURLSessionTask) {
assert(task.state == .Suspended, "Tasks must be suspended.")
self.task = task
super.init()
addObserver(BlockObserver(cancelHandler: { _ in
task.cancel()
}))
}
override public func execute() {
assert(task.state == .Suspended, "Task was resumed by something other than \(self).")
task.addObserver(self, forKeyPath: "state", options: NSKeyValueObservingOptions(), context: &URLSessionTaskOperationKVOContext)
task.resume()
}
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &URLSessionTaskOperationKVOContext else { return }
stateLock.withCriticalScope {
if object === task && keyPath == "state" && !observerRemoved {
switch task.state {
case .Completed:
finish()
fallthrough
case .Canceling:
observerRemoved = true
task.removeObserver(self, forKeyPath: "state")
default:
return
}
}
}
}
}
| mit | 54a12ba2fbd2a435ff886f908f6f19d0 | 37.771084 | 164 | 0.682101 | 5.310231 | false | false | false | false |
smoope/ios-sdk | Pod/Classes/SPCreated.swift | 1 | 1156 | /*
* Copyright 2016 smoope GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public class SPCreated: SPIdentified {
public private(set) var created: NSDate?
public required init(data: [String: AnyObject] = [:]) {
if let created = data["created"] {
self.created = NSDate.fromISO8601String(created as! String)
}
super.init(data: data)
}
public override func unmap() -> [String: AnyObject] {
var result: Dictionary<String, AnyObject> = [:]
if let created = self.created {
result["created"] = created.toISO8601String()
}
return result
.append(super.unmap())
}
} | apache-2.0 | 53ddd659696d99b3c1f47653832fbf66 | 27.925 | 74 | 0.694637 | 4.05614 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/Calling/CallParticipantsListViewControllerTests.swift | 1 | 3966 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import SnapshotTesting
import XCTest
@testable import Wire
final class CallParticipantsListHelper {
static func participants(count participantCount: Int,
videoState: VideoState? = nil,
microphoneState: MicrophoneState? = nil,
mockUsers: [UserType]) -> CallParticipantsList {
let sortedParticipants = (0..<participantCount)
.lazy
.map { mockUsers[$0] }
.sorted { $0.name < $1.name }
return sortedParticipants.map { CallParticipantsListCellConfiguration.callParticipant(user: HashBox(value: $0),
videoState: videoState,
microphoneState: microphoneState,
activeSpeakerState: .inactive)
}
}
}
final class CallParticipantsListViewControllerTests: ZMSnapshotTestCase {
var sut: CallParticipantsListViewController!
var mockParticipants: CallParticipantsList!
override func setUp() {
super.setUp()
mockParticipants = CallParticipantsListHelper.participants(count: 10, mockUsers: SwiftMockLoader.mockUsers())
}
override func tearDown() {
sut = nil
mockParticipants = nil
super.tearDown()
}
func testCallParticipants_Overflowing_Light() {
// When
sut = CallParticipantsListViewController(participants: mockParticipants, showParticipants: true, selfUser: ZMUser.selfUser())
sut.view.frame = CGRect(x: 0, y: 0, width: 325, height: 336)
sut.view.setNeedsLayout()
sut.view.layoutIfNeeded()
sut.view.backgroundColor = .white
// Then
verify(matching: sut.view)
}
func testCallParticipants_Overflowing_Dark() {
// When
sut = CallParticipantsListViewController(participants: mockParticipants, showParticipants: true, selfUser: ZMUser.selfUser())
sut.variant = .dark
sut.overrideUserInterfaceStyle = .dark
sut.view.frame = CGRect(x: 0, y: 0, width: 325, height: 336)
sut.view.setNeedsLayout()
sut.view.layoutIfNeeded()
sut.view.backgroundColor = .black
sut.overrideUserInterfaceStyle = .dark
// Then
verify(matching: sut.view)
}
func testCallParticipants_Truncated_Light() {
// When
sut = CallParticipantsListViewController(participants: mockParticipants, showParticipants: false, selfUser: ZMUser.selfUser())
sut.view.frame = CGRect(x: 0, y: 0, width: 325, height: 336)
sut.view.backgroundColor = .white
// Then
verify(matching: sut.view)
}
func testCallParticipants_Truncated_Dark() {
// When
sut = CallParticipantsListViewController(participants: mockParticipants, showParticipants: false, selfUser: ZMUser.selfUser())
sut.variant = .dark
sut.view.frame = CGRect(x: 0, y: 0, width: 325, height: 336)
sut.view.backgroundColor = .black
// Then
verify(matching: sut.view)
}
}
| gpl-3.0 | 29b721cec5aee294ef0708ec380206e4 | 36.065421 | 134 | 0.622542 | 4.976161 | false | true | false | false |
LiuSky/XBKit | Sources/UserDefaults/UserDefaults.swift | 1 | 3328 | //
// KeyNamespaceable.swift
// HLDD
//
// Created by xiaobin liu on 2016/12/20.
// Copyright © 2016年 Sky. All rights reserved.
//
import Foundation
public protocol KeyNamespaceable {
func namespaced<T: RawRepresentable>(_ key: T) -> String
}
public extension KeyNamespaceable {
func namespaced<T: RawRepresentable>(_ key: T) -> String {
return "\(Self.self).\(key.rawValue)"
}
}
public protocol BoolDefaultSettable : KeyNamespaceable {
associatedtype BoolKey : RawRepresentable
}
public extension BoolDefaultSettable where BoolKey.RawValue == String {
func set(_ value: Bool, forKey key: BoolKey) {
let key = namespaced(key)
UserDefaults.standard.set(value, forKey: key)
}
func bool(forKey key: BoolKey) -> Bool {
let key = namespaced(key)
return UserDefaults.standard.bool(forKey: key)
}
}
public protocol IntegerDefaultSettable: KeyNamespaceable {
associatedtype IntegerKey : RawRepresentable
}
public extension IntegerDefaultSettable where IntegerKey.RawValue == String {
func set(_ value: Int, forKey key: IntegerKey) {
let key = namespaced(key)
UserDefaults.standard.set(value, forKey: key)
}
func int(forKey key: IntegerKey) -> Int {
let key = namespaced(key)
return UserDefaults.standard.integer(forKey: key)
}
}
public protocol DoubleDefaultSettable: KeyNamespaceable {
associatedtype DoubleKey : RawRepresentable
}
public extension DoubleDefaultSettable where DoubleKey.RawValue == String {
func set(_ value: Double, forKey key: DoubleKey) {
let key = namespaced(key)
UserDefaults.standard.set(value, forKey: key)
}
func double(forKey key: DoubleKey) -> Double {
let key = namespaced(key)
return UserDefaults.standard.double(forKey: key)
}
}
public protocol FloatDefaultSettable: KeyNamespaceable {
associatedtype FloatKey : RawRepresentable
}
public extension FloatDefaultSettable where FloatKey.RawValue == String {
func set(_ value: Float, forKey key: FloatKey) {
let key = namespaced(key)
UserDefaults.standard.set(value, forKey: key)
}
func float(forKey key: FloatKey) -> Float {
let key = namespaced(key)
return UserDefaults.standard.float(forKey: key)
}
}
public protocol ObjectDefaultSettable: KeyNamespaceable {
associatedtype ObjectKey : RawRepresentable
}
public extension ObjectDefaultSettable where ObjectKey.RawValue == String {
func set(_ value: Any, forKey key: ObjectKey) {
let key = namespaced(key)
UserDefaults.standard.set(value, forKey: key)
}
func object(forKey key: ObjectKey) -> Any? {
let key = namespaced(key)
return UserDefaults.standard.object(forKey: key)
}
}
public protocol URLDefaultSettable: KeyNamespaceable {
associatedtype URLKey : RawRepresentable
}
public extension URLDefaultSettable where URLKey.RawValue == String {
func set(_ value: URL, forKey key: URLKey) {
let key = namespaced(key)
UserDefaults.standard.set(value, forKey: key)
}
func url(forKey key: URLKey) -> URL? {
let key = namespaced(key)
return UserDefaults.standard.url(forKey: key)
}
}
| mit | ceb5bd53b6fb7da872ea61bd58ab1596 | 24.576923 | 77 | 0.674887 | 4.284794 | false | false | false | false |
eisber/tasty-imitation-keyboard | Keyboard/DefaultKeyboard.swift | 6 | 4358 | //
// DefaultKeyboard.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
func defaultKeyboard() -> Keyboard {
var defaultKeyboard = Keyboard()
for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] {
var keyModel = Key(.Character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 0)
}
for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] {
var keyModel = Key(.Character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 0)
}
var keyModel = Key(.Shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
for key in ["Z", "X", "C", "V", "B", "N", "M"] {
var keyModel = Key(.Character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}
var backspace = Key(.Backspace)
defaultKeyboard.addKey(backspace, row: 2, page: 0)
var keyModeChangeNumbers = Key(.ModeChange)
keyModeChangeNumbers.uppercaseKeyCap = "123"
keyModeChangeNumbers.toMode = 1
defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0)
var keyboardChange = Key(.KeyboardChange)
defaultKeyboard.addKey(keyboardChange, row: 3, page: 0)
var settings = Key(.Settings)
defaultKeyboard.addKey(settings, row: 3, page: 0)
var space = Key(.Space)
space.uppercaseKeyCap = "space"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(space, row: 3, page: 0)
var returnKey = Key(.Return)
returnKey.uppercaseKeyCap = "return"
returnKey.uppercaseOutput = "\n"
returnKey.lowercaseOutput = "\n"
defaultKeyboard.addKey(returnKey, row: 3, page: 0)
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
var keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 1)
}
for key in ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""] {
var keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
var keyModeChangeSpecialCharacters = Key(.ModeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1)
for key in [".", ",", "?", "!", "'"] {
var keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 1)
var keyModeChangeLetters = Key(.ModeChange)
keyModeChangeLetters.uppercaseKeyCap = "ABC"
keyModeChangeLetters.toMode = 0
defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 1)
defaultKeyboard.addKey(Key(settings), row: 3, page: 1)
defaultKeyboard.addKey(Key(space), row: 3, page: 1)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1)
for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] {
var keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 2)
}
for key in ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"] {
var keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
for key in [".", ",", "?", "!", "'"] {
var keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 2)
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 2)
defaultKeyboard.addKey(Key(settings), row: 3, page: 2)
defaultKeyboard.addKey(Key(space), row: 3, page: 2)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 2)
return defaultKeyboard
}
| bsd-3-clause | 9be4013737f45a28915de46b4cf096c5 | 32.476923 | 75 | 0.596507 | 3.742046 | false | false | false | false |
Kruks/FindViewControl | FindViewControl/FindViewControl/VIewController/FindView.swift | 1 | 48422 | //
// FindView.swift
// FindViewControl
//
// Created by Krutika Mac Mini on 3/8/17.
// Copyright © 2017 Kahuna. All rights reserved.
//
import UIKit
import GoogleMaps
import MBProgressHUD
class FindView: UIView, UITextFieldDelegate, FindFilterTableViewControllerDelegate, GMSMapViewDelegate, FindHTTPRequestDelegate, FindMultipleLocationViewControllerDelegate {
var parentViewController: UIViewController?
var filterArray: [FilterObject]!
@IBOutlet weak var searchTextField: UITextField!
@IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var goButton: UIButton!
@IBOutlet weak var useCurrentLocButton: UIButton!
var useGooglePlaces: Bool!
var gisURL: String!
var infoWindowView: InfoWindowView!
var infoWindowTable: UITableView!
var currentLocationMarker: GMSMarker!
var selectedLocation: String!
var isUseCurrentLocationClicked = false
var isInitialLoading = false
var gisAddressResultArray: NSMutableArray!
var serviceRequestType: String!
var selectedLocationInfoDict: FindResult!
var pinLocationType: String!
var selectedFiltersArray: [FilterObject]!
var markerIndex: Int! = 0
let radiusOfEarth: Double = 6371
let conversionKmToMiles: Double = 0.621371192
let searchRadius: Double = 1000
var placesArray: [PlacesObject]! = [PlacesObject]()
var selectedPlace: PlacesObject!
var googlePlacesAPIKey: String!
var defaultLattitude: Double!
var defaultLongitude: Double!
var defaultAddress: String!
var isInitialCall: Bool!
var prevSelectedMarker: GMSMarker!
var nearbyPlacesArray: [NearByInfo]! = [NearByInfo]()
var selectedNearbyPlace: NearByInfo!
var individualMarkersCount: Int!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setNeedsDisplay()
//Setting notification to get current location
}
override func layoutSubviews() {
if isInitialCall == true {
isInitialCall = false
if useGooglePlaces == false {
filterArray = [FilterObject]()
filterArray = FindHandler().filterTypesFromDatabase()
}
NotificationCenter.default.addObserver(self, selector: #selector(locationFound(notify:)), name: NSNotification.Name(rawValue: "LocationFound"), object: nil)
self.goButton.setTitle("goText".localized, for: UIControlState.normal)
self.useCurrentLocButton.setTitle("useCurrentLocation".localized, for: UIControlState.normal)
prevSelectedMarker = nil
if selectedFiltersArray == nil {
self.selectedFiltersArray = [FilterObject]()
self.selectedFiltersArray.append(contentsOf: filterArray)
}
if CLLocationManager.locationServicesEnabled() == true && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.denied {
self.getCurrentLocationIntitally()
}
else {
self.setUpView()
}
}
}
//MARK:- Initializing View
func setUpView() {
let hud = MBProgressHUD.showAdded(to: self, animated: true)
hud?.labelText = "gatheringLocInfoHudTitle".localized
self.setPaddingToTextField(textField: self.searchTextField, padding: 5)
self.setUpGoogleMap()
// check current location
if(self.selectedLocationInfoDict != nil) {
if((Double(self.selectedLocationInfoDict.geometry.location.lat) != 0) && (Double(self.selectedLocationInfoDict.geometry.location.lng) != 0)) {
let mapLocation = CLLocationCoordinate2D(
latitude: Double(self.selectedLocationInfoDict.geometry.location.lat),
longitude: Double(self.selectedLocationInfoDict.geometry.location.lng))
self.currentLocationMarker.position = mapLocation
self.searchTextField.text = self.selectedLocationInfoDict.formattedAddress
self.pinLocationType = FindConstants.pinDragDropViewConstants.kCurrentLocationPinType
}
}
if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kCurrentLocationPinType) {
self.currentLocationMarker.title = "currentLocationText".localized
}
else if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kDefaultLocationType) {
self.currentLocationMarker.title = "defaultLocationText".localized
}
else if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kCacheLocationType) {
self.currentLocationMarker.title = "cacheLocationText".localized
}
self.currentLocationMarker.snippet = self.addressStringForLocationType()
self.currentLocationMarker.isDraggable = false
self.currentLocationMarker.map = self.mapView
}
func addressStringForLocationType() -> (String) {
var address = ""
if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kDefaultLocationType) {
address = defaultAddress
}
else if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kCacheLocationType) {
let userDefault = UserDefaults.standard
if(userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSAddressKey) != nil) {
address = userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSAddressKey) as! String
}
}
else if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kCurrentLocationPinType) {
if(self.selectedLocationInfoDict != nil) {
address = self.selectedLocationInfoDict.formattedAddress
}
}
return address
}
func setUpGoogleMap() {
let userDefault = UserDefaults.standard
var latitude = defaultLattitude
var longitude = defaultLongitude
var addressString = defaultAddress
self.pinLocationType = FindConstants.pinDragDropViewConstants.kDefaultLocationType
if (userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSLatitudeKey) != nil) && (userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSLongitudeKey) != nil) && (userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSAddressKey) != nil) {
latitude = userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSLatitudeKey) as? Double
longitude = userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSLongitudeKey) as? Double
addressString = userDefault.object(forKey: FindConstants.UniqueKeyConstants.GMSAddressKey) as? String
self.pinLocationType = FindConstants.pinDragDropViewConstants.kCacheLocationType
}
let position = CLLocationCoordinate2DMake(latitude!, longitude!)
self.addMarkerOnMap(location: position, address: addressString!)
MBProgressHUD.hide(for: self, animated: true)
}
func setPaddingToTextField(textField: UITextField, padding: CGFloat) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: textField.frame.height))
textField.leftView = paddingView
textField.leftViewMode = UITextFieldViewMode.always
}
func addMarkerOnMap(location: CLLocationCoordinate2D, address: String) {
let cameraPosition = GMSCameraPosition.camera(withLatitude: location.latitude, longitude: location.longitude, zoom: FindConstants.DefaultValues.mapZoom)
self.mapView.camera = cameraPosition
self.mapView.delegate = self
self.mapView.isMyLocationEnabled = true
self.mapView.clear()
self.placesArray = [PlacesObject]()
if(self.currentLocationMarker != nil) {
self.currentLocationMarker.map = nil
}
self.currentLocationMarker = GMSMarker(position: location)
if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kCurrentLocationPinType) {
self.currentLocationMarker.title = "currentLocationText".localized
}
else if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kDefaultLocationType) {
self.currentLocationMarker.title = "defaultLocationText".localized
}
else if(self.pinLocationType == FindConstants.pinDragDropViewConstants.kCacheLocationType) {
self.currentLocationMarker.title = "cacheLocationText".localized
}
self.currentLocationMarker.snippet = address
self.currentLocationMarker.isDraggable = false
self.currentLocationMarker.map = self.mapView
let zoomLevel = self.mapView.camera.zoom
let position = GMSCameraPosition.camera(withLatitude: location.latitude, longitude: location.longitude, zoom: zoomLevel)
self.mapView.camera = position
markerIndex = 0
self.searchTextField.text = address
if self.selectedFiltersArray.count > 0 && FindCheckConnectivitySwift.hasConnectivity() {
if self.useGooglePlaces == true {
self.perform(#selector(self.queryGooglePlaces), with: "", afterDelay: 0.1)
}
else {
self.queryFromDB()
}
}
}
//MARK:- Loading & Validating Location
/**
When no address is cached then get current location not called in case of previous selected sr
*/
func getCurrentLocationIntitally() {
self.isInitialLoading = true
self.myLocationButtonClick(sender: UIButton())
}
//MARK:- My Current location Button Click
@IBAction func myLocationButtonClick(sender: AnyObject) {
if self.infoWindowView != nil && self.infoWindowView.superview != nil {
self.infoWindowView.removeFromSuperview()
}
self.searchTextField.resignFirstResponder()
if(FindCheckConnectivitySwift.hasConnectivity()) {
if (CLLocationManager.locationServicesEnabled() == false || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.denied) {
if(!self.isInitialLoading) {
self.isInitialLoading = false
self.displayAlert(title: "locServiceDisabledMsg".localized, message: "gpsDisabledMsg".localized)
}
}
else {
let hud = MBProgressHUD.showAdded(to: self, animated: true)
hud?.labelText = "gatheringLocInfoHudTitle".localized
FindPSLocationManager.shared().startLocationUpdates()
self.isUseCurrentLocationClicked = true
}
}
else {
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + ", " + "networkconnectionMsg".localized
let alertView = UIAlertController(title: "networkErrorTitle".localized, message: errorMsg, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OKButtonLabel".localized, style: .default)
{
UIAlertAction in
if self.isInitialLoading == true
{
self.isInitialLoading = false
self.setUpView()
}
}
alertView.addAction(action)
parentViewController?.present(alertView, animated: true, completion: nil)
}
}
/**
current location notification method called when notification is received
*/
func locationFound(notify: NSNotification) {
FindPSLocationManager.shared().stopLocationUpdates()
if self.isUseCurrentLocationClicked == true {
self.isUseCurrentLocationClicked = false
var isError = false
if (notify.userInfo != nil) {
if (notify.userInfo!["GPSError"] != nil)
{
isError = true
MBProgressHUD.hideAllHUDs(for: self, animated: true)
let error = notify.userInfo!["GPSError"]
self.handleGPSError(code: CLError(_nsError: error as! NSError))
self.isInitialLoading = false
self.selectedLocation = ""
self.selectedLocationInfoDict = nil
}
}
if isError == false {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
let currentLocation = FindPSLocationManager.shared().currentLocation
self.selectedLocation = ""
self.selectedLocationInfoDict = nil
let position = CLLocationCoordinate2DMake((currentLocation?.coordinate.latitude)!, (currentLocation?.coordinate.longitude)!)
self.pinLocationType = FindConstants.pinDragDropViewConstants.kCurrentLocationPinType
self.callForCoOrdinateLocation(location: position)
}
}
}
//MARK:- Location Manager Delegates
func locationManagerStatus(status: NSString) {
print(status)
}
func locationManagerReceivedError(error: NSString) {
print(error)
}
func locationFoundGetAsString(latitude: NSString, longitude: NSString) {
print(latitude)
}
func locationFound(latitude: Double, longitude: Double) {
print(latitude)
}
func handleGPSError(code: CLError) {
switch code {
case CLError.network: // general, network-related error
if self.isInitialLoading == false {
self.displayAlert(title: "gpsErrorTitle".localized, message: "gpsAeroplaneModeMsg".localized)
}
break;
default:
if(!self.isInitialLoading) {
self.displayAlert(title: "gpsErrorTitle".localized, message: "gpsErrorMsg".localized)
}
break;
}
if self.isInitialLoading == true {
self.isInitialLoading = false
self.setUpView()
}
}
func setCurrentLocationDetails() {
if self.currentLocationMarker != nil {
self.saveValidLocationDetails()
}
}
func saveValidLocationDetails() {
let userDefault = UserDefaults.standard
userDefault.set(self.currentLocationMarker.position.latitude, forKey: FindConstants.UniqueKeyConstants.GMSLatitudeKey)
userDefault.set(self.currentLocationMarker.position.longitude, forKey: FindConstants.UniqueKeyConstants.GMSLongitudeKey)
userDefault.set(self.selectedLocation, forKey: FindConstants.UniqueKeyConstants.GMSAddressKey)
userDefault.synchronize()
}
//MARK: - TextField Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let searchText = self.searchTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
if((searchText?.characters.count)! > 0) {
self.searchLocationAddress(address: searchText!)
}
textField.resignFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
self.selectedLocationInfoDict = nil
return true
}
func searchLocationAddress(address: String) {
if(FindCheckConnectivitySwift.hasConnectivity()) {
MBProgressHUD.showAdded(to: self, animated: true)
self.selectedLocation = ""
self.serviceRequestType = FindConstants.pinDragDropViewConstants.serviceReqTypeGeoAddress
self.getDisplayLocationInfoForAddress(address: address)
}
else {
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + ", " + "networkconnectionMsg".localized
self.displayAlert(title: "networkErrorTitle".localized, message: errorMsg)
}
}
// MARK:- Search address
@IBAction func addressSearchGoButtonClick(sender: AnyObject) {
if self.infoWindowView != nil && self.infoWindowView.superview != nil {
self.infoWindowView.removeFromSuperview()
}
let searchText = self.searchTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
if((searchText?.characters.count)! > 0) {
self.callForAddressLocation(addressString: self.searchTextField.text!)
}
else {
self.displayAlert(title: "enterLocEmptyMsg".localized, message: "")
}
}
func callForCoOrdinateLocation(location: CLLocationCoordinate2D) {
if(FindCheckConnectivitySwift.hasConnectivity()) {
let hud = MBProgressHUD.showAdded(to: self, animated: true)
hud?.labelText = "gatheringLocInfoHudTitle".localized
let location = location
self.selectedLocation = ""
self.serviceRequestType = FindConstants.pinDragDropViewConstants.serviceReqTypeGeoCordinate
self.getDisplayLocationInfoForCoOrdinate(Location: location)
} else {
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + ", " + "networkconnectionMsg".localized
let alertView = UIAlertController(title: "networkErrorTitle".localized, message: errorMsg, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OKButtonLabel".localized, style: .default) {
UIAlertAction in
if self.isInitialLoading == true {
self.isInitialLoading = false
self.setUpView()
}
}
alertView.addAction(action)
parentViewController?.present(alertView, animated: true, completion: nil)
}
}
func callForAddressLocation(addressString: String) {
self.searchTextField.resignFirstResponder()
if(FindCheckConnectivitySwift.hasConnectivity()) {
let hud = MBProgressHUD.showAdded(to: self, animated: true)
hud?.labelText = "gatheringLocInfoHudTitle".localized
// call GIS service for address
self.selectedLocation = ""
self.serviceRequestType = FindConstants.pinDragDropViewConstants.serviceReqTypeGeoAddress
self.getDisplayLocationInfoForAddress(address: addressString)
}
else {
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + " ," + "networkconnectionMsg".localized
self.displayAlert(title: "networkErrorTitle".localized, message: errorMsg)
}
}
/**
call GIS service for co-ordinates when user drag drop the pin
*/
func getDisplayLocationInfoForCoOrdinate(Location: CLLocationCoordinate2D) {
if FindCheckConnectivitySwift.hasConnectivity() {
// call coordinate search service
let coOrdinateRequestObj = GISAddressSearchRequest()
coOrdinateRequestObj.latitude = Float(Location.latitude)
coOrdinateRequestObj.longitude = Float(Location.longitude)
coOrdinateRequestObj.requestType = self.serviceRequestType
self.getMatchesForCurrentLocation(coOrdinateSearchReq: coOrdinateRequestObj)
}
else {
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + ", " + "networkconnectionMsg".localized
let alertView = UIAlertController(title: "networkErrorTitle".localized, message: errorMsg, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OKButtonLabel".localized, style: .cancel) {
UIAlertAction in
if self.isInitialLoading == true
{
self.isInitialLoading = false
self.setUpView()
}
}
alertView.addAction(cancelAction)
parentViewController?.present(alertView, animated: true, completion: nil)
}
}
/**
call GIS service for address when user enters address in search field
*/
func getDisplayLocationInfoForAddress(address: String) {
if FindCheckConnectivitySwift.hasConnectivity() {
// call coordinate search service
let addressRequestObj = GISAddressSearchRequest()
addressRequestObj.address = address
addressRequestObj.requestType = self.serviceRequestType
self.getMatchesForCurrentLocation(coOrdinateSearchReq: addressRequestObj)
}
else {
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + ", " + "networkconnectionMsg".localized
self.displayAlert(title: "networkErrorTitle".localized, message: errorMsg)
}
}
// MARK:- Filter Button action
@IBAction func filtersButton_Clicked() {
if parentViewController?.menuContainerViewController != nil {
let bundle = Bundle(identifier: FindConstants.findBundleID)
let viewController = bundle?.loadNibNamed("FindFilterTableViewController", owner: self, options: nil)![0] as! FindFilterTableViewController
viewController.selectedFiltersArray = [FilterObject]()
viewController.selectedFiltersArray.append(contentsOf: selectedFiltersArray)
viewController.filterArray = [FilterObject]()
viewController.filterArray.append(contentsOf: filterArray)
viewController.delegate = self
let nav = UINavigationController(rootViewController: viewController)
nav.navigationBar.barStyle = UIBarStyle.black
parentViewController?.menuContainerViewController.rightMenuViewController = nav
parentViewController?.menuContainerViewController.toggleRightSideMenuCompletion(nil)
}
}
//MARK:- Filter Delegate
func filtersTableViewController(selectedFilters: [FilterObject]) {
let hud = MBProgressHUD.showAdded(to: self, animated: true)
hud?.labelText = "gatheringLocInfoHudTitle".localized
markerIndex = 0
if self.infoWindowView != nil && self.infoWindowView.superview != nil {
self.infoWindowView.removeFromSuperview()
}
self.mapView.clear()
self.placesArray = [PlacesObject]()
self.currentLocationMarker.map = self.mapView
self.selectedFiltersArray.removeAll()
selectedFiltersArray = [FilterObject]()
self.selectedFiltersArray.append(contentsOf: selectedFilters)
if self.selectedFiltersArray.count > 0 {
if self.useGooglePlaces == true {
self.queryGooglePlaces(nextPageToken: "")
}
else {
self.queryFromDB()
}
}
else {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
}
self.setMapCenter()
}
//MARK:- Set Map Center
func setMapCenter() {
let zoomLevel = self.mapView.camera.zoom
let position = GMSCameraPosition.camera(withLatitude: self.currentLocationMarker.position.latitude, longitude: self.currentLocationMarker.position.longitude, zoom: zoomLevel)
self.mapView.camera = position
}
func queryFromDB() {
var filterArr = [String]()
for filterObj in selectedFiltersArray {
filterArr.append(filterObj.filterID)
}
nearbyPlacesArray = FindHandler().getDatafromDB(searchType: filterArr, isAllCategories: false)
if selectedFiltersArray.count == self.filterArray.count {
self.sortArray()
}
else {
self.plotNearbyPlacesMarker()
}
}
func plotNearbyPlacesMarker() {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
markerIndex = 0
self.mapView.clear()
var bounds = GMSCoordinateBounds()
self.currentLocationMarker.map = self.mapView
bounds = bounds.includingCoordinate(self.currentLocationMarker.position)
for placeObj in nearbyPlacesArray {
let markerOptions1 = GMSMarker()
markerOptions1.position = CLLocationCoordinate2DMake(Double(placeObj.nearLat)!, Double(placeObj.nearLong)!)
let imgName = "\(placeObj.nearLocationType!).png"
markerOptions1.icon = UIImage(named: imgName)
markerOptions1.infoWindowAnchor = CGPoint(x: 0.5, y: 0.25)
markerOptions1.groundAnchor = CGPoint(x: 0.5, y: 1.0)
markerOptions1.accessibilityLabel = String(format: "%d", markerIndex)
markerOptions1.map = self.mapView
markerIndex = markerIndex + 1
bounds = bounds.includingCoordinate(markerOptions1.position)
}
self.mapView.animate(with: GMSCameraUpdate.fit(bounds))
}
//MARK:- Call Google Places API
func queryGooglePlaces (nextPageToken: String) {
var url = ""
if nextPageToken == "" {
var type = ""
for filterObj in selectedFiltersArray {
if type == "" {
type = filterObj.filterID
}
else
{
type = type + "|" + filterObj.filterID
}
}
url = "\(FindConstants.findConstants.kGooglePlacesUrl)location=\(self.currentLocationMarker.position.latitude),\(self.currentLocationMarker.position.longitude)&radius=\(self.radiusOfEarth)&types=\(type)&sensor=true&key=\(googlePlacesAPIKey!)"
}
else {
url = "\(FindConstants.findConstants.kGooglePlacesUrl)pagetoken=\(nextPageToken)&key=\(googlePlacesAPIKey)"
}
let customAllowedSet = NSCharacterSet(charactersIn: "|").inverted
let escapedString = url.addingPercentEncoding(withAllowedCharacters: customAllowedSet)
print("URL : \(escapedString)")
if(FindCheckConnectivitySwift.hasConnectivity()) {
if let googleRequestURL = NSURL(string: escapedString!) {
if let data = NSData(contentsOf: googleRequestURL as URL) {
self.fetchedData(responseData: data)
}
else {
self.displayAlert(title: "unableFindPlacesTitle".localized, message: "")
MBProgressHUD.hideAllHUDs(for: self, animated: true)
}
}
else {
self.displayAlert(title: "unableFindPlacesTitle".localized, message: "")
MBProgressHUD.hideAllHUDs(for: self, animated: true)
}
}
else {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + ", " + "networkconnectionMsg".localized
self.displayAlert(title: "networkErrorTitle".localized, message: errorMsg)
}
}
//MARK:- Verify Google Places API Response
func fetchedData(responseData: NSData) {
var isQueryComplete = false
do {
let jsonResult: NSDictionary! = try JSONSerialization.jsonObject(with: responseData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
if (jsonResult != nil) {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
let placesResp = PlacesAPIResponseModel (fromDictionary: jsonResult as NSDictionary)
isQueryComplete = true
if placesResp.results != nil && placesResp.results.count > 0 {
placesArray.append(contentsOf: placesResp.results)
}
else {
self.displayAlert(title: "noPlacesFoundTitle".localized, message: "")
}
}
else {
if placesArray.count > 0 {
isQueryComplete = true
}
else {
self.displayAlert(title: "unableFindPlacesTitle".localized, message: "")
}
MBProgressHUD.hideAllHUDs(for: self, animated: true)
}
}
catch {
if(placesArray.count > 0) {
isQueryComplete = true
}
else {
self.displayAlert(title: "unableFindPlacesTitle".localized, message: "")
}
MBProgressHUD.hideAllHUDs(for: self, animated: true)
}
if isQueryComplete == true {
isQueryComplete = false
if(FindCheckConnectivitySwift.hasConnectivity()) {
self.addPlacesMarker()
}
else {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
let appName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let errorMsg = appName + ", " + "networkconnectionMsg".localized
self.displayAlert(title: "networkErrorTitle".localized, message: errorMsg)
}
}
}
//MARK:- Add places marker on map
func addPlacesMarker() {
markerIndex = 0
self.mapView.clear()
var bounds = GMSCoordinateBounds()
self.currentLocationMarker.map = self.mapView
bounds = bounds.includingCoordinate(self.currentLocationMarker.position)
for placeObj in placesArray {
let markerOptions1 = GMSMarker()
markerOptions1.position = CLLocationCoordinate2DMake(Double(placeObj.geometry.location.lat), Double(placeObj.geometry.location.lng))
if(placeObj.icon != nil && placeObj.icon.characters.count > 0) {
let url = NSURL(string: placeObj.icon)
let data = NSData(contentsOf: url! as URL)
markerOptions1.icon = UIImage(data: data! as Data, scale: 2.0)
}
markerOptions1.infoWindowAnchor = CGPoint(x: 0.5, y: 0.25)
markerOptions1.groundAnchor = CGPoint(x: 0.5, y: 1.0)
markerOptions1.accessibilityLabel = String(format: "%d", markerIndex)
markerOptions1.map = self.mapView
markerIndex = markerIndex + 1
bounds = bounds.includingCoordinate(markerOptions1.position)
}
self.mapView.animate(with: GMSCameraUpdate.fit(bounds))
}
//MARK:- GMSMapView delegate
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
self.endEditing(true)
if marker != self.currentLocationMarker {
if useGooglePlaces == true {
self.setInfoViewForGooglePlaces(marker: marker)
}
else {
self.setInfoViewForDBPlaces(marker: marker)
}
}
else {
self.hideInfoView(value: self.frame.size.height)
}
return false
}
func setInfoViewForGooglePlaces(marker: GMSMarker) {
if self.placesArray.count > Int(marker.accessibilityLabel!)! {
if prevSelectedMarker != nil && self.selectedPlace != nil {
if(self.selectedPlace.icon != nil && self.selectedPlace.icon.characters.count > 0) {
let url = NSURL(string: self.selectedPlace.icon)
let data = NSData(contentsOf: url! as URL)
prevSelectedMarker.icon = UIImage(data: data! as Data, scale: 2.0)
}
}
self.selectedPlace = self.placesArray[Int(marker.accessibilityLabel!)!]
if(self.selectedPlace.icon != nil && self.selectedPlace.icon.characters.count > 0) {
let url = NSURL(string: self.selectedPlace.icon)
let data = NSData(contentsOf: url! as URL)
marker.icon = UIImage(data: data! as Data, scale: 1.0)
}
prevSelectedMarker = marker
if infoWindowView != nil {
infoWindowView.removeFromSuperview()
}
let bundle = Bundle(identifier: FindConstants.findBundleID)
infoWindowView = bundle?.loadNibNamed("InfoWindowView", owner: self, options: nil)![0] as? InfoWindowView
infoWindowView.frame = CGRect(x: 0, y: self.frame.size.height - 100, width: self.frame.size.width, height: 100)
infoWindowView.nameLabel.text = self.selectedPlace.name
infoWindowView.addressLabel.text = self.selectedPlace.vicinity
if(self.selectedPlace.icon != nil && self.selectedPlace.icon.characters.count > 0) {
let url = NSURL(string: self.selectedPlace.icon)
let data = NSData(contentsOf: url! as URL)
infoWindowView.markerIcon.image = UIImage(data: data! as Data, scale: 1.0)
}
infoWindowView.getDirectionsButton.addTarget(self, action: #selector(self.onGetDirectionButtonClick(sender:)), for: UIControlEvents.touchUpInside)
self.setUpInfoView()
}
else {
self.selectedPlace = nil
}
}
func setInfoViewForDBPlaces(marker: GMSMarker) {
if self.nearbyPlacesArray.count > Int(marker.accessibilityLabel!)! {
if prevSelectedMarker != nil && self.selectedNearbyPlace != nil {
let imgName = "\(self.selectedNearbyPlace.nearLocationType!).png"
prevSelectedMarker.icon = UIImage(named: imgName)
}
self.selectedNearbyPlace = self.nearbyPlacesArray[Int(marker.accessibilityLabel!)!]
let imgName = "\(self.selectedNearbyPlace.nearLocationType!)Selected.png"
let filePath = Bundle.main.path(forResource: imgName, ofType: nil)
if filePath != nil {
marker.icon = UIImage(named: imgName)
}
else {
let bundle = Bundle(identifier: FindConstants.findBundleID)
marker.icon = UIImage(named: "default_markerSelected.png", in: bundle, compatibleWith: nil)
}
prevSelectedMarker = marker
if infoWindowView != nil {
infoWindowView.removeFromSuperview()
}
let bundle = Bundle(identifier: FindConstants.findBundleID)
infoWindowView = bundle?.loadNibNamed("InfoWindowView", owner: self, options: nil)![0] as? InfoWindowView
infoWindowView.frame = CGRect(x: 0, y: self.frame.size.height - 100, width: self.frame.size.width, height: 100)
infoWindowView.nameLabel.text = self.selectedNearbyPlace.nearFacilityName
infoWindowView.addressLabel.text = self.selectedNearbyPlace.nearAddress
if filePath != nil {
infoWindowView.markerIcon.image = UIImage(named: imgName)
}
else {
let bundle = Bundle(identifier: FindConstants.findBundleID)
infoWindowView.markerIcon.image = UIImage(named: "default_markerSelected.png", in: bundle, compatibleWith: nil)
}
infoWindowView.getDirectionsButton.addTarget(self, action: #selector(self.onGetDirectionButtonClick(sender:)), for: UIControlEvents.touchUpInside)
self.setUpInfoView()
}
else {
self.selectedNearbyPlace = nil
}
}
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
if self.infoWindowView != nil {
self.hideInfoView(value: self.frame.size.height)
}
}
// MARK: - Setup Info window
func setUpInfoView() {
UIView.animate(withDuration: 0.0,
delay: 0.0,
options: .transitionCurlUp,
animations: {
self.infoWindowView.frame = CGRect(x: 0, y: self.frame.size.height, width: self.frame.size.width, height: 100)
},
completion: { finished in
self.addSubview(self.infoWindowView)
UIView.animate(withDuration: 0.3,
delay: 0.0,
options: .transitionCurlDown,
animations: {
self.infoWindowView.frame = CGRect(x: 0, y: self.frame.size.height - 100, width: self.frame.size.width, height: 100)
},
completion: { finished in
})
})
}
// MARK: - Inde info window
func hideInfoView(value: CGFloat) {
if useGooglePlaces == true {
if prevSelectedMarker != nil && self.selectedPlace != nil {
if(self.selectedPlace.icon != nil && self.selectedPlace.icon.characters.count > 0) {
let url = NSURL(string: self.selectedPlace.icon)
let data = NSData(contentsOf: url! as URL)
prevSelectedMarker.icon = UIImage(data: data! as Data, scale: 2.0)
}
}
}
else {
if prevSelectedMarker != nil && self.selectedNearbyPlace != nil {
let imgName = "\(self.selectedNearbyPlace.nearLocationType!).png"
prevSelectedMarker.icon = UIImage(named: imgName)
}
}
UIView.animate(withDuration: 0.3,
delay: 0.0,
options: .transitionCurlUp,
animations: {
if self.infoWindowView != nil {
self.infoWindowView.frame = CGRect(x: 0, y: value, width: self.frame.size.width, height: 100)
}
},
completion: { finished in
if self.infoWindowView != nil {
self.infoWindowView.removeFromSuperview()
}
})
}
@IBAction func onGetDirectionButtonClick(sender: AnyObject) {
var http = ""
if useGooglePlaces == true {
http = "http://maps.apple.com/?saddr=\(self.currentLocationMarker.position.latitude),\(self.currentLocationMarker.position.longitude)&daddr=\(self.selectedPlace.geometry.location.lat!),\(self.self.selectedPlace.geometry.location.lng!)"
}
else {
http = "http://maps.apple.com/?saddr=\(self.currentLocationMarker.position.latitude),\(self.currentLocationMarker.position.longitude)&daddr=\(self.selectedNearbyPlace.nearLat!),\(self.self.selectedNearbyPlace.nearLong!)"
}
UIApplication.shared.openURL(NSURL(string: http)! as URL)
}
//MARK:- Display Alert
func displayAlert (title: String, message: String) {
let alertView = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OKButtonLabel".localized, style: .default, handler: nil)
alertView.addAction(action)
parentViewController?.present(alertView, animated: true, completion: nil)
}
//Mark: fetch address from co-ordinates
func getMatchesForCurrentLocation(coOrdinateSearchReq: GISAddressSearchRequest) {
let requestParameters = coOrdinateSearchReq.toDictionary()
let requestHandler = FindHTTPRequest.sharedInstance
requestHandler.delegate = self
requestHandler.sendRequestAtPath(gisURL, withParameters: requestParameters as? [String: AnyObject], timeoutInterval: Constants.TimeOutIntervals.kSRTimeoutInterval)
}
// MARK: - CONFIRMING HTTP REQUEST DELEGATE
func httpRequest(_ requestHandler: FindHTTPRequest, requestCompletedWithResponseJsonObject jsonObject: AnyObject, forPath path: String) {
self.handleGISResponse(jsonObject: jsonObject)
}
func httpRequest(_ requestHandler: FindHTTPRequest, requestFailedWithError failureError: Error, forPath path: String) {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
let intCode = failureError._code
let errorMessage = String(format: "%@ - %d", failureError._domain, intCode)
self.selectedLocation = ""
self.selectedLocationInfoDict = nil
let alertView = UIAlertController(title: "", message: errorMessage, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OKButtonLabel".localized, style: UIAlertActionStyle.cancel) {
UIAlertAction in
if self.isInitialLoading == true {
self.isInitialLoading = false
self.setUpView()
}
}
alertView.addAction(cancelAction)
parentViewController?.present(alertView, animated: true, completion: nil)
}
func handleGISResponse(jsonObject: AnyObject) {
MBProgressHUD.hideAllHUDs(for: self, animated: true)
let gisResponse = FindGISAddressSearchResponse(fromDictionary: jsonObject as! NSDictionary)
if gisResponse.status == nil {
MBProgressHUD.hide(for: self, animated: true)
if self.isInitialLoading == true {
self.isInitialLoading = false
self.setUpView()
}
return
}
if gisResponse.status.code == FindConstants.ServerResponseCodes.successCode {
print(gisResponse.response.results)
let resultsArray = gisResponse.response.results
if((resultsArray?.count)! > 0) {
self.gisAddressResultArray = NSMutableArray(array: resultsArray!)
if((resultsArray?.count)! > 1) {
let bundle = Bundle(identifier: FindConstants.findBundleID)
let multipleLocationObj = bundle?.loadNibNamed("FindMultipleLocationSelectionViewController", owner: self, options: nil)![0] as! FindMultipleLocationSelectionViewController
multipleLocationObj.setLocaArray(locArray: self.gisAddressResultArray)
multipleLocationObj.delegate = self
multipleLocationObj.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext;
parentViewController?.present(multipleLocationObj, animated: true, completion: nil)
} else {
let dataDict = self.gisAddressResultArray.object(at: 0) as! FindResult
self.selectedLocation = dataDict.formattedAddress
let tempdict = dataDict.geometry.location
let mapLocation = CLLocationCoordinate2D(
latitude: Double(((tempdict?.lat)! as Float)),
longitude: Double(((tempdict?.lng)! as Float))
)
self.searchTextField.text = self.selectedLocation
self.selectedLocationInfoDict = dataDict
self.pinLocationType = FindConstants.pinDragDropViewConstants.kCurrentLocationPinType
self.addMarkerOnMap(location: mapLocation, address: self.selectedLocation)
self.setCurrentLocationDetails()
}
}
} else {
let errorMessage = gisResponse.status.message
let message = String(format: "%@%d", "errorCodeTitle".localized, gisResponse.status.code)
let alertView = UIAlertController(title: errorMessage, message: message, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OKButtonLabel".localized, style: UIAlertActionStyle.cancel) {
UIAlertAction in
if self.isInitialLoading == true
{
self.isInitialLoading = false
self.setUpView()
}
}
alertView.addAction(cancelAction)
parentViewController?.present(alertView, animated: true, completion: nil)
}
}
//MARK: Multiple Location Delegate
func locationSelectedFromMultipleLocation(selectedLocationAddress selectedLocationAddressDictionary: FindResult) {
//Call Service to check if the address is inside nagpur
self.selectedLocationInfoDict = selectedLocationAddressDictionary
self.selectedLocation = self.selectedLocationInfoDict.formattedAddress
self.searchTextField.text = self.selectedLocation
let tempdict = self.selectedLocationInfoDict.geometry.location
let mapLocation = CLLocationCoordinate2D(
latitude: Double(((tempdict?.lat)! as Float)),
longitude: Double(((tempdict?.lng)! as Float))
)
self.addMarkerOnMap(location: mapLocation, address: self.selectedLocation)
self.pinLocationType = FindConstants.pinDragDropViewConstants.kCurrentLocationPinType
self.setCurrentLocationDetails()
}
func sortArray() {
let nearbyArray = self.getNearbyArray(nearArray: self.nearbyPlacesArray)
self.nearbyPlacesArray = [NearByInfo]()
for filterObj in filterArray {
let array = nearbyArray.filter { $0.nearLocationType == filterObj.filterID }
self.sortArray(nearByArray: array)
}
self.plotNearbyPlacesMarker()
}
func sortArray(nearByArray: [NearByInfo]) {
let array = nearByArray.sorted { (p1: NearByInfo, p2: NearByInfo) -> Bool in
return p1.distance < p2.distance
}
for i in stride(from: 0, through: self.individualMarkersCount, by: 1) {
if array.count > i {
self.nearbyPlacesArray.append(array[i])
}
}
}
func getNearbyArray(nearArray: [NearByInfo]) -> [NearByInfo] {
var nearbyArray = [NearByInfo]()
for nearInfo in nearArray {
nearInfo.distance = self.getDistance(fromLat: self.currentLocationMarker.position.latitude, fromLong: self.currentLocationMarker.position.longitude, toLat: Double(nearInfo.nearLat)!, toLong: Double(nearInfo.nearLat)!)
nearbyArray.append(nearInfo)
}
return nearbyArray
}
func getDistance(fromLat: Double, fromLong: Double, toLat: Double, toLong: Double) -> Double {
let latDist = self.toRad(val: toLat - fromLat)
let longDist = self.toRad(val: toLong - fromLong)
let a = sin(latDist / 2) * sin(latDist / 2) + cos(self.toRad(val: fromLat)) * cos(self.toRad(val: toLat)) * sin(longDist / 2) * sin(longDist / 2)
let c = 2 * atan2(sqrt(a), sqrt(1 - a))
return self.radiusOfEarth * c * self.conversionKmToMiles
}
func toRad(val: Double) -> Double {
return val * M_PI / 180
}
}
extension String {
var localized: String {
let bundle = Bundle(identifier: FindConstants.findBundleID)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
| mit | ee46b556a5d2774e0aa30b67e7ea3564 | 42.859601 | 273 | 0.616385 | 5.193714 | false | false | false | false |
hiragram/AbstractionKit | AbstractionKitSample/Endpoint.swift | 1 | 1287 | //
// Endpoint.swift
// AbstractionKit
//
// Created by Yuya Hirayama on 2017/09/24.
// Copyright © 2017年 Yuya Hirayama. All rights reserved.
//
import Foundation
import AbstractionKit
struct Endpoint {
struct GetForecast: EndpointDefinition {
typealias Response = ListKeyResponse<ArrayResponse<Forecast>>
var path: String = "/forecast"
static var environment: Environment = .init()
let parameters: [String: Any]
var method: HTTPMethod = .get
var header: [String : String] {
return ["Endpoint-Specific-Header": "Hello"]
}
init(cityName: String, countryCode: String) {
parameters = [
"q": "\(cityName),\(countryCode)",
"appid": "_"
]
}
}
}
struct ListKeyResponse<T: DataResponseDefinition>: DataResponseDefinition {
typealias Result = T.Result
typealias JSON = [String: Any]
var result: Result
static var jsonKey: String {
return "list"
}
init(json: JSON) throws {
guard let tJSON = json[ListKeyResponse<T>.jsonKey] as? T.JSON else {
throw CombinedResponseError.keyNotFound(key: ListKeyResponse<T>.jsonKey)
}
result = try T.init(json: tJSON).result
}
}
| mit | 28a612da10bf64b57e8340c15ab3524f | 25.204082 | 84 | 0.608255 | 4.237624 | false | false | false | false |
b3log/symphony-ios | HPApp/ChromeActivity.swift | 1 | 1550 | //
// ChromeActivity.swift
// HPApp
//
// Created by André Schneider on 16.03.15.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
class ChromeActivity: UIActivity {
private var url: NSURL?
override func activityType() -> String? {
return "ChromeActivity"
}
override func activityTitle() -> String? {
return "Open in Chrome"
}
override func activityImage() -> UIImage? {
return UIImage(named: "chrome-activity-icon")
}
override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool {
if let chromeURL = NSURL(string: "googlechrome-x-callback://") {
if !UIApplication.sharedApplication().canOpenURL(chromeURL) {
return false
}
for item in activityItems {
if let item = item as? NSURL {
if UIApplication.sharedApplication().canOpenURL(item) {
return true
}
}
}
}
return false
}
override func prepareWithActivityItems(activityItems: [AnyObject]) {
for item in activityItems {
if let item = item as? NSURL {
url = item
}
}
}
override func performActivity() {
if let url = url {
if let chromeURL = NSURL(string: "googlechrome-x-callback://x-callback-url/open/?url=\(url)") {
UIApplication.sharedApplication().openURL(chromeURL)
}
}
}
}
| apache-2.0 | 6ec66eb55518f9d3f17c5c8f9f6ac245 | 26.175439 | 107 | 0.553906 | 4.780864 | false | false | false | false |
PeteShearer/SwiftNinja | 012-Intro to Protocols/Lesson 012 - Protocols.playground/Contents.swift | 1 | 2543 | /*
// Protocols can act like interfaces in other languages
protocol Car {
}
class Camry: Car {
}
var genericCar: Car
genericCar = Camry()
print (genericCar) // <-- Prints Camry
*/
protocol Car {
var numberOfCylinders: Int {get}
var color: String {get set}
}
/*
// If we leave this blank, we get errors
class Camry: Car {
}
// error: type 'Camry' does not conform to protocol 'Car'
// note: protocol requires property 'numberOfCylinders' with type 'Int'
// note: protocol requires property 'color' with type 'String'
*/
// Instead, we have to define "the minimum"
class Camry: Car {
var numberOfCylinders: Int { return 6 }
var color: String
init(color: String) {
self.color = color
}
}
var genericCar: Car
genericCar = Camry(color: "Black")
print(genericCar.color) // <-- Prints Black
// We can add Protocols to classes we don't even own retroactively!!!
protocol BiggieSize {
var doubleUp: String {get}
}
extension String: BiggieSize {
var doubleUp: String {
return "\(self)\(self)"
}
}
func usingAProtocolAsAParameter(input: BiggieSize) {
print(input.doubleUp)
}
usingAProtocolAsAParameter(input: "Pete") // <-- prints PetePete
protocol A {
var foo: String {get set}
func talk() -> Void
}
protocol B {
var bar: String {get set}
func talkAlso() -> Void
}
func demonstrateIntersection(input: A & B) -> Void {
input.talk()
input.talkAlso()
}
class onlyHasA: A {
var foo: String = ""
init(foo: String) {
self.foo = foo
}
func talk() -> Void {
print(self.foo)
}
}
class onlyHasB: B {
var bar: String = ""
init(bar: String) {
self.bar = bar
}
func talkAlso() -> Void {
print(self.bar)
}
}
class hasBoth: A, B {
var foo: String = ""
var bar: String = ""
init(foo: String, bar: String) {
self.foo = foo
self.bar = bar
}
func talk() -> Void {
print(foo)
}
func talkAlso() -> Void {
print(bar)
}
}
var aVariable = onlyHasA(foo: "FOOO!")
var bVariable = onlyHasB(bar: "BARRRRR!")
var bothVariable = hasBoth(foo: "FOOOO!", bar: "BARRRR!")
// error: argument type 'onlyHasA' does not conform to expected type 'protocol<A, B>'
// demonstrateIntersection(aVariable)
// error: argument type 'onlyHasB' does not conform to expected type 'protocol<A, B>'
// demonstrateIntersection(bVariable)
demonstrateIntersection(input: bothVariable) // <-- WORKS!
| bsd-2-clause | c2a5511f0e185b182bc293447a28b7c9 | 17.427536 | 85 | 0.614628 | 3.395194 | false | false | false | false |
Baglan/MCResource | Classes/LocalODRSource.swift | 1 | 3694 | //
// LocalODRSource.swift
// MCResourceLoader
//
// Created by Baglan on 06/11/2016.
// Copyright © 2016 Mobile Creators. All rights reserved.
//
import Foundation
extension MCResource {
class LocalODRSource: MCResourceSource, ErrorSource {
let fractionCompleted: Double = 0
let url: URL
var priority: Int
init(url: URL, priority: Int = 0) {
self.url = url
self.priority = priority
}
var request: NSBundleResourceRequest?
let queueHelper = OperationQueueHelper()
func beginAccessing(completionHandler: @escaping (URL?, Error?) -> Void) {
guard request == nil else {
completionHandler(nil, ErrorHelper.error(for: ErrorCodes.AlreadyAccessing.rawValue, source: self))
return
}
guard let scheme = url.scheme, scheme == "odr" else {
completionHandler(nil, ErrorHelper.error(for: ErrorCodes.SchemeNotSupported.rawValue, source: self))
return
}
guard let tag = url.host else {
completionHandler(nil, ErrorHelper.error(for: ErrorCodes.TagMissingFromURL.rawValue, source: self))
return
}
var path = url.path
guard path != "" else {
completionHandler(nil, ErrorHelper.error(for: ErrorCodes.PathMissingFromURL.rawValue, source: self))
return
}
path.remove(at: path.startIndex)
let ch = completionHandler
queueHelper.preferred = OperationQueue.current
request = NSBundleResourceRequest(tags: [tag])
request?.conditionallyBeginAccessingResources(completionHandler: { (available) in
if available {
guard let resourceURL = Bundle.main.url(forResource: path, withExtension: nil) else {
self.queueHelper.queue.addOperation { [unowned self] in
completionHandler(nil, ErrorHelper.error(for: ErrorCodes.NotFoundInBundle.rawValue, source: self))
}
return
}
self.queueHelper.queue.addOperation {
ch(resourceURL, nil)
}
} else {
self.queueHelper.queue.addOperation { ch(nil, ErrorHelper.error(for: ErrorCodes.NotReadilyAvailable.rawValue, source: self)) }
}
})
}
func endAccessing() {
request?.endAccessingResources()
request = nil
}
// MARK: - Errors
static let errorDomain = "MCResourceLocalODRSourceErrorDomain"
enum ErrorCodes: Int {
case AlreadyAccessing
case SchemeNotSupported
case TagMissingFromURL
case PathMissingFromURL
case NotFoundInBundle
case NotReadilyAvailable
}
static let errorDescriptions: [Int: String] = [
ErrorCodes.AlreadyAccessing.rawValue: "Already accessing",
ErrorCodes.SchemeNotSupported.rawValue: "URL scheme is not 'odr'",
ErrorCodes.TagMissingFromURL.rawValue: "Malformed ODR URL: tag missing",
ErrorCodes.PathMissingFromURL.rawValue: "Malformed ODR URL: path missing",
ErrorCodes.NotFoundInBundle.rawValue: "Path not found in bundle",
ErrorCodes.NotReadilyAvailable.rawValue: "Not readily available"
]
}
}
| mit | 012c29b8f12d7d993869a13ced7137a0 | 37.072165 | 146 | 0.561061 | 5.313669 | false | false | false | false |
renzifeng/ZFZhiHuDaily | ZFZhiHuDaily/ThemeList/View/ZFThemeListCell.swift | 1 | 1192 | //
// ZFThemeListCell.swift
// ZFZhiHuDaily
//
// Created by 任子丰 on 16/1/11.
// Copyright © 2016年 任子丰. All rights reserved.
//
import UIKit
import Kingfisher
class ZFThemeListCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var rightImageView: UIImageView!
@IBOutlet weak var imageWidthConstraint: NSLayoutConstraint!
var story : ZFThemeStories! {
didSet {
self.titleLabel.text = story.title
if story.images != nil {
rightImageView.kf_setImageWithURL(NSURL(string: story.images![0])!, placeholderImage: UIImage(named: "Image_Preview"))
imageWidthConstraint.constant = 80;
}else {
imageWidthConstraint.constant = 0;
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
dk_backgroundColorPicker = CELL_COLOR
titleLabel.dk_textColorPicker = CELL_TITLE
selectionStyle = .None
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | c7125dd1a00f44d41134a3fad01fc73e | 27.02381 | 134 | 0.637213 | 4.544402 | false | false | false | false |
einfallstoll/async-swift | Async-Test/Async_Test.swift | 2 | 4413 | //
// Async_Test.swift
// Async-Test
//
// Created by Fabio Poloni on 01.10.14.
//
//
import Cocoa
import XCTest
class Async_Test: XCTestCase {
func testEach() {
var expectation = self.expectationWithDescription("Async.each()")
var items = ["Item 1", "Item 2"]
var iteratorCount = 0
var finishedCount = 0
Async.each(items, iterator: { (item, asyncCallback) -> Void in
XCTAssertEqual(item, items[iteratorCount], "Item does not match")
XCTAssertLessThan(iteratorCount++, items.count, "Iterator was called too often")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
asyncCallback(error: nil)
}
}) { (error: String?) -> Void in
XCTAssertLessThan(finishedCount++, 1, "Finished was called too often")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testEachWithError() {
var expectation = self.expectationWithDescription("Async.each() with error")
var items = ["Item 1", "Item 2"]
var expectedError = "This is an error"
var iteratorCount = 0
var finishedCount = 0
Async.each(items , iterator: { (item, asyncCallback) -> Void in
XCTAssertEqual(item, items[iteratorCount], "Item does not match")
XCTAssertLessThan(iteratorCount++, items.count, "Iterator was called too often")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
asyncCallback(error: expectedError)
}
}) { (error: String?) -> Void in
XCTAssertLessThan(finishedCount++, 1, "Finished was called too often")
XCTAssertNotNil(error, "There was no error (and there should have been one)")
XCTAssertEqual(error!, expectedError, "Error does not match")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testEachSync() {
var expectation = self.expectationWithDescription("Async.eachSync()")
var items = ["Item 1", "Item 2"]
var iteratorCount = 0
var finishedCount = 0
Async.eachSeries(items, iterator: { (item, asyncCallback) -> Void in
XCTAssertEqual(item, items[iteratorCount], "Item does not match")
XCTAssertLessThan(iteratorCount++, items.count, "Iterator was called too often")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
asyncCallback(error: nil)
}
}) { (error: String?) -> Void in
XCTAssertLessThan(finishedCount++, 1, "Finished was called too often")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testEachSyncWithError() {
var expectation = self.expectationWithDescription("Async.eachSync() with error")
var items = ["Item 1", "Item 2"]
var expectedError = "This is an error"
var iteratorCount = 0
var finishedCount = 0
Async.eachSeries(items, iterator: { (item, asyncCallback) -> Void in
XCTAssertEqual(item, items[iteratorCount], "Item does not match")
XCTAssertLessThan(iteratorCount++, items.count, "Iterator was called too often")
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
asyncCallback(error: expectedError)
}
}) { (error: String?) -> Void in
XCTAssertLessThan(finishedCount++, 1, "Finished was called too often")
XCTAssertNotNil(error, "There was no error (and there should have been one)")
XCTAssertEqual(error!, expectedError, "Error does not match")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
}
| mit | b623c8d72066841ee1e996f7845ad8ac | 35.172131 | 105 | 0.563336 | 5.06659 | false | true | false | false |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Chapters/Document11.playgroundchapter/Pages/Exercise1.playgroundpage/Contents.swift | 1 | 2028 | //#-hidden-code
//
// Contents.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
//#-end-hidden-code
/*:
**Goal:** Initialize an instance of type `Expert` and solve the puzzle with the `turnLockUp()` method.
In this puzzle, there's a new element to deal with: a lock. To solve the puzzle, you’ll need to turn the lock, which raises a platform in front of an unreachable gem.
The character you've worked with up to now has certain abilities, like moving forward, collecting gems, and toggling switches. One ability your character doesn’t have is picking locks. You’ll need a new character—an expert—to do that. Because your expert won't change, you’ll [declare](glossary://declaration) it by using a [constant](glossary://constant), and then [initialize](glossary://initialization) it by assigning it the `Expert` [type](glossary://type).
* callout(Initializing an expert):
`let expert = Expert()`
1. steps: Initialize your new expert character. Don’t change the constant name, `expert`.
2. Move your expert around and give commands using dot notation.
3. Use the `turnLockUp()` [method](glossary://method) on the lock to reveal the path between the platforms.
*/
//#-hidden-code
playgroundPrologue()
typealias Character = Actor
//#-end-hidden-code
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, show, isOnOpenSwitch, if, func, for, while, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, Expert, Character, (, ), (), isOnClosedSwitch, let, ., =, <, >, ==, !=, +, -, isBlocked, true, false, isBlockedLeft, &&, ||, !, isBlockedRight, turnLockUp())
//#-editable-code Initialize your expert here
let expert = <#initialize#>
//#-end-editable-code
//#-hidden-code
world.place(expert, facing: east, at: Coordinate(column: 3, row: 3))
//#-end-hidden-code
//#-editable-code Enter the rest of your solution here
//#-end-editable-code
//#-hidden-code
playgroundEpilogue()
//#-end-hidden-code
| mit | 97bb1fb9e1654db97a371a954c4f700b | 46.952381 | 462 | 0.717478 | 3.988119 | false | false | false | false |
LockLight/Weibo_Demo | SinaWeibo/SinaWeibo/Tools/UIImage+draw.swift | 1 | 2409 | //
// UIImage+draw.swift
// weiboNine
//
// Created by HM09 on 17/4/2.
// Copyright © 2017年 itheima. All rights reserved.
//
import UIKit
extension UIImage {
//图片平铺
class func pureImage(color: UIColor = UIColor.white, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? {
//1. 开始图形上下文
UIGraphicsBeginImageContext(size)
//2. 设置颜色
color.setFill()
//3. 颜色填充
UIRectFill(CGRect(origin: CGPoint.zero, size: size))
//4. 从图形上下文获取图片
let image = UIGraphicsGetImageFromCurrentImageContext()
//5. 关闭图形上下文
UIGraphicsEndImageContext()
return image
}
//绘制圆角头像
func createCircleImage(color:UIColor = UIColor.white ,size:CGSize = CGSize.zero,callBack:@escaping (UIImage) -> ()){
DispatchQueue.global().async {
let rect = CGRect(origin: CGPoint.zero, size: size)
//开始图形上下文
UIGraphicsBeginImageContext(size)
//设置填充颜色
color.setFill()
UIRectFill(rect)
//绘制圆形
let path = UIBezierPath(ovalIn: rect)
path.addClip()
self.draw(in: rect)
//从上下文获取图像
let image = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()
DispatchQueue.main.async {
callBack(image!)
}
}
}
//根据当前上下文裁剪图片,以压缩大小
func resizeImage(color:UIColor = UIColor.white,size:CGSize = CGSize(width: 1, height: 1),callBack: @escaping (UIImage?) -> ()){
DispatchQueue.global().async {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContext(size)
color.setFill()
UIRectFill(rect)
self.draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
DispatchQueue.main.async {
callBack(image)
}
}
}
}
| mit | 9f589fc0e0131a938928817f7667b0cb | 25.86747 | 131 | 0.516592 | 5.068182 | false | false | false | false |
caxco93/peliculas | DemoWS/iPhone/Clases/Carrousel/GDCCarruselView.swift | 1 | 7526 | //
// GDCCarruselView.swift
// Carrusel
//
// Created by Benjamin Eyzaguirre on 10/13/16.
// Copyright © 2016 GDC Digital Cinema Network S.A.C. All rights reserved.
//
import UIKit
@objc protocol GDCCarruselViewDataSource{
func numeroDeCeldas(en carrusel : GDCCarruselView) -> Int
func carrusel(_ Carrusel: GDCCarruselView, celdaParaIndex index: Int) -> GDCCarruselViewCell
}
@objc protocol GDCCarruselViewDelegate{
@objc optional func carrusel(_ carrusel: GDCCarruselView, seleccionoCeldaEnIndex index: Int)
@objc optional func carrusel(_ carrusel: GDCCarruselView, tamanoParaIndex index: Int) -> CGSize
@objc optional func carrusel(_ carrusel: GDCCarruselView, tapeoCeldaEnIndex index: Int)
}
class GDCCarruselView: UIView {
var arrayCeldas = NSMutableArray()
var indexSeleccionado : Int = 0
var cantidadDeCeldas : Int = 0
weak open var delegate : GDCCarruselViewDelegate?
weak open var dataSoruce : GDCCarruselViewDataSource?
lazy var swipGestureAdelantar : UISwipeGestureRecognizer = {
let _swipGestureAdelantar = UISwipeGestureRecognizer()
_swipGestureAdelantar.direction = .right
_swipGestureAdelantar.addTarget(self, action: #selector(GDCCarruselView.adelantar))
return _swipGestureAdelantar
}()
lazy var swipGestureRetroceder : UISwipeGestureRecognizer = {
let _swipGestureRetroceder = UISwipeGestureRecognizer()
_swipGestureRetroceder.direction = .left
_swipGestureRetroceder.addTarget(self, action: #selector(GDCCarruselView.retroceder))
return _swipGestureRetroceder
}()
lazy var tapGestureSeleccionar : UITapGestureRecognizer = {
let _tapGestureSeleccionar = UITapGestureRecognizer()
_tapGestureSeleccionar.numberOfTapsRequired = 1
_tapGestureSeleccionar.numberOfTouchesRequired = 1
_tapGestureSeleccionar.addTarget(self, action: #selector(GDCCarruselView.seleccionar))
return _tapGestureSeleccionar
}()
func reloadData(){
self.arrayCeldas.enumerateObjects ({ (obj, idx, stop) in
let celda = obj as! GDCCarruselViewCell
celda.removeFromSuperview()
})
self.arrayCeldas.removeAllObjects()
self.dibujarCeldas()
}
func dibujarCeldas(){
self.cantidadDeCeldas = (self.dataSoruce?.numeroDeCeldas(en: self))!
if cantidadDeCeldas == 0 {
return
}
for i in 0...(self.cantidadDeCeldas > 4 ? 3 : self.cantidadDeCeldas - 1) {
let celda = self.dataSoruce?.carrusel(self, celdaParaIndex: i)
celda?.posicion = i
let tamano = self.delegate?.carrusel!(self, tamanoParaIndex: i)
celda?.anchoCelda = Int((tamano?.width)!)
celda?.altoCelda = Int((tamano?.height)!)
self.insertSubview(celda!, at: 0)
celda?.iniciarPintado()
self.arrayCeldas.add(celda)
}
self.delegate?.carrusel!(self, seleccionoCeldaEnIndex: self.indexSeleccionado)
}
override func draw(_ rect: CGRect) {
self.addGestureRecognizer(self.swipGestureAdelantar)
self.addGestureRecognizer(self.swipGestureRetroceder)
self.addGestureRecognizer(self.tapGestureSeleccionar)
self.dibujarCeldas()
}
func adelantar(){
if self.indexSeleccionado + 1 == self.cantidadDeCeldas {
return
}
if self.indexSeleccionado < self.cantidadDeCeldas - 4 {
let nuevaCelda : GDCCarruselViewCell = (self.dataSoruce?.carrusel(self, celdaParaIndex: self.indexSeleccionado + 4))!
nuevaCelda.posicion = 4
let tamano = self.delegate?.carrusel!(self, tamanoParaIndex: self.indexSeleccionado + 4)
nuevaCelda.anchoCelda = Int((tamano?.width)!)
nuevaCelda.altoCelda = Int((tamano?.height)!)
self.insertSubview(nuevaCelda, at: 0)
nuevaCelda.iniciarPintado()
self.arrayCeldas.add(nuevaCelda)
}
self.indexSeleccionado = self.indexSeleccionado + 1
self.delegate?.carrusel!(self, seleccionoCeldaEnIndex: self.indexSeleccionado)
self.arrayCeldas.enumerateObjects ({ (obj, idx, stop) in
let celda = obj as! GDCCarruselViewCell
celda.posicion = celda.posicion! - 1
if celda.posicion == -1 {
celda.animarCambioCeldaDerechaEfectoSolapa(conCeldaCentral: self.arrayCeldas[idx + 1] as! GDCCarruselViewCell, conCompletion: { (celdaCarrusel) in
})
}else{
celda.animarCambioCeldaDerecha(conCompletion: { (celdaCarrusel) in
if celdaCarrusel.posicion == -4 {
celdaCarrusel.removeFromSuperview()
self.arrayCeldas.removeObject(at: 0)
stop.initialize(to: true)
}
})
}
})
}
func seleccionar(){
self.delegate?.carrusel!(self, tapeoCeldaEnIndex: self.indexSeleccionado)
}
func retroceder(){
if self.indexSeleccionado == 0 {
return
}
if self.indexSeleccionado > 3 {
let nuevaCelda : GDCCarruselViewCell = (self.dataSoruce?.carrusel(self, celdaParaIndex: self.indexSeleccionado - 4))!
nuevaCelda.posicion = -4
let tamano = self.delegate?.carrusel!(self, tamanoParaIndex: self.indexSeleccionado - 4)
nuevaCelda.anchoCelda = Int((tamano?.width)!)
nuevaCelda.altoCelda = Int((tamano?.height)!)
self.insertSubview(nuevaCelda, at: 0)
nuevaCelda.iniciarPintado()
self.arrayCeldas.insert(nuevaCelda, at: 0)
}
self.indexSeleccionado = self.indexSeleccionado - 1
self.delegate?.carrusel!(self, seleccionoCeldaEnIndex: self.indexSeleccionado)
self.arrayCeldas.enumerateObjects ({ (obj, idx, stop) in
let celda = obj as! GDCCarruselViewCell
celda.posicion = celda.posicion! + 1
if celda.posicion == 1 {
celda.animarCambioCeldaIzquierdaEfectoSolapa(conCeldaCentral: self.arrayCeldas[idx - 1] as! GDCCarruselViewCell, conCompletion: { (celdaCarrusel) in
})
}else{
celda.animarCambioCeldaDerecha(conCompletion: { (celdaCarrusel) in
if celdaCarrusel.posicion == 4 {
celdaCarrusel.removeFromSuperview()
self.arrayCeldas.removeLastObject()
stop.initialize(to: true)
}
})
}
})
}
}
| mit | ca9302fa7320f4c5150429777ece4f5b | 30.354167 | 164 | 0.564784 | 4.026217 | false | false | false | false |
aizcheryz/HZTableView | HZTableViewSample/HZTableViewSample/HZMaterialTableView/HZMaterialColor.swift | 2 | 28725 | //
// HZMaterialColor.swift
// HZMaterialDesign
//
// Created by Moch Fariz Al Hazmi on 12/31/15.
// Copyright © 2015 alhazme. All rights reserved.
//
import Foundation
import UIKit
public struct HZMaterialColor {
// clear
public static let clear: UIColor = UIColor.clearColor()
// white
public static let white: UIColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
// black
public static let black: UIColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1)
// red
public struct red {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 235/255, blue: 238/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 225/255, green: 205/255, blue: 210/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 239/255, green: 154/255, blue: 254/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 229/255, green: 115/255, blue: 115/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 229/255, green: 83/255, blue: 80/255, alpha: 1)
public static let base: UIColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 229/255, green: 57/255, blue: 53/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 211/255, green: 47/255, blue: 47/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 198/255, green: 40/255, blue: 40/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 183/255, green: 28/255, blue: 28/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 138/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 82/255, blue: 82/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 23/255, blue: 68/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 213/255, green: 0/255, blue: 0/255, alpha: 1)
}
// pink
public struct pink {
public static let lighten5: UIColor = UIColor(red: 252/255, green: 228/255, blue: 236/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 248/255, green: 107/255, blue: 208/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 244/255, green: 143/255, blue: 177/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 240/255, green: 98/255, blue: 146/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 236/255, green: 64/255, blue: 122/255, alpha: 1)
public static let base: UIColor = UIColor(red: 233/255, green: 30/255, blue: 99/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 216/255, green: 27/255, blue: 96/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 194/255, green: 24/255, blue: 191/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 173/255, green: 20/255, blue: 87/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 136/255, green: 14/255, blue: 79/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 128/255, blue: 171/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 64/255, blue: 129/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 245/255, green: 0/255, blue: 87/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 197/255, green: 17/255, blue: 98/255, alpha: 1)
}
// purple
public struct purple {
public static let lighten5: UIColor = UIColor(red: 243/255, green: 229/255, blue: 245/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 225/255, green: 190/255, blue: 231/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 206/255, green: 147/255, blue: 216/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 186/255, green: 104/255, blue: 200/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 171/255, green: 71/255, blue: 188/255, alpha: 1)
public static let base: UIColor = UIColor(red: 156/255, green: 39/255, blue: 176/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 142/255, green: 36/255, blue: 170/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 123/255, green: 31/255, blue: 162/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 106/255, green: 27/255, blue: 154/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 74/255, green: 20/255, blue: 140/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 234/255, green: 128/255, blue: 252/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 224/255, green: 64/255, blue: 251/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 213/255, green: 0/255, blue: 249/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 170/255, green: 0/255, blue: 255/255, alpha: 1)
}
// deepPurple
public struct deepPurple {
public static let lighten5: UIColor = UIColor(red: 237/255, green: 231/255, blue: 246/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 209/255, green: 196/255, blue: 233/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 179/255, green: 157/255, blue: 219/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 149/255, green: 117/255, blue: 205/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 126/255, green: 87/255, blue: 194/255, alpha: 1)
public static let base: UIColor = UIColor(red: 103/255, green: 58/255, blue: 183/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 94/255, green: 53/255, blue: 177/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 81/255, green: 45/255, blue: 168/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 69/255, green: 39/255, blue: 160/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 49/255, green: 27/255, blue: 146/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 179/255, green: 136/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 124/255, green: 77/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 101/255, green: 31/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 98/255, green: 0/255, blue: 234/255, alpha: 1)
}
// indigo
public struct indigo {
public static let lighten5: UIColor = UIColor(red: 232/255, green: 234/255, blue: 246/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 197/255, green: 202/255, blue: 233/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 159/255, green: 168/255, blue: 218/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 121/255, green: 134/255, blue: 203/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 92/255, green: 107/255, blue: 192/255, alpha: 1)
public static let base: UIColor = UIColor(red: 63/255, green: 81/255, blue: 181/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 57/255, green: 73/255, blue: 171/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 48/255, green: 63/255, blue: 159/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 40/255, green: 53/255, blue: 147/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 26/255, green: 35/255, blue: 126/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 140/255, green: 158/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 83/255, green: 109/255, blue: 254/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 61/255, green: 90/255, blue: 254/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 48/255, green: 79/255, blue: 254/255, alpha: 1)
}
// blue
public struct blue {
public static let lighten5: UIColor = UIColor(red: 227/255, green: 242/255, blue: 253/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 187/255, green: 222/255, blue: 251/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 144/255, green: 202/255, blue: 249/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 100/255, green: 181/255, blue: 246/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 66/255, green: 165/255, blue: 245/255, alpha: 1)
public static let base: UIColor = UIColor(red: 33/255, green: 150/255, blue: 243/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 30/255, green: 136/255, blue: 229/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 25/255, green: 118/255, blue: 210/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 21/255, green: 101/255, blue: 192/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 13/255, green: 71/255, blue: 161/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 130/255, green: 177/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 68/255, green: 138/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 41/255, green: 121/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 41/255, green: 98/255, blue: 255/255, alpha: 1)
}
// light blue
public struct lightBlue {
public static let lighten5: UIColor = UIColor(red: 225/255, green: 245/255, blue: 254/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 179/255, green: 229/255, blue: 252/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 129/255, green: 212/255, blue: 250/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 79/255, green: 195/255, blue: 247/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 41/255, green: 182/255, blue: 246/255, alpha: 1)
public static let base: UIColor = UIColor(red: 3/255, green: 169/255, blue: 244/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 3/255, green: 155/255, blue: 229/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 2/255, green: 136/255, blue: 209/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 2/255, green: 119/255, blue: 189/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 1/255, green: 87/255, blue: 155/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 128/255, green: 216/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 64/255, green: 196/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 176/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 145/255, blue: 234/255, alpha: 1)
}
// cyan
public struct cyan {
public static let lighten5: UIColor = UIColor(red: 224/255, green: 247/255, blue: 250/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 1178/255, green: 235/255, blue: 242/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 128/255, green: 222/255, blue: 2343/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 77/255, green: 208/255, blue: 225/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 38/255, green: 198/255, blue: 218/255, alpha: 1)
public static let base: UIColor = UIColor(red: 0/255, green: 188/255, blue: 212/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 0/255, green: 172/255, blue: 193/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 0/255, green: 151/255, blue: 167/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 0/255, green: 131/255, blue: 143/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 0/255, green: 96/255, blue: 100/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 132/255, green: 255/255, blue: 255/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 24/255, green: 255/255, blue: 255/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 229/255, blue: 255/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 184/255, blue: 212/255, alpha: 1)
}
// teal
public struct teal {
public static let lighten5: UIColor = UIColor(red: 224/255, green: 242/255, blue: 241/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 178/255, green: 223/255, blue: 219/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 128/255, green: 203/255, blue: 196/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 77/255, green: 182/255, blue: 172/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 38/255, green: 166/255, blue: 154/255, alpha: 1)
public static let base: UIColor = UIColor(red: 0/255, green: 150/255, blue: 136/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 0/255, green: 137/255, blue: 123/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 0/255, green: 121/255, blue: 107/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 0/255, green: 105/255, blue: 92/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 0/255, green: 77/255, blue: 64/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 167/255, green: 255/255, blue: 235/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 100/255, green: 255/255, blue: 218/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 29/255, green: 133/255, blue: 182/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 191/255, blue: 165/255, alpha: 1)
}
// green
public struct green {
public static let lighten5: UIColor = UIColor(red: 232/255, green: 245/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 200/255, green: 230/255, blue: 201/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 165/255, green: 214/255, blue: 167/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 129/255, green: 199/255, blue: 132/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 102/255, green: 187/255, blue: 106/255, alpha: 1)
public static let base: UIColor = UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 67/255, green: 160/255, blue: 71/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 56/255, green: 142/255, blue: 60/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 46/255, green: 125/255, blue: 50/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 27/255, green: 94/255, blue: 32/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 185/255, green: 246/255, blue: 202/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 105/255, green: 240/255, blue: 174/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 0/255, green: 230/255, blue: 118/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 0/255, green: 200/255, blue: 83/255, alpha: 1)
}
// light green
public struct lightGreen {
public static let lighten5: UIColor = UIColor(red: 241/255, green: 248/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 220/255, green: 237/255, blue: 200/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 197/255, green: 225/255, blue: 165/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 174/255, green: 213/255, blue: 129/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 156/255, green: 204/255, blue: 101/255, alpha: 1)
public static let base: UIColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 124/255, green: 179/255, blue: 66/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 104/255, green: 159/255, blue: 56/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 85/255, green: 139/255, blue: 47/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 51/255, green: 105/255, blue: 30/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 204/255, green: 255/255, blue: 144/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 178/255, green: 255/255, blue: 89/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 118/255, green: 255/255, blue: 3/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 100/255, green: 221/255, blue: 23/255, alpha: 1)
}
// lime
public struct lime {
public static let lighten5: UIColor = UIColor(red: 249/255, green: 251/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 240/255, green: 244/255, blue: 195/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 230/255, green: 238/255, blue: 156/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 220/255, green: 231/255, blue: 117/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 212/255, green: 225/255, blue: 87/255, alpha: 1)
public static let base: UIColor = UIColor(red: 205/255, green: 220/255, blue: 57/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 192/255, green: 202/255, blue: 51/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 175/255, green: 180/255, blue: 43/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 158/255, green: 157/255, blue: 36/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 130/255, green: 119/255, blue: 23/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 244/255, green: 255/255, blue: 129/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 238/255, green: 255/255, blue: 65/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 198/255, green: 255/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 174/255, green: 234/255, blue: 0/255, alpha: 1)
}
// yellow
public struct yellow {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 253/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 249/255, blue: 196/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 245/255, blue: 157/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 241/255, blue: 118/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 238/255, blue: 88/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 235/255, blue: 59/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 253/255, green: 216/255, blue: 53/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 251/255, green: 192/255, blue: 45/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 249/255, green: 168/255, blue: 37/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 245/255, green: 127/255, blue: 23/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 255/255, blue: 141/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 255/255, blue: 0/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 234/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 214/255, blue: 0/255, alpha: 1)
}
// amber
public struct amber {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 248/255, blue: 225/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 236/255, blue: 179/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 224/255, blue: 130/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 213/255, blue: 79/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 202/255, blue: 40/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 193/255, blue: 7/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 255/255, green: 179/255, blue: 0/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 255/255, green: 160/255, blue: 0/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 255/255, green: 143/255, blue: 0/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 255/255, green: 111/255, blue: 0/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 229/255, blue: 127/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 215/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 196/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 171/255, blue: 0/255, alpha: 1)
}
// orange
public struct orange {
public static let lighten5: UIColor = UIColor(red: 255/255, green: 243/255, blue: 224/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 224/255, blue: 178/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 204/255, blue: 128/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 183/255, blue: 77/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 167/255, blue: 38/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 152/255, blue: 0/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 251/255, green: 140/255, blue: 0/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 245/255, green: 124/255, blue: 0/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 239/255, green: 108/255, blue: 0/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 230/255, green: 81/255, blue: 0/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 209/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 171/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 145/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 255/255, green: 109/255, blue: 0/255, alpha: 1)
}
// deep orange
public struct deepOrange {
public static let lighten5: UIColor = UIColor(red: 251/255, green: 233/255, blue: 231/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 255/255, green: 204/255, blue: 188/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 255/255, green: 171/255, blue: 145/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 255/255, green: 138/255, blue: 101/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 255/255, green: 112/255, blue: 67/255, alpha: 1)
public static let base: UIColor = UIColor(red: 255/255, green: 87/255, blue: 34/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 244/255, green: 81/255, blue: 30/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 230/255, green: 74/255, blue: 25/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 216/255, green: 67/255, blue: 21/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 191/255, green: 54/255, blue: 12/255, alpha: 1)
public static let accent1: UIColor = UIColor(red: 255/255, green: 158/255, blue: 128/255, alpha: 1)
public static let accent2: UIColor = UIColor(red: 255/255, green: 110/255, blue: 64/255, alpha: 1)
public static let accent3: UIColor = UIColor(red: 255/255, green: 61/255, blue: 0/255, alpha: 1)
public static let accent4: UIColor = UIColor(red: 221/255, green: 44/255, blue: 0/255, alpha: 1)
}
// brown
public struct brown {
public static let lighten5: UIColor = UIColor(red: 239/255, green: 235/255, blue: 233/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 215/255, green: 204/255, blue: 200/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 188/255, green: 170/255, blue: 164/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 161/255, green: 136/255, blue: 127/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 141/255, green: 110/255, blue: 99/255, alpha: 1)
public static let base: UIColor = UIColor(red: 121/255, green: 85/255, blue: 72/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 109/255, green: 76/255, blue: 65/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 93/255, green: 64/255, blue: 55/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 78/255, green: 52/255, blue: 46/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 62/255, green: 39/255, blue: 35/255, alpha: 1)
}
// grey
public struct grey {
public static let lighten5: UIColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 189/255, green: 189/255, blue: 189/255, alpha: 1)
public static let base: UIColor = UIColor(red: 158/255, green: 158/255, blue: 158/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 117/255, green: 117/255, blue: 117/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 97/255, green: 97/255, blue: 97/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 66/255, green: 66/255, blue: 66/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 33/255, green: 33/255, blue: 33/255, alpha: 1)
}
// blue grey
public struct blueGrey {
public static let lighten5: UIColor = UIColor(red: 236/255, green: 239/255, blue: 241/255, alpha: 1)
public static let lighten4: UIColor = UIColor(red: 207/255, green: 216/255, blue: 220/255, alpha: 1)
public static let lighten3: UIColor = UIColor(red: 176/255, green: 190/255, blue: 197/255, alpha: 1)
public static let lighten2: UIColor = UIColor(red: 144/255, green: 164/255, blue: 174/255, alpha: 1)
public static let lighten1: UIColor = UIColor(red: 120/255, green: 144/255, blue: 156/255, alpha: 1)
public static let base: UIColor = UIColor(red: 96/255, green: 125/255, blue: 139/255, alpha: 1)
public static let darken1: UIColor = UIColor(red: 84/255, green: 110/255, blue: 122/255, alpha: 1)
public static let darken2: UIColor = UIColor(red: 69/255, green: 90/255, blue: 100/255, alpha: 1)
public static let darken3: UIColor = UIColor(red: 55/255, green: 71/255, blue: 79/255, alpha: 1)
public static let darken4: UIColor = UIColor(red: 38/255, green: 50/255, blue: 56/255, alpha: 1)
}
} | mit | d27f304b40c99889781f2d94f1721fbb | 80.144068 | 109 | 0.656385 | 3.295927 | false | false | false | false |
iossocket/SerialHttpRequest | APIManager/Request.swift | 1 | 1124 | //
// Request.swift
// SerialHttpRequest
//
// Created by Xueliang Zhu on 6/23/16.
// Copyright © 2016 kotlinchina. All rights reserved.
//
import UIKit
enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
func request(_ url: String, method: Method, parameters: [String: Any]? = nil,
encoding: ParameterEncoding = .url, headers: [String: String]? = nil) -> URLRequest? {
let request = requestWithHeader(url, method: method, headers: headers)
guard let _request = request else { return nil }
let encodedRequest = encoding.encode(_request, parameters: parameters)
return encodedRequest
}
func requestWithHeader(_ url: String, method: Method, headers: [String: String]? = nil) -> URLRequest? {
guard let url = URL(string: url) else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
if let headers = headers {
for (headerField, headerValue) in headers {
request.setValue(headerValue, forHTTPHeaderField: headerField)
}
}
return request
}
| mit | 4838fbf3d5d6779029658c5213db19d4 | 29.351351 | 104 | 0.661621 | 4.09854 | false | false | false | false |
qds-hoi/suracare | suracare/suracare/App/ViewControllers/HomeViewController/rSHomeViewController.swift | 1 | 2768 | //
// rSHomeViewController.swift
// suracare
//
// Created by hoi on 8/16/16.
// Copyright © 2016 Sugar Rain. All rights reserved.
//
import UIKit
class rSHomeViewController: rSBaseViewController {
lazy var layoutLoader: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 1.0
layout.minimumInteritemSpacing = 1.0
// layout.itemSize = CGSize(width: self.talentinCollectionView.bounds.size.width/2 , height: self.talentinCollectionView.bounds.size.height/2.5)
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
return layout
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
func registerDelegateCollectionView() {
// self.talentinCollectionView.delegate = self
// self.talentinCollectionView.dataSource = self
// self.talentinCollectionView.collectionViewLayout = self.layoutLoader
// self.talentinCollectionView.registerNib(TAHomeCollectionViewCell.nib, forCellWithReuseIdentifier: TAHomeCollectionViewCell.nibName)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
// func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// let cell = collectionView.dequeueReusableCellWithReuseIdentifier(TAHomeCollectionViewCell.nibName, forIndexPath: indexPath) as! TAHomeCollectionViewCell
// return cell
// }
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
//device screen size
let width = (collectionView.bounds.size.width/2) - 1
let height = collectionView.bounds.size.height/2.2
//calculation of cell size
return CGSize(width: width , height: height)
}
}
| mit | 8378faec8ce0b0554ab4bcefe0bc6e85 | 35.407895 | 162 | 0.697145 | 5.404297 | false | false | false | false |
redfatty/SinaWeibo | SinaWeibo/SinaWeibo/Main/Visitor/VisitorView.swift | 1 | 1350 | //
// VisitorView.swift
// SinaWeibo
//
// Created by huangjiong on 16/10/1.
// Copyright © 2016年 huangjiong. All rights reserved.
//
import UIKit
class VisitorView: UIView {
@IBOutlet weak var rotationView: UIImageView!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var registerBtn: UIButton!
@IBOutlet weak var loginBtn: UIButton!
class func loadNib() -> VisitorView {
return NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).last as! VisitorView
}
//MARK: -设置信息
func setupInfo(inconImg iconImg: UIImage?, tipTitle: String) {
iconView.image = iconImg
tipLabel.text = tipTitle
rotationView.hidden = true
}
//MARK: -添加旋转动画
func addRotationAnimation() {
let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnim.fromValue = 0
rotationAnim.toValue = 2 * M_PI
rotationAnim.repeatCount = MAXFLOAT//一直循环
rotationAnim.duration = 5
rotationAnim.removedOnCompletion = false//不让系统移除
rotationView.layer.addAnimation(rotationAnim, forKey: "rotationAnim")
}
deinit {
rotationView.layer.removeAnimationForKey("rotationAnim")
}
}
| apache-2.0 | a9e97153add785766a6a05ec8c003794 | 27.413043 | 111 | 0.664116 | 4.476027 | false | false | false | false |
xwu/swift | test/Sanitizers/tsan/async_let_fibonacci.swift | 1 | 1419 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library -sanitize=thread)
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// REQUIRES: tsan_runtime
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// rdar://83246843 This tet is failing non-deterministically in CI.
// REQUIRES: rdar83246843
func fib(_ n: Int) -> Int {
var first = 0
var second = 1
for _ in 0..<n {
let temp = first
first = second
second = temp + first
}
return first
}
@available(SwiftStdlib 5.5, *)
func asyncFib(_ n: Int) async -> Int {
if n == 0 || n == 1 {
return n
}
async let first = await asyncFib(n-2)
async let second = await asyncFib(n-1)
// Sleep a random amount of time waiting on the result producing a result.
await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000)
let result = await first + second
// Sleep a random amount of time before producing a result.
await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000)
return result
}
@available(SwiftStdlib 5.5, *)
func runFibonacci(_ n: Int) async {
let result = await asyncFib(n)
print()
print("Async fib = \(result), sequential fib = \(fib(n))")
assert(result == fib(n))
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await runFibonacci(10)
}
}
| apache-2.0 | ed58460966d56373636076755fbe0454 | 22.65 | 131 | 0.669486 | 3.411058 | false | false | false | false |
bestwpw/RxSwift | RxTests/RxSwiftTests/TestImplementations/Schedulers/VirtualTimeSchedulerBase.swift | 2 | 4508 | //
// VirtualTimeSchedulerBase.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
protocol ScheduledItemProtocol : Cancelable {
var time: Int {
get
}
func invoke()
}
class ScheduledItem<T> : ScheduledItemProtocol {
typealias Action = T -> Disposable
let action: Action
let state: T
let time: Int
var disposed: Bool {
get {
return disposable.disposed
}
}
var disposable = SingleAssignmentDisposable()
init(action: Action, state: T, time: Int) {
self.action = action
self.state = state
self.time = time
}
func invoke() {
self.disposable.disposable = action(state)
}
func dispose() {
self.disposable.dispose()
}
}
class VirtualTimeSchedulerBase : Scheduler, CustomStringConvertible {
typealias TimeInterval = Int
typealias Time = Int
var clock : Time
var enabled : Bool
var now: Time {
get {
return self.clock
}
}
var description: String {
get {
return self.schedulerQueue.description
}
}
private var schedulerQueue : [ScheduledItemProtocol] = []
init(initialClock: Time) {
self.clock = initialClock
self.enabled = false
}
func schedule<StateType>(state: StateType, action: StateType -> Disposable) -> Disposable {
return self.scheduleRelative(state, dueTime: 0) { a in
return action(a)
}
}
func scheduleRelative<StateType>(state: StateType, dueTime: Int, action: StateType -> Disposable) -> Disposable {
return schedule(state, time: now + dueTime, action: action)
}
func schedule<StateType>(state: StateType, time: Int, action: StateType -> Disposable) -> Disposable {
let compositeDisposable = CompositeDisposable()
let scheduleTime: Int
if time <= self.now {
scheduleTime = self.now + 1
}
else {
scheduleTime = time
}
let item = ScheduledItem(action: action, state: state, time: scheduleTime)
schedulerQueue.append(item)
compositeDisposable.addDisposable(item)
return compositeDisposable
}
func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable {
let compositeDisposable = CompositeDisposable()
let scheduleTime: Int
if startAfter <= 0 {
scheduleTime = self.now + 1
}
else {
scheduleTime = self.now + startAfter
}
let item = ScheduledItem(action: { [unowned self] state in
if compositeDisposable.disposed {
return NopDisposable.instance
}
let nextState = action(state)
return self.schedulePeriodic(nextState, startAfter: period, period: period, action: action)
}, state: state, time: scheduleTime)
schedulerQueue.append(item)
compositeDisposable.addDisposable(item)
return compositeDisposable
}
func start() {
if !enabled {
enabled = true
repeat {
if let next = getNext() {
if next.disposed {
continue
}
if next.time > self.now {
self.clock = next.time
}
next.invoke()
}
else {
enabled = false;
}
} while enabled
}
}
func getNext() -> ScheduledItemProtocol? {
var minDate = Time.max
var minElement : ScheduledItemProtocol? = nil
var minIndex = -1
var index = 0
for item in self.schedulerQueue {
if item.time < minDate {
minDate = item.time
minElement = item
minIndex = index
}
index++
}
if minElement != nil {
self.schedulerQueue.removeAtIndex(minIndex)
}
return minElement
}
} | mit | 8a79c23d051807ae94968a3ce749f482 | 24.331461 | 152 | 0.531278 | 5.347568 | false | false | false | false |
Marguerite-iOS/Marguerite | Marguerite/ShuttleSystem+Location.swift | 1 | 3675 | //
// ShuttleSystem+Location.swift
// Marguerite
//
// Created by Andrew Finke on 1/26/16.
// Copyright © 2016 Andrew Finke. All rights reserved.
//
import MapKit
protocol ShuttleSystemLocationDelegate {
func locationAvailable()
func locationUnavailable()
}
extension ShuttleSystem: CoreLocationControllerDelegate {
// MARK: - Shuttle system attributes
/**
Gets the Stanford Region
- returns: The region.
*/
var region: MKCoordinateRegion {
return MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 37.432233, longitude: -122.171183), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
}
/**
Creates a CGPath representing the Marguerite parking lot for inactive shuttles
*/
func createParkingLotPath() {
let coordinates: [(latitude: CGFloat, longitude: CGFloat)] = [(37.431005, -122.182307), (37.430743, -122.182835), (37.430777, -122.184055), (37.431262, -122.183943), (37.431646, -122.183562), (37.432474, -122.181883), (37.432613, -122.181046), (37.432555, -122.180617), (37.431584, -122.180435), (37.431462, -122.181274)]
let mutablePath = CGPathCreateMutable()
for (index, coordinate) in coordinates.enumerate() {
if index == 0 {
CGPathMoveToPoint(mutablePath, nil, coordinate.latitude, coordinate.longitude)
} else {
CGPathAddLineToPoint(mutablePath, nil, coordinate.latitude, coordinate.longitude)
}
}
parkingLotPath = mutablePath
}
/**
If shuttle coordinates in the main parking lot, then the shuttle is inactive
*/
func coordinatesInParkingLot(latitude: Double, _ longitude: Double) -> Bool {
return CGPathContainsPoint(parkingLotPath, nil, CGPointMake(CGFloat(latitude), CGFloat(longitude)), false)
}
// MARK: - CoreLocationControllerDelegate
func locationAuthorizationStatusChanged(nowEnabled: Bool) {
if nowEnabled {
locationController.refreshLocation()
locationDelegate?.locationAvailable()
} else {
locationDelegate?.locationUnavailable()
}
}
func locationUpdate(location: CLLocation) {
closestStops = getClosestStops(25, location: location)
locationDelegate?.locationAvailable()
}
func locationError(error: NSError) {
print("GPS location error: \(error.localizedDescription)")
locationDelegate?.locationUnavailable()
}
// MARK: - Other
/**
Get a list of a certain number of closest stops to a location, or the
number of stops, whichever is smaller. Calling this function also sets
the "milesAway" variable for all of the stops returned.
- parameter numStops: The number of closest stops to get.
- parameter location: The location to find closest stops near.
- returns: The list of closest stops to the provided location.
*/
private func getClosestStops(numStops: Int, location: CLLocation) -> [ShuttleStop] {
let allStops = Stop.getAllStops()
let n = min(numStops, allStops.count)
var stopsSortedByDistance: [ShuttleStop] = stops.sort { (first, second) -> Bool in
first.distance = first.location?.distanceFromLocation(location)
second.distance = second.location?.distanceFromLocation(location)
return first.distance < second.distance
}
guard stopsSortedByDistance.count > 0 else {
return []
}
return [ShuttleStop](stopsSortedByDistance[0...n-1])
}
} | mit | 0a76aa517a03143925b19a9a46d00f06 | 35.386139 | 329 | 0.649973 | 4.519065 | false | false | false | false |
kingiol/IBDesignableDemo | IBDesignableDemo/OverCustomizableView.swift | 1 | 647 | //
// OverCustomizableView.swift
// IBDesignableDemo
//
// Created by Kingiol on 14-6-11.
// Copyright (c) 2014年 Kingiol. All rights reserved.
//
import UIKit
class OverCustomizableView: UIView {
@IBInspectable var integer: Int = 0
@IBInspectable var float: CGFloat = 0
@IBInspectable var double: Double = 0
@IBInspectable var point: CGPoint = CGPointZero
@IBInspectable var size: CGSize = CGSizeZero
@IBInspectable var customFrame: CGRect = CGRectZero
@IBInspectable var color: UIColor = UIColor.clearColor()
@IBInspectable var string: String = "we ❤ Swift"
@IBInspectable var bool: Bool = false
}
| mit | dd9e3aa58c87d7ffe51ce7d289b5b27a | 26.956522 | 60 | 0.710731 | 4.175325 | false | false | false | false |
Faryn/CycleMaps | Pods/Cache/Source/Shared/Configuration/DiskConfig.swift | 4 | 1321 | import Foundation
public struct DiskConfig {
/// The name of disk storage, this will be used as folder name within directory
public let name: String
/// Expiry date that will be applied by default for every added object
/// if it's not overridden in the add(key: object: expiry: completion:) method
public let expiry: Expiry
/// Maximum size of the disk cache storage (in bytes)
public let maxSize: UInt
/// A folder to store the disk cache contents. Defaults to a prefixed directory in Caches if nil
public let directory: URL?
#if os(iOS) || os(tvOS)
/// Data protection is used to store files in an encrypted format on disk and to decrypt them on demand.
/// Support only on iOS and tvOS.
public let protectionType: FileProtectionType?
public init(name: String, expiry: Expiry = .never,
maxSize: UInt = 0, directory: URL? = nil,
protectionType: FileProtectionType? = nil) {
self.name = name
self.expiry = expiry
self.maxSize = maxSize
self.directory = directory
self.protectionType = protectionType
}
#else
public init(name: String, expiry: Expiry = .never,
maxSize: UInt = 0, directory: URL? = nil) {
self.name = name
self.expiry = expiry
self.maxSize = maxSize
self.directory = directory
}
#endif
}
| mit | 9f613256884165bfd7459033f6ee321f | 35.694444 | 106 | 0.68433 | 4.247588 | false | false | false | false |
DavidSanf0rd/FireRecord-1 | FireRecord/Source/Extensions/Storage/FirebaseModel+Storator.swift | 1 | 2263 | //
// FirebaseDataModel+Storator.swift
// FirebaseCommunity
//
// Created by David Sanford on 24/08/17.
//
import Foundation
import FirebaseCommunity
import HandyJSON
public extension Storator where Self: FirebaseModel {
func uploadFiles(completion: @escaping ([NameAndUrl?]) -> Void) {
let selfMirror = Mirror(reflecting: self)
var possibleUploads = [UploadOperation?]()
for (name, value) in selfMirror.children {
guard let name = name else { continue }
//This aditional cast to Anyobject is needed because of this swift bug: https://bugs.swift.org/browse/SR-3871
if let firebaseStorable = value as? AnyObject as? FirebaseStorable {
let uniqueId = NSUUID().uuidString
let storagePath = "FireRecord/\(Self.className)/\(Self.autoId)/\(name)-\(uniqueId)"
possibleUploads.append(firebaseStorable.buildUploadOperation(fileName: name, path: storagePath))
}
}
let uploads = possibleUploads.flatMap { $0 }
let operationQueue = UploadOperationQueue(operations: uploads)
operationQueue.startUploads { results in
completion(results)
}
}
internal mutating func deserializeStorablePaths(snapshot: DataSnapshot) {
let selfMirror = Mirror(reflecting: self)
let modelDictionary = snapshot.value as? NSDictionary
var storables = [String: Any]()
for (name, propertyValue) in selfMirror.children {
guard let name = name else { continue }
// Cast to OptionalProtocol because swift(4.0) still can't infer that FirebaseImage?.self is FirebaseStorable?.Type.
if let optionalProperty = propertyValue as? OptionalProtocol,
let propertyType = optionalProperty.wrappedType() as? FirebaseStorable.Type {
var firebaseStorable = propertyType.init()
firebaseStorable.path = modelDictionary?[name] as? String
storables[name] = firebaseStorable
}
}
JSONDeserializer.update(object: &self, from: storables)
}
}
| mit | 0473b3cdde6efda9cfffa9eed315c19f | 36.716667 | 128 | 0.615996 | 5.226328 | false | false | false | false |
algolia/algoliasearch-client-swift | Tests/AlgoliaSearchClientTests/Unit/DisjunctiveFacetingHelperTests.swift | 1 | 13691 | //
// DisjunctiveFacetingHelperTests.swift
//
//
// Created by Vladislav Fitc on 20/03/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class DisjunctiveFacetingHelperTests: XCTestCase {
func testBuildFilters() throws {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let disjunctiveFacets: Set<Attribute> = [
"color"
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: disjunctiveFacets)
XCTAssertEqual(helper.buildFilters(excluding: .none), """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("color":"blue" OR "color":"green" OR "color":"red") AND ("size":"m" AND "size":"s")
""")
XCTAssertEqual(helper.buildFilters(excluding: "popularity"), """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("color":"blue" OR "color":"green" OR "color":"red") AND ("size":"m" AND "size":"s")
""")
XCTAssertEqual(helper.buildFilters(excluding: "brand"), """
("color":"blue" OR "color":"green" OR "color":"red") AND ("size":"m" AND "size":"s")
""")
XCTAssertEqual(helper.buildFilters(excluding: "color"), """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("size":"m" AND "size":"s")
""")
XCTAssertEqual(helper.buildFilters(excluding: "size"), """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("color":"blue" OR "color":"green" OR "color":"red")
""")
}
func testAppliedDisjunctiveFacetValues() {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let disjunctiveFacets: Set<Attribute> = [
"color",
"brand"
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: disjunctiveFacets)
XCTAssertTrue(helper.appliedDisjunctiveFacetValues(for: "popularity").isEmpty)
XCTAssertTrue(helper.appliedDisjunctiveFacetValues(for: "size").isEmpty)
XCTAssertEqual(helper.appliedDisjunctiveFacetValues(for: "color"), ["red", "green", "blue"])
XCTAssertEqual(helper.appliedDisjunctiveFacetValues(for: "brand"), ["samsung", "sony", "apple"])
}
func testMakeQueriesNoDisjunctive() {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: [])
let queries = helper.makeQueries()
XCTAssertEqual(queries.count, 1)
XCTAssertEqual(queries.first?.filters, """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("color":"blue" AND "color":"green" AND "color":"red") AND ("size":"m" AND "size":"s")
""")
}
func testMakeQueriesDisjunctiveSingle() {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: ["color"])
let queries = helper.makeQueries()
XCTAssertEqual(queries.count, 2)
XCTAssertEqual(queries.first?.filters, """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("color":"blue" OR "color":"green" OR "color":"red") AND ("size":"m" AND "size":"s")
""")
XCTAssertEqual(queries.last?.facets, ["color"])
XCTAssertEqual(queries.last?.filters, """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("size":"m" AND "size":"s")
""")
}
func testMakeQueriesDisjunctiveDouble() {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let disjunctiveFacets: Set<Attribute> = [
"color",
"size"
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: disjunctiveFacets)
let queries = helper.makeQueries()
XCTAssertEqual(queries.count, 3)
XCTAssertEqual(queries.first?.filters, """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("color":"blue" OR "color":"green" OR "color":"red") AND ("size":"m" OR "size":"s")
""")
XCTAssertEqual(queries[1].facets, ["color"])
XCTAssertEqual(queries[1].filters, """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("size":"m" OR "size":"s")
""")
XCTAssertEqual(queries[2].facets, ["size"])
XCTAssertEqual(queries[2].filters, """
("brand":"apple" AND "brand":"samsung" AND "brand":"sony") AND ("color":"blue" OR "color":"green" OR "color":"red")
""")
}
func testMergeEmptyResponses() {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let disjunctiveFacets: Set<Attribute> = [
"color",
"size"
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: disjunctiveFacets)
XCTAssertThrowsError(try helper.mergeResponses([]))
}
func testMergeDisjunctiveSingle() throws {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let disjunctiveFacets: Set<Attribute> = [
"color"
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: disjunctiveFacets)
var mainResponse = SearchResponse()
mainResponse.facets = [
"size": [
Facet(value: "s", count: 5),
Facet(value: "m", count: 7),
],
"color": [
Facet(value: "red", count: 1),
Facet(value: "green", count: 2),
Facet(value: "blue", count: 3),
],
"brand": [
Facet(value: "samsung", count: 5),
Facet(value: "sony", count: 10),
Facet(value: "apple", count: 15),
],
]
var disjunctiveResponse = SearchResponse()
disjunctiveResponse.facets = [
"color": [
Facet(value: "red", count: 10),
Facet(value: "green", count: 20),
Facet(value: "blue", count: 30),
]
]
let response = try helper.mergeResponses([
mainResponse,
disjunctiveResponse,
])
XCTAssertEqual(response.facets, [
"size": [
Facet(value: "s", count: 5),
Facet(value: "m", count: 7),
],
"color": [
Facet(value: "red", count: 1),
Facet(value: "green", count: 2),
Facet(value: "blue", count: 3),
],
"brand": [
Facet(value: "samsung", count: 5),
Facet(value: "sony", count: 10),
Facet(value: "apple", count: 15),
],
])
XCTAssertEqual(response.disjunctiveFacets, ["color": [
Facet(value: "red", count: 10),
Facet(value: "green", count: 20),
Facet(value: "blue", count: 30),
]])
}
func testMergeDisjunctiveDouble() throws {
let refinements: [Attribute: [String]] = [
"size": ["m", "s"],
"color": ["blue", "green", "red"],
"brand": ["apple", "samsung", "sony"]
]
let disjunctiveFacets: Set<Attribute> = [
"color",
"size"
]
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: refinements,
disjunctiveFacets: disjunctiveFacets)
var mainResponse = SearchResponse()
mainResponse.facets = [
"size": [
Facet(value: "s", count: 5),
Facet(value: "m", count: 7),
],
"color": [
Facet(value: "red", count: 1),
Facet(value: "green", count: 2),
Facet(value: "blue", count: 3),
],
"brand": [
Facet(value: "samsung", count: 5),
Facet(value: "sony", count: 10),
Facet(value: "apple", count: 15),
],
]
var firstDisjunctiveResponse = SearchResponse()
firstDisjunctiveResponse.facets = [
"color": [
Facet(value: "red", count: 10),
Facet(value: "green", count: 20),
Facet(value: "blue", count: 30),
]
]
var secondDisjunctiveResponse = SearchResponse()
secondDisjunctiveResponse.facets = [
"size": [
Facet(value: "s", count: 3),
Facet(value: "m", count: 4),
]
]
let response = try helper.mergeResponses([
mainResponse,
firstDisjunctiveResponse,
secondDisjunctiveResponse,
])
XCTAssertEqual(response.facets, [
"size": [
Facet(value: "s", count: 5),
Facet(value: "m", count: 7),
],
"color": [
Facet(value: "red", count: 1),
Facet(value: "green", count: 2),
Facet(value: "blue", count: 3),
],
"brand": [
Facet(value: "samsung", count: 5),
Facet(value: "sony", count: 10),
Facet(value: "apple", count: 15),
],
])
XCTAssertEqual(response.disjunctiveFacets, [
"color": [
Facet(value: "red", count: 10),
Facet(value: "green", count: 20),
Facet(value: "blue", count: 30),
],
"size": [
Facet(value: "s", count: 3),
Facet(value: "m", count: 4),
],
])
}
func testMergeFacetStats() throws {
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: [:],
disjunctiveFacets: [])
var mainResponse = SearchResponse()
mainResponse.facetStats = [
"price": FacetStats(min: 5, max: 100, avg: 52.5, sum: 2400),
"target": FacetStats(min: 1, max: 10, avg: 5.5, sum: 43)
]
var firstDisjunctiveResponse = SearchResponse()
firstDisjunctiveResponse.facetStats = [
"price": FacetStats(min: 7, max: 103, avg: 55, sum: 3000),
"note": FacetStats(min: 1, max: 5, avg: 3, sum: 37)
]
var secondDisjunctiveResponse = SearchResponse()
secondDisjunctiveResponse.facetStats = [
"size": FacetStats(min: 20, max: 56, avg: 38, sum: 242)
]
let response = try helper.mergeResponses([
mainResponse,
firstDisjunctiveResponse,
secondDisjunctiveResponse,
])
XCTAssertEqual(response.facetStats?.count, 4)
assertEqual(response.facetStats?["price"], FacetStats(min: 7, max: 103, avg: 55, sum: 3000),
file: #filePath,
line: #line)
assertEqual(response.facetStats?["target"], FacetStats(min: 1, max: 10, avg: 5.5, sum: 43),
file: #filePath,
line: #line)
assertEqual(response.facetStats?["size"], FacetStats(min: 20, max: 56, avg: 38, sum: 242),
file: #filePath,
line: #line)
assertEqual(response.facetStats?["note"], FacetStats(min: 1, max: 5, avg: 3, sum: 37),
file: #filePath,
line: #line)
}
func assertEqual(_ lhs: FacetStats?, _ rhs: FacetStats?, file: StaticString = #filePath, line: UInt = #line) {
guard let lhs = lhs else {
XCTAssertNil(rhs, file: file, line: line)
return
}
guard let rhs = rhs else {
XCTAssertNil(lhs, file: file, line: line)
return
}
XCTAssertEqual(lhs.min, rhs.min, accuracy: 0.01, file: file, line: line)
XCTAssertEqual(lhs.max, rhs.max, accuracy: 0.01, file: file, line: line)
if let lAvg = lhs.avg, let rAvg = rhs.avg {
XCTAssertEqual(lAvg, rAvg, accuracy: 0.01, file: file, line: line)
} else {
XCTAssertEqual(lhs.avg, rhs.avg, file: file, line: line)
}
if let lSum = lhs.sum, let rSum = rhs.sum {
XCTAssertEqual(lSum, rSum, accuracy: 0.01, file: file, line: line)
} else {
XCTAssertEqual(lhs.sum, rhs.sum, file: file, line: line)
}
}
func testMergeExhaustiveFacetsCount() throws {
let helper = DisjunctiveFacetingHelper(query: Query(),
refinements: [:],
disjunctiveFacets: [])
var mainResponse = SearchResponse()
mainResponse.exhaustiveFacetsCount = true
var firstDisjunctiveResponse = SearchResponse()
firstDisjunctiveResponse.exhaustiveFacetsCount = true
var secondDisjunctiveResponse = SearchResponse()
secondDisjunctiveResponse.exhaustiveFacetsCount = false
var response = try helper.mergeResponses([
mainResponse,
firstDisjunctiveResponse,
secondDisjunctiveResponse,
])
XCTAssertFalse(response.exhaustiveFacetsCount!)
secondDisjunctiveResponse.exhaustiveFacetsCount = true
response = try helper.mergeResponses([
mainResponse,
firstDisjunctiveResponse,
secondDisjunctiveResponse,
])
XCTAssertTrue(response.exhaustiveFacetsCount!)
}
}
| mit | 43118551a8c74cf9c525d6295e3e0e44 | 34.468912 | 153 | 0.556716 | 3.893914 | false | false | false | false |
narner/AudioKit | AudioKit/macOS/AudioKit/User Interface/AKPresetLoaderView.swift | 1 | 11965 | //
// AKPresetLoaderView.swift
// AudioKit for macOS
//
// Created by Aurelius Prochazka on 7/30/16.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
public class AKPresetLoaderView: NSView {
// Default corner radius
static var standardCornerRadius: CGFloat = 3.0
var player: AKAudioPlayer?
var presetOuterPath = NSBezierPath()
var upOuterPath = NSBezierPath()
var downOuterPath = NSBezierPath()
var currentIndex = -1
var presets = [String]()
var callback: (String) -> Void
var isPresetLoaded = false
open var bgColor: AKColor? {
didSet {
needsDisplay = true
}
}
open var textColor: AKColor? {
didSet {
needsDisplay = true
}
}
open var borderColor: AKColor? {
didSet {
needsDisplay = true
}
}
open var borderWidth: CGFloat = 3.0 {
didSet {
needsDisplay = true
}
}
public init(presets: [String],
frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60),
callback: @escaping (String) -> Void) {
self.callback = callback
self.presets = presets
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func mouseDown(with theEvent: NSEvent) {
isPresetLoaded = false
let touchLocation = convert(theEvent.locationInWindow, from: nil)
if upOuterPath.contains(touchLocation) {
currentIndex -= 1
isPresetLoaded = true
}
if downOuterPath.contains(touchLocation) {
currentIndex += 1
isPresetLoaded = true
}
if currentIndex < 0 { currentIndex = presets.count - 1 }
if currentIndex >= presets.count { currentIndex = 0 }
if isPresetLoaded {
callback(presets[currentIndex])
needsDisplay = true
}
}
// Default background color per theme
var bgColorForTheme: AKColor {
if let bgColor = bgColor { return bgColor }
switch AKStylist.sharedInstance.theme {
case .basic: return AKColor(white: 0.8, alpha: 1.0)
case .midnight: return AKColor(white: 0.7, alpha: 1.0)
}
}
// Default border color per theme
var borderColorForTheme: AKColor {
if let borderColor = borderColor { return borderColor }
switch AKStylist.sharedInstance.theme {
case .basic: return AKColor(white: 0.3, alpha: 1.0).withAlphaComponent(0.8)
case .midnight: return AKColor.white.withAlphaComponent(0.8)
}
}
// Default text color per theme
var textColorForTheme: AKColor {
if let textColor = textColor { return textColor }
switch AKStylist.sharedInstance.theme {
case .basic: return AKColor(white: 0.3, alpha: 1.0)
case .midnight: return AKColor.white
}
}
func drawPresetLoader(presetName: String = "None", isPresetLoaded: Bool = false) {
//// General Declarations
let rect = self.bounds
let _ = unsafeBitCast(NSGraphicsContext.current?.graphicsPort, to: CGContext.self)
let cornerRadius: CGFloat = AKPresetLoaderView.standardCornerRadius
//// Color Declarations
let green = AKStylist.sharedInstance.colorForTrueValue
let red = AKStylist.sharedInstance.colorForFalseValue
let gray = bgColorForTheme
//// Variable Declarations
let expression: NSColor = isPresetLoaded ? green : red
//// background Drawing
let backgroundPath = NSBezierPath(rect: NSRect(x: borderWidth,
y: borderWidth,
width: rect.width - borderWidth * 2.0,
height: rect.height - borderWidth * 2.0))
gray.setFill()
backgroundPath.fill()
//// presetButton
//// presetOuter Drawing
presetOuterPath = NSBezierPath(rect: NSRect(x: borderWidth, y: borderWidth, width: rect.width * 0.25, height: rect.height - borderWidth * 2.0))
expression.setFill()
presetOuterPath.fill()
// presetButton border Path
let presetButtonBorderPath = NSBezierPath()
presetButtonBorderPath.move(to: NSPoint(x: rect.width * 0.25 + borderWidth, y: borderWidth))
presetButtonBorderPath.line(to: NSPoint(x: rect.width * 0.25 + borderWidth, y: rect.height - borderWidth))
borderColorForTheme.setStroke()
presetButtonBorderPath.lineWidth = borderWidth / 2.0
presetButtonBorderPath.stroke()
//// presetLabel Drawing
let presetLabelRect = NSRect(x: 0, y: 0, width: rect.width * 0.25, height: rect.height)
let presetLabelTextContent = NSString(string: "Preset")
let presetLabelStyle = NSMutableParagraphStyle()
presetLabelStyle.alignment = .center
let presetLabelFontAttributes = [NSAttributedStringKey.font: NSFont.boldSystemFont(ofSize: 24),
NSAttributedStringKey.foregroundColor: textColorForTheme,
NSAttributedStringKey.paragraphStyle: presetLabelStyle]
let presetLabelInset: CGRect = presetLabelRect.insetBy(dx: 10, dy: 0)
let presetLabelTextHeight: CGFloat = presetLabelTextContent.boundingRect(
with: NSSize(width: presetLabelInset.width, height: CGFloat.infinity),
options: NSString.DrawingOptions.usesLineFragmentOrigin,
attributes: presetLabelFontAttributes).size.height
let presetLabelTextRect: NSRect = NSRect(
x: presetLabelInset.minX,
y: presetLabelInset.minY + (presetLabelInset.height - presetLabelTextHeight) / 2,
width: presetLabelInset.width,
height: presetLabelTextHeight)
NSGraphicsContext.saveGraphicsState()
__NSRectClip(presetLabelInset)
presetLabelTextContent.draw(in: presetLabelTextRect.offsetBy(dx: 0, dy: 0),
withAttributes: presetLabelFontAttributes)
NSGraphicsContext.restoreGraphicsState()
//// upButton
//// upOuter Drawing
upOuterPath = NSBezierPath(rect: NSRect(x: rect.width * 0.9, y: rect.height * 0.5, width: rect.width * 0.07, height: rect.height * 0.5))
//// upInner Drawing
let upperArrowRect = NSRect(x: rect.width * 0.9, y: rect.height * 0.58, width: rect.width * 0.07, height: rect.height * 0.3)
let upInnerPath = NSBezierPath()
upInnerPath.move(to: NSPoint(x: upperArrowRect.minX + cornerRadius / 2.0, y: upperArrowRect.minY))
upInnerPath.line(to: NSPoint(x: upperArrowRect.maxX - cornerRadius / 2.0, y: upperArrowRect.minY))
upInnerPath.curve(to: NSPoint(x: upperArrowRect.maxX - cornerRadius / 2.0, y: upperArrowRect.minY + cornerRadius / 2.0), controlPoint1: NSPoint(x: upperArrowRect.maxX, y: upperArrowRect.minY), controlPoint2: NSPoint(x: upperArrowRect.maxX, y: upperArrowRect.minY))
upInnerPath.line(to: NSPoint(x: upperArrowRect.midX + cornerRadius / 2.0, y: upperArrowRect.maxY - cornerRadius / 2.0))
upInnerPath.curve(to: NSPoint(x: upperArrowRect.midX - cornerRadius / 2.0, y: upperArrowRect.maxY - cornerRadius / 2.0), controlPoint1: NSPoint(x: upperArrowRect.midX, y: upperArrowRect.maxY), controlPoint2: NSPoint(x: upperArrowRect.midX, y: upperArrowRect.maxY))
upInnerPath.line(to: NSPoint(x: upperArrowRect.minX + cornerRadius / 2.0, y: upperArrowRect.minY + cornerRadius / 2.0))
upInnerPath.curve(to: NSPoint(x: upperArrowRect.minX + cornerRadius / 2.0, y: upperArrowRect.minY), controlPoint1: NSPoint(x: upperArrowRect.minX, y: upperArrowRect.minY), controlPoint2: NSPoint(x: upperArrowRect.minX, y: upperArrowRect.minY))
textColorForTheme.setStroke()
upInnerPath.lineWidth = borderWidth
upInnerPath.stroke()
downOuterPath = NSBezierPath(rect: NSRect(x: rect.width * 0.9, y: 0, width: rect.width * 0.07, height: rect.height * 0.5))
//// downInner Drawing
let downArrowRect = NSRect(x: rect.width * 0.9, y: rect.height * 0.12, width: rect.width * 0.07, height: rect.height * 0.3)
let downInnerPath = NSBezierPath()
downInnerPath.move(to: NSPoint(x: downArrowRect.minX + cornerRadius / 2.0, y: downArrowRect.maxY))
downInnerPath.line(to: NSPoint(x: downArrowRect.maxX - cornerRadius / 2.0, y: downArrowRect.maxY))
downInnerPath.curve(to: NSPoint(x: downArrowRect.maxX - cornerRadius / 2.0, y: downArrowRect.maxY - cornerRadius / 2.0), controlPoint1: NSPoint(x: downArrowRect.maxX, y: downArrowRect.maxY), controlPoint2: NSPoint(x: downArrowRect.maxX, y: downArrowRect.maxY))
downInnerPath.line(to: NSPoint(x: downArrowRect.midX + cornerRadius / 2.0, y: downArrowRect.minY + cornerRadius / 2.0))
downInnerPath.curve(to: NSPoint(x: downArrowRect.midX - cornerRadius / 2.0, y: downArrowRect.minY + cornerRadius / 2.0), controlPoint1: NSPoint(x: downArrowRect.midX, y: downArrowRect.minY), controlPoint2: NSPoint(x: downArrowRect.midX, y: downArrowRect.minY))
downInnerPath.line(to: NSPoint(x: downArrowRect.minX + cornerRadius / 2.0, y: downArrowRect.maxY - cornerRadius / 2.0))
downInnerPath.curve(to: NSPoint(x: downArrowRect.minX + cornerRadius / 2.0, y: downArrowRect.maxY), controlPoint1: NSPoint(x: downArrowRect.minX, y: downArrowRect.maxY), controlPoint2: NSPoint(x: downArrowRect.minX, y: downArrowRect.maxY))
textColorForTheme.setStroke()
downInnerPath.lineWidth = borderWidth
downInnerPath.stroke()
//// nameLabel Drawing
let nameLabelRect = NSRect(x: rect.width * 0.25, y: 0, width: rect.width * 0.75, height: rect.height)
let nameLabelStyle = NSMutableParagraphStyle()
nameLabelStyle.alignment = .left
let nameLabelFontAttributes = [NSAttributedStringKey.font: NSFont.boldSystemFont(ofSize: 24),
NSAttributedStringKey.foregroundColor: textColorForTheme,
NSAttributedStringKey.paragraphStyle: nameLabelStyle]
let nameLabelInset: CGRect = nameLabelRect.insetBy(dx: rect.width * 0.04, dy: 0)
let nameLabelTextHeight: CGFloat = NSString(string: presetName).boundingRect(
with: NSSize(width: nameLabelInset.width, height: CGFloat.infinity),
options: NSString.DrawingOptions.usesLineFragmentOrigin,
attributes: nameLabelFontAttributes).size.height
let nameLabelTextRect: NSRect = NSRect(
x: nameLabelInset.minX,
y: nameLabelInset.minY + (nameLabelInset.height - nameLabelTextHeight) / 2,
width: nameLabelInset.width,
height: nameLabelTextHeight)
NSGraphicsContext.saveGraphicsState()
__NSRectClip(nameLabelInset)
NSString(string: presetName).draw(in: nameLabelTextRect.offsetBy(dx: 0, dy: 0),
withAttributes: nameLabelFontAttributes)
NSGraphicsContext.restoreGraphicsState()
let outerRect = CGRect(x: rect.origin.x + borderWidth / 2.0,
y: rect.origin.y + borderWidth / 2.0,
width: rect.width - borderWidth,
height: rect.height - borderWidth)
let outerPath = NSBezierPath(roundedRect: outerRect, xRadius: cornerRadius, yRadius: cornerRadius)
borderColorForTheme.setStroke()
outerPath.lineWidth = borderWidth
outerPath.stroke()
}
override public func draw(_ rect: CGRect) {
let presetName = isPresetLoaded ? presets[currentIndex] : "None"
drawPresetLoader(presetName: presetName, isPresetLoaded: isPresetLoaded)
}
}
| mit | d4ec13b5cad49a0e548af66e6b450af4 | 47.634146 | 272 | 0.648027 | 4.496054 | false | false | false | false |
mentalfaculty/impeller | Playgrounds/TypeMapping.playground/Contents.swift | 1 | 897 | //: Playground - noun: a place where people can play
import UIKit
protocol Storable {
static var name: String { get }
init(age: Int)
}
extension Storable {
func hash() {}
}
protocol Storage : class {
var types: [Storable.Type]? { get set }
}
struct Person : Storable {
let age: Int = 0
init(age: Int) {
}
static var name: String { return "Person" }
}
struct Child : Storable {
let age: Int = 0
init(age: Int) {
}
static var name: String { return "Child" }
}
let storableTypes:[Storable.Type] = [Person.self, Child.self]
var storableTypeByName = [String:Storable.Type]()
for s in storableTypes {
storableTypeByName[s.name] = s
}
func create(for name:String) -> Storable? {
if let t = storableTypeByName[name] {
return t.init(age: 10)
}
return nil
}
create(for: "Child")
create(for: "Person")
create(for: "Elephant")
| mit | d8580806b94aad7d8f909d17ee936304 | 17.6875 | 61 | 0.632107 | 3.309963 | false | false | false | false |
TechnologySpeaks/smile-for-life | smile-for-life/UsersTable.swift | 1 | 8358 | //
// SQLTable.swift
// smile-for-life
//
// Created by Lisa Swanson on 8/15/16.
// Copyright © 2016 Technology Speaks. All rights reserved.
//
/*
import Foundation
//
// SQLTable.swift
// SQLiteDB-iOS
//
// Created by Fahim Farook on 6/11/15.
// Copyright © 2015 RookSoft Pte. Ltd. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
@objc(SQLTable)
class UsersTable:NSObject {
fileprivate var table:String!
fileprivate static var table:String {
let cls = "\(self.classForCoder())".lowercased()
let tnm = cls.hasSuffix("y") ? cls.substring(to: cls.characters.index(before: cls.endIndex)) + "ies" : cls + "s"
return tnm
}
required override init() {
super.init()
// Table name
let cls = "\(self.classForCoder)".lowercased()
let tnm = cls.hasSuffix("y") ? cls.substring(to: cls.characters.index(before: cls.endIndex)) + "ies" : cls + "s"
self.table = tnm
}
// MARK:- Table property management
func primaryKey() -> String {
return "id"
}
func ignoredKeys() -> [String] {
return []
}
func setPrimaryKey(_ val:AnyObject) {
setValue(val, forKey:primaryKey())
}
func getPrimaryKey() -> AnyObject? {
return value(forKey: primaryKey()) as AnyObject?
}
// MARK:- Class Methods
class func rows(_ filter:String="", order:String="", limit:Int=0) -> [UsersTable] {
var sql = "SELECT * FROM \(table)"
if !filter.isEmpty {
sql += " WHERE \(filter)"
}
if !order.isEmpty {
sql += " ORDER BY \(order)"
}
if limit > 0 {
sql += " LIMIT 0, \(limit)"
}
return self.rowsFor(sql)
}
class func rowsFor(_ sql:String="") -> [UsersTable] {
var res = [UsersTable]()
let tmp = self.init()
let data = tmp.values()
let db = SQLiteDB.sharedInstance
let fsql = sql.isEmpty ? "SELECT * FROM \(table)" : sql
let arr = db.query(sql: fsql)
for row in arr {
let t = self.init()
for (key, _) in data {
if let val = row[key] {
t.setValue(val, forKey:key)
}
}
res.append(t)
}
return res
}
class func rowByID(_ rid:Int) -> UsersTable? {
let row = self.init()
let data = row.values()
let db = SQLiteDB.sharedInstance
let sql = "SELECT * FROM \(table) WHERE \(row.primaryKey())=\(rid)"
let arr = db.query(sql: sql)
if arr.count == 0 {
return nil
}
for (key, _) in data {
if let val = arr[0][key] {
row.setValue(val, forKey:key)
}
}
return row
}
class func count(_ filter:String="") -> Int {
let db = SQLiteDB.sharedInstance
var sql = "SELECT COUNT(*) AS count FROM \(table)"
if !filter.isEmpty {
sql += " WHERE \(filter)"
}
let arr = db.query(sql: sql)
if arr.count == 0 {
return 0
}
if let val = arr[0]["count"] as? Int {
return val
}
return 0
}
class func row(_ rowNumber:Int, filter:String="", order:String="") -> UsersTable? {
let row = self.init()
let data = row.values()
let db = SQLiteDB.sharedInstance
var sql = "SELECT * FROM \(table)"
if !filter.isEmpty {
sql += " WHERE \(filter)"
}
if !order.isEmpty {
sql += " ORDER BY \(order)"
}
// Limit to specified row
sql += " LIMIT 1 OFFSET \(rowNumber-1)"
let arr = db.query(sql: sql)
if arr.count == 0 {
return nil
}
for (key, _) in data {
if let val = arr[0][key] {
row.setValue(val, forKey:key)
}
}
return row
}
class func remove(_ filter:String = "") -> Bool {
let db = SQLiteDB.sharedInstance
let sql:String
if filter.isEmpty {
// Delete all records
sql = "DELETE FROM \(table)"
} else {
// Use filter to delete
sql = "DELETE FROM \(table) WHERE \(filter)"
}
let rc = db.execute(sql: sql)
return (rc != 0)
}
class func zap() {
let db = SQLiteDB.sharedInstance
let sql = "DELETE FROM \(table)"
db.execute(sql: sql)
}
// MARK:- Public Methods
func save() -> Int {
let db = SQLiteDB.sharedInstance
let key = primaryKey()
let data = values()
var insert = true
if let rid = data[key] {
let sql = "SELECT COUNT(*) AS count FROM \(table) WHERE \(primaryKey())=\(rid)"
let arr = db.query(sql: sql)
if arr.count == 1 {
if let cnt = arr[0]["count"] as? Int {
insert = (cnt == 0)
}
}
}
// Insert or update
let (sql, params) = getSQL(data, forInsert:insert)
let rc = db.execute(sql: sql, parameters:params)
// Update primary key
let rid = Int(rc)
if insert {
setValue(rid, forKey:key)
}
let res = (rc != 0)
if !res {
NSLog("Error saving record!")
}
return rid
}
func delete() -> Bool {
let db = SQLiteDB.sharedInstance
let key = primaryKey()
let data = values()
if let rid = data[key] {
let sql = "DELETE FROM \(table) WHERE \(primaryKey())=\(rid)"
let rc = db.execute(sql: sql)
return (rc != 0)
}
return false
}
func refresh() {
let db = SQLiteDB.sharedInstance
let key = primaryKey()
let data = values()
if let rid = data[key] {
let sql = "SELECT * FROM \(table) WHERE \(primaryKey())=\(rid)"
let arr = db.query(sql: sql)
for (key, _) in data {
if let val = arr[0][key] {
setValue(val, forKey:key)
}
}
}
}
// MARK:- Private Methods
// private func properties() -> [String] {
// var res = [String]()
// for c in Mirror(reflecting:self).children {
// if let name = c.label{
// res.append(name)
// }
// }
// return res
// }
fileprivate func values() -> [String:AnyObject] {
var res = [String:AnyObject]()
let obj = Mirror(reflecting:self)
for (_, attr) in obj.children.enumerated() {
if let name = attr.label {
// Ignore special properties and lazy vars
if ignoredKeys().contains(name) || name.hasSuffix(".storage") {
continue
}
res[name] = getValue(attr.value as AnyObject)
}
}
return res
}
fileprivate func getValue(_ val:AnyObject) -> AnyObject {
if val is String {
return val as! String as AnyObject
} else if val is Int {
return val as! Int as AnyObject
} else if val is Float {
return val as! Float as AnyObject
} else if val is Double {
return val as! Double as AnyObject
} else if val is Bool {
return val as! Bool as AnyObject
} else if val is Date {
return val as! Date as AnyObject
} else if val is Data {
return val as! Data as AnyObject
}
return "nAn" as AnyObject
}
fileprivate func getSQL(_ data:[String:AnyObject], forInsert:Bool = true) -> (String, [AnyObject]?) {
var sql = ""
var params:[AnyObject]? = nil
if forInsert {
// INSERT INTO tasks(task, categoryID) VALUES ('\(txtTask.text)', 1)
sql = "INSERT INTO \(table)("
} else {
// UPDATE tasks SET task = ? WHERE categoryID = ?
sql = "UPDATE \(table) SET "
}
let pkey = primaryKey()
var wsql = ""
var rid:AnyObject?
var first = true
for (key, val) in data {
// Primary key handling
if pkey == key {
if forInsert {
if val is Int && (val as! Int) == -1 {
// Do not add this since this is (could be?) an auto-increment value
continue
}
} else {
// Update - set up WHERE clause
wsql += " WHERE " + key + " = ?"
rid = val
continue
}
}
// Set up parameter array - if we get here, then there are parameters
if first && params == nil {
params = [AnyObject]()
}
if forInsert {
sql += first ? "\(key)" : ", \(key)"
wsql += first ? " VALUES (?" : ", ?"
params!.append(val)
} else {
sql += first ? "\(key) = ?" : ", \(key) = ?"
params!.append(val)
}
first = false
}
// Finalize SQL
if forInsert {
sql += ")" + wsql + ")"
} else if params != nil && !wsql.isEmpty {
sql += wsql
params!.append(rid!)
}
// NSLog("Final SQL: \(sql) with parameters: \(params)")
return (sql, params)
}
}
*/
| mit | 6fc56dede76ae30313091d0524013468 | 24.398176 | 116 | 0.546793 | 3.689183 | false | false | false | false |
SwiftKitz/Datez | Sources/Datez/Entity/DateView.swift | 1 | 1427 | //
// Date.swift
// Prayerz
//
// Created by Mazyad Alabduljaleel on 9/16/15.
// Copyright (c) 2015 ArabianDevs. All rights reserved.
//
import Foundation
/** A date associated with an `Calendar` */
public struct DateView: Equatable {
// MARK: - Properties
public let date: Date
public let calendar: Calendar
public var components: CalendarComponents {
return calendar.dateComponents(
Calendar.Component.all,
from: date
).calendarComponents
}
// MARK: - Init & Dealloc
public init(forDate date: Date, inCalendar calendar: Calendar) {
self.calendar = calendar
self.date = date
}
public init(forCalendarComponents calendarComponents: CalendarComponents, inCalendar calendar: Calendar) {
self.init(
forDate: calendar.date(from: calendarComponents.dateComponents)!,
inCalendar: calendar
)
}
// MARK: - Public methods
public func update(
year: Int? = nil,
month: Int? = nil,
day: Int? = nil,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil
) -> DateView
{
let comps = components.update(year: year, month: month, day: day, hour: hour, minute: minute, second: second)
return DateView(forCalendarComponents: comps, inCalendar: calendar)
}
}
| mit | 442ea17f365e0ed13d0424b844df5c90 | 24.035088 | 117 | 0.594954 | 4.377301 | false | false | false | false |
wackosix/WSNetEaseNews | NetEaseNews/Classes/External/PhotoBrowser/Controller/PhotoBrowser+Indicator.swift | 1 | 895 | //
// PhotoBrowser+Indicator.swift
// PhotoBrowser
//
// Created by 冯成林 on 15/8/13.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
extension PhotoBrowser{
/** pagecontrol准备 */
func pagecontrolPrepare(){
if !hideMsgForZoomAndDismissWithSingleTap {return}
view.addSubview(pagecontrol)
pagecontrol.make_bottomInsets_bottomHeight(left: 0, bottom: 0, right: 0, bottomHeight: 37)
pagecontrol.numberOfPages = photoModels.count
pagecontrol.enabled = false
}
/** pageControl页面变动 */
func pageControlPageChanged(page: Int){
if page<0 || page>=photoModels.count {return}
if showType == ShowType.ZoomAndDismissWithSingleTap && hideMsgForZoomAndDismissWithSingleTap{
pagecontrol.currentPage = page
}
}
}
| mit | a20270db3b812870259c25e39321d72b | 24.558824 | 101 | 0.635213 | 4.323383 | false | false | false | false |
googleprojectzero/fuzzilli | Sources/Fuzzilli/Util/RingBuffer.swift | 1 | 2242 | // Copyright 2019 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 Foundation
public struct RingBuffer<Element>: Collection {
/// The internal buffer used by this implementation.
private var buffer: [Element]
/// The index in the buffer that is the current start (the oldest element).
private var start: Int
/// The maximum size of this ring buffer.
public let maxSize: Int
/// The number of elements in this ring buffer.
public var count: Int {
return buffer.count
}
/// The index of the first element.
public let startIndex = 0
/// The first index after the end of this buffer.
public var endIndex: Int {
return count
}
public init(maxSize: Int) {
self.buffer = []
self.start = 0
self.maxSize = maxSize
}
/// Returns the next index after the provided one.
public func index(after i: Int) -> Int {
return i + 1
}
/// Accesses the element at the given index.
public subscript(index: Int) -> Element {
get {
return buffer[(start + index) % maxSize]
}
mutating set(newValue) {
buffer[(start + index) % maxSize] = newValue
}
}
/// Appends the element to this buffer, evicting the oldest element if necessary.
public mutating func append(_ element: Element) {
if buffer.count < maxSize {
buffer.append(element)
} else {
buffer[(start + count) % maxSize] = element
start += 1
}
}
/// Removes all elements from this buffer, resetting its size to zero.
public mutating func removeAll() {
buffer.removeAll()
start = 0
}
}
| apache-2.0 | 35636f4831743ca0d189aaf4538c453c | 28.5 | 85 | 0.633809 | 4.547667 | false | false | false | false |
milseman/swift | test/SILGen/scalar_to_tuple_args.swift | 8 | 4407 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {}
func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {}
func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {}
func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {}
func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {}
func variadicFirst(_ x: Int...) {}
func variadicSecond(_ x: Int, _ y: Int...) {}
var x = 0
// CHECK: [[X_ADDR:%.*]] = global_addr @_T020scalar_to_tuple_args1xSiv : $*Int
// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args17inoutWithDefaultsySiz_Si1ySi1ztF
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
// CHECK: apply [[INOUT_WITH_DEFAULTS]]([[WRITE]], [[DEFAULT_Y]], [[DEFAULT_Z]])
inoutWithDefaults(&x)
// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args27inoutWithCallerSideDefaultsySiz_Si1ytF
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
// CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[WRITE]], [[LINE]])
inoutWithCallerSideDefaults(&x)
// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A12WithDefaultsySi_Si1ySi1ztF
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]])
scalarWithDefaults(x)
// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A22WithCallerSideDefaultsySi_Si1ytF
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]])
scalarWithCallerSideDefaults(x)
// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0C12WithDefaultsySi_Sit1x_Si1ySi1ztF
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X1:%.*]] = load [trivial] [[READ]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X2:%.*]] = load [trivial] [[READ]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]])
tupleWithDefaults(x: (x,x))
// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_T020scalar_to_tuple_args13variadicFirstySaySiGd_tF
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[BORROWED_ALLOC_ARRAY:%.*]] = begin_borrow [[ALLOC_ARRAY]]
// CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]]
// CHECK: [[MEMORY:%.*]] = tuple_extract [[BORROWED_ALLOC_ARRAY]] {{.*}}, 1
// CHECK: end_borrow [[BORROWED_ALLOC_ARRAY]] from [[ALLOC_ARRAY]]
// CHECK: destroy_value [[ALLOC_ARRAY]]
// CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: store [[X]] to [trivial] [[ADDR]]
// CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
variadicFirst(x)
// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_T020scalar_to_tuple_args14variadicSecondySi_SaySiGdtF
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[BORROWED_ALLOC_ARRAY:%.*]] = begin_borrow [[ALLOC_ARRAY]]
// CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]]
// CHECK: end_borrow [[BORROWED_ALLOC_ARRAY]] from [[ALLOC_ARRAY]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
variadicSecond(x)
| apache-2.0 | f3dbd589b905e5654a7d3097e532421d | 54.759494 | 126 | 0.603632 | 3.185105 | false | false | false | false |
googleprojectzero/fuzzilli | Sources/Fuzzilli/Lifting/JavaScriptExploreLifting.swift | 1 | 43785 | // Copyright 2022 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.
/// This file contains the JavaScript specific implementation of the Explore operation. See ExplorationMutator.swift for an overview of this feature.
struct JavaScriptExploreHelper {
static let prefixCode = """
const explore = (function() {
// Note: this code must generally assume that any operation performed on the object to explore, or any object obtained through it (e.g. a prototype), may raise an exception, for example due to triggering a Proxy trap.
// Further, it must also assume that the environment has been modified arbitrarily. For example, the Array.prototype[@@iterator] may have been set to an invalid value, so using `for...of` syntax could trigger an exception.
// Load all necessary routines into local variables as they may be overwritten by the program.
// We generally want to avoid triggerring observable side-effects, such as storing or loading
// properties. For that reason, we prefer to use builtins like Object.defineProperty.
const ObjectPrototype = Object.prototype;
const getOwnPropertyNames = Object.getOwnPropertyNames;
const getPrototypeOf = Object.getPrototypeOf;
const setPrototypeOf = Object.setPrototypeOf;
const stringify = JSON.stringify;
const hasOwnProperty = Object.hasOwn;
const defineProperty = Object.defineProperty;
const propertyValues = Object.values;
const parseInteger = parseInt;
const NumberIsInteger = Number.isInteger;
const isNaN = Number.isNaN;
const isFinite = Number.isFinite;
const random = Math.random;
const truncate = Math.trunc;
const apply = Reflect.apply;
const construct = Reflect.construct;
const makeBigInt = BigInt;
// Bind methods to local variables. These all expect the 'this' object as first parameter.
const concat = Function.prototype.call.bind(Array.prototype.concat);
const findIndex = Function.prototype.call.bind(Array.prototype.findIndex);
const includes = Function.prototype.call.bind(Array.prototype.includes);
const shift = Function.prototype.call.bind(Array.prototype.shift);
const pop = Function.prototype.call.bind(Array.prototype.pop);
const push = Function.prototype.call.bind(Array.prototype.push);
const match = Function.prototype.call.bind(RegExp.prototype[Symbol.match]);
const stringSlice = Function.prototype.call.bind(String.prototype.slice);
const toUpperCase = Function.prototype.call.bind(String.prototype.toUpperCase);
const numberToString = Function.prototype.call.bind(Number.prototype.toString);
const bigintToString = Function.prototype.call.bind(BigInt.prototype.toString);
// When creating empty arrays to which elements are later added, use a custom array type that has a null prototype. This way, the arrays are not
// affected by changes to the Array.prototype that could interfere with array builtins (e.g. indexed setters or a modified .constructor property).
function EmptyArray() {
let array = [];
setPrototypeOf(array, null);
return array;
}
//
// Global constants.
//
const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
// Property names to use when defining new properties. Should be kept in sync with the equivalent set in JavaScriptEnvironment.swift
const customPropertyNames = ['a', 'b', 'c', 'd', 'e'];
// Special value to indicate that no action should be performed, usually because there was an error performing the chosen action.
const NO_ACTION = null;
// Maximum number of parameters for function/method calls. Everything above this is consiered an invalid .length property of the function.
const MAX_PARAMETERS = 10;
// Well known integer/number values to use when generating random values.
const WELL_KNOWN_INTEGERS = [-4294967296, -4294967295, -2147483648, -2147483647, -4096, -1024, -256, -128, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 64, 128, 256, 1024, 4096, 65535, 65536, 2147483647, 2147483648, 4294967295, 4294967296];
const WELL_KNOWN_NUMBERS = concat(WELL_KNOWN_INTEGERS, [-1e6, -1e3, -5.0, -4.0, -3.0, -2.0, -1.0, -0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 1e3, 1e6]);
const WELL_KNOWN_BIGINTS = [-18446744073709551616n, -9223372036854775808n, -9223372036854775807n, -9007199254740991n, -9007199254740990n, -4294967297n, -4294967296n, -4294967295n, -2147483648n, -2147483647n, -4096n, -1024n, -256n, -128n, -2n, -1n, 0n, 1n, 2n, 3n, 4n, 5n, 6n, 7n, 8n, 9n, 10n, 16n, 64n, 128n, 256n, 1024n, 4096n, 65535n, 65536n, 2147483647n, 2147483648n, 4294967295n, 4294967296n, 4294967297n, 9007199254740990n, 9007199254740991n, 9223372036854775806n, 9223372036854775807n, 9223372036854775808n, 18446744073709551616n];
//
// List of all supported operations. Must be kept in sync with the ExplorationMutator.
//
const OP_CALL_FUNCTION = 'CALL_FUNCTION';
const OP_CONSTRUCT = 'CONSTRUCT';
const OP_CALL_METHOD = 'CALL_METHOD';
const OP_CONSTRUCT_MEMBER = 'CONSTRUCT_MEMBER';
const OP_GET_PROPERTY = 'GET_PROPERTY';
const OP_SET_PROPERTY = 'SET_PROPERTY';
const OP_DEFINE_PROPERTY = 'DEFINE_PROPERTY';
const OP_GET_ELEMENT = 'GET_ELEMENT';
const OP_SET_ELEMENT = 'SET_ELEMENT';
const OP_ADD = 'ADD';
const OP_SUB = 'SUB';
const OP_MUL = 'MUL';
const OP_DIV = 'DIV';
const OP_MOD = 'MOD';
const OP_INC = 'INC';
const OP_DEC = 'DEC';
const OP_NEG = 'NEG';
const OP_LOGICAL_AND = 'LOGICAL_AND';
const OP_LOGICAL_OR = 'LOGICAL_OR';
const OP_LOGICAL_NOT = 'LOGICAL_NOT';
const OP_BITWISE_AND = 'BITWISE_AND';
const OP_BITWISE_OR = 'BITWISE_OR';
const OP_BITWISE_XOR = 'BITWISE_XOR';
const OP_LEFT_SHIFT = 'LEFT_SHIFT';
const OP_SIGNED_RIGHT_SHIFT = 'SIGNED_RIGHT_SHIFT';
const OP_UNSIGNED_RIGHT_SHIFT = 'UNSIGNED_RIGHT_SHIFT';
const OP_BITWISE_NOT = 'BITWISE_NOT';
const OP_COMPARE_EQUAL = 'COMPARE_EQUAL';
const OP_COMPARE_STRICT_EQUAL = 'COMPARE_STRICT_EQUAL';
const OP_COMPARE_NOT_EQUAL = 'COMPARE_NOT_EQUAL';
const OP_COMPARE_STRICT_NOT_EQUAL = 'COMPARE_STRICT_NOT_EQUAL';
const OP_COMPARE_GREATER_THAN = 'COMPARE_GREATER_THAN';
const OP_COMPARE_LESS_THAN = 'COMPARE_LESS_THAN';
const OP_COMPARE_GREATER_THAN_OR_EQUAL = 'COMPARE_GREATER_THAN_OR_EQUAL';
const OP_COMPARE_LESS_THAN_OR_EQUAL = 'COMPARE_LESS_THAN_OR_EQUAL';
const OP_TEST_IS_NAN = 'TEST_IS_NAN';
const OP_TEST_IS_FINITE = 'TEST_IS_FINITE';
const OP_SYMBOL_REGISTRATION = 'SYMBOL_REGISTRATION';
// Operation groups. See e.g. exploreNumber() for examples of how they are used.
const SHIFT_OPS = [OP_LEFT_SHIFT, OP_SIGNED_RIGHT_SHIFT, OP_UNSIGNED_RIGHT_SHIFT];
// Unsigned shift is not defined for bigints.
const BIGINT_SHIFT_OPS = [OP_LEFT_SHIFT, OP_SIGNED_RIGHT_SHIFT];
const BITWISE_OPS = [OP_BITWISE_OR, OP_BITWISE_AND, OP_BITWISE_XOR];
const ARITHMETIC_OPS = [OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_MOD];
const UNARY_OPS = [OP_INC, OP_DEC, OP_NEG, OP_BITWISE_NOT];
const COMPARISON_OPS = [OP_COMPARE_EQUAL, OP_COMPARE_STRICT_EQUAL, OP_COMPARE_NOT_EQUAL, OP_COMPARE_STRICT_NOT_EQUAL, OP_COMPARE_GREATER_THAN, OP_COMPARE_LESS_THAN, OP_COMPARE_GREATER_THAN_OR_EQUAL, OP_COMPARE_LESS_THAN_OR_EQUAL];
const BOOLEAN_BINARY_OPS = [OP_LOGICAL_AND, OP_LOGICAL_OR];
const BOOLEAN_UNARY_OPS = [OP_LOGICAL_NOT];
//
// Global variables.
//
// The arguments given to the Explore operation which can be used by the concrete action.
let exploreArguments;
// The current value of |this| when exploring. Needed to correctly set the |this| value when performing a regular function call (see OP_CALL_FUNCTION handler).
let currentThis;
// Whether exploration is currently happening. This is required to detect recursive exploration, where for example a callback
// triggered during property enumeration triggers further exploration calls. See explore().
let currentlyExploring = false;
//
// Error and result reporting.
// The concrete action performed by an Explore operation is encoded and transmitted as an object: {operation: OP_SOMETHING, inputs: inputs_array}.
// The operation is one of the above constants, the inputs is an array of input objects, see below.
//
// Results (indexed by their ID) will be stored in here.
const results = { __proto__: null };
function reportError(msg) {
fuzzilli('FUZZILLI_PRINT', 'EXPLORE_ERROR: ' + msg);
}
function recordFailure(id) {
// Delete the property if it already exists (from recordAction).
delete results[id];
defineProperty(results, id, {__proto__: null, value: null});
fuzzilli('FUZZILLI_PRINT', 'EXPLORE_FAILURE: ' + id);
}
function recordAction(id, action) {
if (hasOwnProperty(results, id)) {
throw "Duplicate action for " + id;
}
if (action === NO_ACTION) {
// This is equivalent to a failure.
return recordFailure(id);
}
action.id = id;
// These are configurable as they may need to be overwritten (by recordFailure) in the future.
defineProperty(results, id, {__proto__: null, value: action, configurable: true});
fuzzilli('FUZZILLI_PRINT', 'EXPLORE_ACTION: ' + stringify(action));
}
function hasActionFor(id) {
return hasOwnProperty(results, id);
}
function getActionFor(id) {
return results[id];
}
//
// Misc. helper functions.
//
// Type check helpers. These are less error-prone than manually using typeof and comparing against a string.
function isObject(v) {
return typeof v === 'object';
}
function isFunction(v) {
return typeof v === 'function';
}
function isString(v) {
return typeof v === 'string';
}
function isNumber(v) {
return typeof v === 'number';
}
function isBigint(v) {
return typeof v === 'bigint';
}
function isSymbol(v) {
return typeof v === 'symbol';
}
function isBoolean(v) {
return typeof v === 'boolean';
}
function isUndefined(v) {
return typeof v === 'undefined';
}
// Helper function to determine if a value is an integer, and within [MIN_SAFE_INTEGER, MAX_SAFE_INTEGER].
function isInteger(n) {
return isNumber(n) && NumberIsInteger(n) && n>= MIN_SAFE_INTEGER && n <= MAX_SAFE_INTEGER;
}
// Helper function to determine if a string is "simple". We only include simple strings for property/method names or string literals.
// A simple string is basically a valid, property name with a maximum length.
function isSimpleString(s) {
if (!isString(s)) throw "Non-string argument to isSimpleString: " + s;
return s.length < 50 && match(/^[0-9a-zA-Z_$]+$/, s);
}
// Helper function to determine whether a property can be accessed without raising an exception.
function tryAccessProperty(prop, obj) {
try {
obj[prop];
return true;
} catch (e) {
return false;
}
}
// Helper function to determine if a property exists on an object or one of its prototypes. If an exception is raised, false is returned.
function tryHasProperty(prop, obj) {
try {
return prop in obj;
} catch (e) {
return false;
}
}
// Helper function to load a property from an object. If an exception is raised, undefined is returned.
function tryGetProperty(prop, obj) {
try {
return obj[prop];
} catch (e) {
return undefined;
}
}
// Helper function to obtain the own properties of an object. If that raises an exception (e.g. on a Proxy object), an empty array is returned.
function tryGetOwnPropertyNames(obj) {
try {
return getOwnPropertyNames(obj);
} catch (e) {
return new Array();
}
}
// Helper function to fetch the prototype of an object. If that raises an exception (e.g. on a Proxy object), null is returned.
function tryGetPrototypeOf(obj) {
try {
return getPrototypeOf(obj);
} catch (e) {
return null;
}
}
// Helper function to that creates a wrapper function for the given function which will call it in a try-catch and return false on exception.
function wrapInTryCatch(f) {
return function() {
try {
return apply(f, this, arguments);
} catch (e) {
return false;
}
};
}
//
// Basic random number generation utility functions.
//
function probability(p) {
if (p < 0 || p > 1) throw "Argument to probability must be a number between zero and one";
return random() < p;
}
function randomIntBetween(start, end) {
if (!isInteger(start) || !isInteger(end)) throw "Arguments to randomIntBetween must be integers";
return truncate(random() * (end - start) + start);
}
function randomBigintBetween(start, end) {
if (!isBigint(start) || !isBigint(end)) throw "Arguments to randomBigintBetween must be bigints";
if (!isInteger(Number(start)) || !isInteger(Number(end))) throw "Arguments to randomBigintBetween must be representable as regular intergers";
return makeBigInt(randomIntBetween(Number(start), Number(end)));
}
function randomIntBelow(n) {
if (!isInteger(n)) throw "Argument to randomIntBelow must be an integer";
return truncate(random() * n);
}
function randomElement(array) {
return array[randomIntBelow(array.length)];
}
//
// Input constructors.
// The inputs for actions are encoded as objects that specify both the type and the value of the input:
// {argumentIndex: i} Use the ith argument of the Explore operation (index 0 corresponds to the 2nd input of the Explore operation, the first input is the value to explore)
// {methodName: m} Contains the method name as string for method calls. Always the first input.
// {propertyName: p} Contains the property name as string for property operations. Always the first input.
// {elementIndex: i} Contains the element index as integer for element operations. Always the first input.
// {intValue: v}
// {floatValue: v}
// {bigintValue: v} As bigints are not encodable using JSON.stringify, they are stored as strings.
// {stringValue: v}
//
// These must be kept in sync with the Action.Input struct in the ExplorationMutator.
//
function ArgumentInput(idx) {
this.argumentIndex = idx;
}
function MethodNameInput(name) {
this.methodName = name;
}
function PropertyNameInput(name) {
this.propertyName = name;
}
function ElementIndexInput(idx) {
this.elementIndex = idx;
}
function IntInput(v) {
if (!isInteger(v)) throw "IntInput value is not an integer: " + v;
this.intValue = v;
}
function FloatInput(v) {
if (!isNumber(v) || !isFinite(v)) throw "FloatInput value is not a (finite) number: " + v;
this.floatValue = v;
}
function BigintInput(v) {
if (!isBigint(v)) throw "BigintInput value is not a bigint: " + v;
// Bigints can't be serialized by JSON.stringify, so store them as strings instead.
this.bigintValue = bigintToString(v);
}
function StringInput(v) {
if (!isString(v) || !isSimpleString(v)) throw "StringInput value is not a (simple) string: " + v;
this.stringValue = v;
}
//
// Access to random inputs.
// These functions prefer to take an existing variable from the arguments to the Explore operations if it satistifes the specified criteria. Otherwise, they generate a new random value.
// Testing whether an argument satisfies some criteria (e.g. be a value in a certain range) may trigger type conversions. This is expected as it may lead to interesting values being used.
// These are grouped into a namespace object to make it more clear that they return an Input object (from one of the above constructors), rather than a value.
//
let Inputs = {
randomArgument() {
return new ArgumentInput(randomIntBelow(exploreArguments.length));
},
randomArguments(n) {
let args = EmptyArray();
for (let i = 0; i < n; i++) {
push(args, new ArgumentInput(randomIntBelow(exploreArguments.length)));
}
return args;
},
randomArgumentForReplacing(propertyName, obj) {
let curValue = tryGetProperty(propertyName, obj);
if (isUndefined(curValue)) {
return Inputs.randomArgument();
}
function isCompatible(arg) {
let sameType = typeof curValue === typeof arg;
if (sameType && isObject(curValue)) {
sameType = arg instanceof curValue.constructor;
}
return sameType;
}
let idx = findIndex(exploreArguments, wrapInTryCatch(isCompatible));
if (idx != -1) return new ArgumentInput(idx);
return Inputs.randomArgument();
},
randomInt() {
let idx = findIndex(exploreArguments, isInteger);
if (idx != -1) return new ArgumentInput(idx);
return new IntInput(randomElement(WELL_KNOWN_INTEGERS));
},
randomNumber() {
let idx = findIndex(exploreArguments, isNumber);
if (idx != -1) return new ArgumentInput(idx);
return new FloatInput(randomElement(WELL_KNOWN_NUMBERS));
},
randomBigint() {
let idx = findIndex(exploreArguments, isBigint);
if (idx != -1) return new ArgumentInput(idx);
return new BigintInput(randomElement(WELL_KNOWN_BIGINTS));
},
randomIntBetween(start, end) {
if (!isInteger(start) || !isInteger(end)) throw "Arguments to randomIntBetween must be integers";
let idx = findIndex(exploreArguments, wrapInTryCatch((e) => NumberIsInteger(e) && (e >= start) && (e < end)));
if (idx != -1) return new ArgumentInput(idx);
return new IntInput(randomIntBetween(start, end));
},
randomBigintBetween(start, end) {
if (!isBigint(start) || !isBigint(end)) throw "Arguments to randomBigintBetween must be bigints";
if (!isInteger(Number(start)) || !isInteger(Number(end))) throw "Arguments to randomBigintBetween must be representable as regular integers";
let idx = findIndex(exploreArguments, wrapInTryCatch((e) => (e >= start) && (e < end)));
if (idx != -1) return new ArgumentInput(idx);
return new BigintInput(randomBigintBetween(start, end));
},
randomNumberCloseTo(v) {
if (!isFinite(v)) throw "Argument to randomNumberCloseTo is not a finite number: " + v;
let idx = findIndex(exploreArguments, wrapInTryCatch((e) => (e >= v - 10) && (e <= v + 10)));
if (idx != -1) return new ArgumentInput(idx);
let step = randomIntBetween(-10, 10);
let value = v + step;
if (isInteger(value)) {
return new IntInput(value);
} else {
return new FloatInput(v + step);
}
},
randomBigintCloseTo(v) {
if (!isBigint(v)) throw "Argument to randomBigintCloseTo is not a bigint: " + v;
let idx = findIndex(exploreArguments, wrapInTryCatch((e) => (e >= v - 10n) && (e <= v + 10n)));
if (idx != -1) return new ArgumentInput(idx);
let step = randomBigintBetween(-10n, 10n);
let value = v + step;
return new BigintInput(value);
},
// Returns a random property, element, or method on the given object or one of its prototypes.
randomPropertyElementOrMethod(o) {
// TODO: Add special handling for ArrayBuffers: most of the time, wrap these into a Uint8Array to be able to modify them.
// Collect all properties, including those from prototypes, in this array.
let properties = EmptyArray();
// Give properties from prototypes a lower weight. Currently, the weight is halved for every new level of the prototype chain.
let currentWeight = 1.0;
let totalWeight = 0.0;
function recordProperty(p) {
push(properties, {name: p, weight: currentWeight});
totalWeight += currentWeight;
}
// Iterate over the prototype chain and record all properties.
let obj = o;
while (obj !== null) {
// Special handling for array-like things: if the array is too large, skip this level and just include a couple random indices.
// We need to be careful when accessing the length though: for TypedArrays, the length property is defined on the prototype but
// must be accessed with the TypedArray as |this| value (not the prototype).
let maybeLength = tryGetProperty('length', obj);
if (isInteger(maybeLength) && maybeLength > 100) {
for (let i = 0; i < 10; i++) {
let randomElement = randomIntBelow(maybeLength);
recordProperty(randomElement);
}
} else {
// TODO do we want to also enumerate symbol properties here (using Object.getOwnPropertySymbols)? If we do, we should probable also add IL-level support for Symbols (i.e. a `LoadSymbol` instruction that ensures the symbol is in the global Symbol registry).
let allOwnPropertyNames = tryGetOwnPropertyNames(obj);
let allOwnElements = EmptyArray();
for (let i = 0; i < allOwnPropertyNames.length; i++) {
let p = allOwnPropertyNames[i];
let index = parseInteger(p);
// TODO should we allow negative indices here as well?
if (index >= 0 && index <= MAX_SAFE_INTEGER && numberToString(index) === p) {
push(allOwnElements, index);
} else if (isSimpleString(p) && tryAccessProperty(p, o)) {
// Only include properties with "simple" names and only if they can be accessed on the original object without raising an exception.
recordProperty(p);
}
}
// Limit array-like objects to at most 10 random elements.
for (let i = 0; i < 10 && allOwnElements.length > 0; i++) {
let index = randomIntBelow(allOwnElements.length);
recordProperty(allOwnElements[index]);
allOwnElements[index] = pop(allOwnElements);
}
}
obj = tryGetPrototypeOf(obj);
currentWeight /= 2.0;
// Greatly reduce the property weights for the Object.prototype. These methods are always available and we can use more targeted things like CodeGenerators to call them if we want to.
if (obj === ObjectPrototype) {
// Somewhat arbitrarily reduce the weight as if there were another 3 levels.
currentWeight /= 8.0;
// However, if we've reached the Object prototype without any other properties (i.e. are exploring an empty, plain object), then always abort, in which case we'll define a new property instead.
if (properties.length == 0) {
return null;
}
}
}
// Require at least 3 different properties to chose from.
if (properties.length < 3) {
return null;
}
// Now choose a random property. If a property has weight 2W, it will be selected with twice the probability of a property with weight W.
let p;
let remainingWeight = random() * totalWeight;
for (let i = 0; i < properties.length; i++) {
let candidate = properties[i];
remainingWeight -= candidate.weight;
if (remainingWeight < 0) {
p = candidate.name;
break;
}
}
// Sanity checking. This may fail for example if Proxies are involved. In that case, just fail here.
if (!tryHasProperty(p, o)) return null;
// Determine what type of property it is.
if (isNumber(p)) {
return new ElementIndexInput(p);
} else if (isFunction(tryGetProperty(p, o))) {
return new MethodNameInput(p);
} else {
return new PropertyNameInput(p);
}
}
}
//
// Explore implementation for different basic types.
//
// These all return an "action" object of the form {operation: SOME_OPERATION, inputs: array_of_inputs}. They may also return the special NO_ACTION value (null).
//
function Action(operation, inputs = EmptyArray()) {
this.operation = operation;
this.inputs = inputs;
}
// Heuristic to determine when a function should be invoked as a constructor.
function shouldTreatAsConstructor(f) {
let name = tryGetProperty('name', f);
// If the function has no name (or a non-string name), it's probably a regular function (or something like an arrow function).
if (!isString(name) || name.length < 1) {
return probability(0.1);
}
// If the name is something like `v42`, it's probably a function defined by Fuzzilli. These can typicall be as function or constructor, but prefer to call them as regular functions.
if (name[0] === 'v' && !isNaN(parseInteger(stringSlice(name, 1)))) {
return probability(0.2);
}
// Otherwise, the basic heuristic is that functions that start with an uppercase letter (e.g. Object, Uint8Array, etc.) are probably constructors (but not always, e.g. BigInt).
// This is also compatible with Fuzzilli's lifting of classes, as they will look something like this: `class V3 { ...`.
if (name[0] === toUpperCase(name[0])) {
return probability(0.9);
} else {
return probability(0.1);
}
}
function exploreObject(o) {
if (o === null) {
// Can't do anything with null.
return NO_ACTION;
}
// Determine a random property, which can generally either be a method, an element, or a "regular" property.
let input = Inputs.randomPropertyElementOrMethod(o);
// Determine the appropriate action to perform.
// If the property lookup failed (for whatever reason), we always define a new property.
if (input === null) {
return new Action(OP_DEFINE_PROPERTY, [new PropertyNameInput(randomElement(customPropertyNames)), Inputs.randomArgument()]);
} else if (input instanceof MethodNameInput) {
let f = tryGetProperty(input.methodName, o);
// More sanity checks. These may rarely fail e.g. due to non-deterministically behaving Proxies. In that case, just give up.
if (!isFunction(f)) return NO_ACTION;
let numParameters = tryGetProperty('length', f);
if (!isInteger(numParameters) || numParameters > MAX_PARAMETERS || numParameters < 0) return NO_ACTION;
// Small hack, generate n+1 input arguments, then replace index 0 with the method name input.
let inputs = Inputs.randomArguments(numParameters + 1);
inputs[0] = input;
if (shouldTreatAsConstructor(f)) {
return new Action(OP_CONSTRUCT_MEMBER, inputs);
} else {
return new Action(OP_CALL_METHOD, inputs);
}
} else if (input instanceof ElementIndexInput) {
if (probability(0.5)) {
return new Action(OP_GET_ELEMENT, [input]);
} else {
let newValue = Inputs.randomArgumentForReplacing(input.elementIndex, o);
return new Action(OP_SET_ELEMENT, [input, newValue]);
}
} else if (input instanceof PropertyNameInput) {
// Besides getting and setting the property, we also sometimes define a new property instead.
if (probability(1/3)) {
input.propertyName = randomElement(customPropertyNames);
return new Action(OP_SET_PROPERTY, [input, Inputs.randomArgument()]);
} else if (probability(0.5)) {
return new Action(OP_GET_PROPERTY, [input]);
} else {
let newValue = Inputs.randomArgumentForReplacing(input.propertyName, o);
return new Action(OP_SET_PROPERTY, [input, newValue]);
}
} else {
throw "Got unexpected input " + input;
}
}
function exploreFunction(f) {
// Sometimes treat functions as objects.
// This will cause interesting properties like 'arguments' or 'prototype' to be accessed, methods like 'apply' or 'bind' to be called, and methods on builtin constructors like 'Array', and 'Object' to be used.
if (probability(0.5)) {
return exploreObject(f);
}
// Otherwise, call or construct the function/constructor.
let numParameters = tryGetProperty('length', f);
if (!isInteger(numParameters) || numParameters > MAX_PARAMETERS || numParameters < 0) {
numParameters = 0;
}
let operation = shouldTreatAsConstructor(f) ? OP_CONSTRUCT : OP_CALL_FUNCTION;
return new Action(operation, Inputs.randomArguments(numParameters));
}
function exploreString(s) {
// Sometimes (rarely) compare the string against it's original value. Otherwise, treat the string as an object.
if (probability(0.1) && isSimpleString(s)) {
return new Action(OP_COMPARE_EQUAL, [new StringInput(s)]);
} else {
return exploreObject(new String(s));
}
}
const ALL_NUMBER_OPERATIONS = concat(SHIFT_OPS, BITWISE_OPS, ARITHMETIC_OPS, UNARY_OPS);
const ALL_NUMBER_OPERATIONS_AND_COMPARISONS = concat(ALL_NUMBER_OPERATIONS, COMPARISON_OPS);
function exploreNumber(n) {
// Somewhat arbitrarily give comparisons a lower probability when choosing the operation to perform.
let operation = randomElement(probability(0.5) ? ALL_NUMBER_OPERATIONS : ALL_NUMBER_OPERATIONS_AND_COMPARISONS);
let action = new Action(operation);
if (includes(COMPARISON_OPS, operation)) {
if (isNaN(n)) {
// In that case, regular comparisons don't make sense, so just test for isNaN instead.
action.operation = OP_TEST_IS_NAN;
} else if (!isFinite(n)) {
// Similar to the NaN case, just test for isFinite here.
action.operation = OP_TEST_IS_FINITE;
} else {
push(action.inputs, Inputs.randomNumberCloseTo(n));
}
} else if (includes(SHIFT_OPS, operation)) {
push(action.inputs, Inputs.randomIntBetween(1, 32));
} else if (includes(BITWISE_OPS, operation)) {
push(action.inputs, Inputs.randomInt());
} else if (includes(ARITHMETIC_OPS, operation)) {
if (isInteger(n)) {
push(action.inputs, Inputs.randomInt());
} else {
push(action.inputs, Inputs.randomNumber());
}
}
return action;
}
const ALL_BIGINT_OPERATIONS = concat(BIGINT_SHIFT_OPS, BITWISE_OPS, ARITHMETIC_OPS, UNARY_OPS);
const ALL_BIGINT_OPERATIONS_AND_COMPARISONS = concat(ALL_BIGINT_OPERATIONS, COMPARISON_OPS);
function exploreBigint(b) {
// Somewhat arbitrarily give comparisons a lower probability when choosing the operation to perform.
let operation = randomElement(probability(0.5) ? ALL_BIGINT_OPERATIONS : ALL_BIGINT_OPERATIONS_AND_COMPARISONS);
let action = new Action(operation);
if (includes(COMPARISON_OPS, operation)) {
push(action.inputs, Inputs.randomBigintCloseTo(b));
} else if (includes(BIGINT_SHIFT_OPS, operation)) {
push(action.inputs, Inputs.randomBigintBetween(1n, 128n));
} else if (includes(BITWISE_OPS, operation) || includes(ARITHMETIC_OPS, operation)) {
push(action.inputs, Inputs.randomBigint());
}
return action;
}
function exploreSymbol(s) {
// Lookup or insert the symbol into the global symbol registry. This will also allow static typing of the output.
return new Action(OP_SYMBOL_REGISTRATION);
}
const ALL_BOOLEAN_OPERATIONS = concat(BOOLEAN_BINARY_OPS, BOOLEAN_UNARY_OPS);
function exploreBoolean(b) {
let operation = randomElement(ALL_BOOLEAN_OPERATIONS);
let action = new Action(operation);
if (includes(BOOLEAN_BINARY_OPS, operation)) {
// It probably doesn't make sense to hardcode boolean constants, so always use an existing argument.
push(action.inputs, Inputs.randomArgument());
}
return action;
}
// Explores the given value and returns an action to perform on it.
function exploreValue(id, v) {
if (isObject(v)) {
return exploreObject(v);
} else if (isFunction(v)) {
return exploreFunction(v);
} else if (isString(v)) {
return exploreString(v);
} else if (isNumber(v)) {
return exploreNumber(v);
} else if (isBigint(v)) {
return exploreBigint(v);
} else if (isSymbol(v)) {
return exploreSymbol(v);
} else if (isBoolean(v)) {
return exploreBoolean(v);
} else if (isUndefined(v)) {
// Can't do anything with undefined.
return NO_ACTION;
} else {
throw "Unexpected value type: " + typeof v;
}
}
//
// Execution of actions determined through exploration.
//
// Handlers for all supported operations;
const actionHandlers = {
[OP_CALL_FUNCTION]: (v, inputs) => apply(v, currentThis, inputs),
[OP_CONSTRUCT]: (v, inputs) => construct(v, inputs),
[OP_CALL_METHOD]: (v, inputs) => { let m = shift(inputs); apply(v[m], v, inputs); },
[OP_CONSTRUCT_MEMBER]: (v, inputs) => { let m = shift(inputs); construct(v[m], inputs); },
[OP_GET_PROPERTY]: (v, inputs) => v[inputs[0]],
[OP_SET_PROPERTY]: (v, inputs) => v[inputs[0]] = inputs[1],
[OP_DEFINE_PROPERTY]: (v, inputs) => v[inputs[0]] = inputs[1],
[OP_GET_ELEMENT]: (v, inputs) => v[inputs[0]],
[OP_SET_ELEMENT]: (v, inputs) => v[inputs[0]] = inputs[1],
[OP_ADD]: (v, inputs) => v + inputs[0],
[OP_SUB]: (v, inputs) => v - inputs[0],
[OP_MUL]: (v, inputs) => v * inputs[0],
[OP_DIV]: (v, inputs) => v / inputs[0],
[OP_MOD]: (v, inputs) => v % inputs[0],
[OP_INC]: (v, inputs) => v++,
[OP_DEC]: (v, inputs) => v--,
[OP_NEG]: (v, inputs) => -v,
[OP_LOGICAL_AND]: (v, inputs) => v && inputs[0],
[OP_LOGICAL_OR]: (v, inputs) => v || inputs[0],
[OP_LOGICAL_NOT]: (v, inputs) => !v,
[OP_BITWISE_AND]: (v, inputs) => v & inputs[0],
[OP_BITWISE_OR]: (v, inputs) => v | inputs[0],
[OP_BITWISE_XOR]: (v, inputs) => v ^ inputs[0],
[OP_LEFT_SHIFT]: (v, inputs) => v << inputs[0],
[OP_SIGNED_RIGHT_SHIFT]: (v, inputs) => v >> inputs[0],
[OP_UNSIGNED_RIGHT_SHIFT]: (v, inputs) => v >>> inputs[0],
[OP_BITWISE_NOT]: (v, inputs) => ~v,
[OP_COMPARE_EQUAL]: (v, inputs) => v == inputs[0],
[OP_COMPARE_STRICT_EQUAL]: (v, inputs) => v === inputs[0],
[OP_COMPARE_NOT_EQUAL]: (v, inputs) => v != inputs[0],
[OP_COMPARE_STRICT_NOT_EQUAL]: (v, inputs) => v !== inputs[0],
[OP_COMPARE_GREATER_THAN]: (v, inputs) => v > inputs[0],
[OP_COMPARE_LESS_THAN]: (v, inputs) => v < inputs[0],
[OP_COMPARE_GREATER_THAN_OR_EQUAL]: (v, inputs) => v >= inputs[0],
[OP_COMPARE_LESS_THAN_OR_EQUAL]: (v, inputs) => v <= inputs[0],
[OP_TEST_IS_NAN]: (v, inputs) => Number.isNaN(v),
[OP_TEST_IS_FINITE]: (v, inputs) => Number.isFinite(v),
[OP_SYMBOL_REGISTRATION]: (v, inputs) => Symbol.for(v.description),
};
// Performs the given action on the given value. Returns true on success, false otherwise.
function perform(v, action) {
if (action === NO_ACTION) {
return true;
}
// Compute the concrete inputs: the actual runtime values of all inputs.
let concreteInputs = EmptyArray();
for (let i = 0; i < action.inputs.length; i++) {
let input = action.inputs[i];
if (input instanceof ArgumentInput) {
push(concreteInputs, exploreArguments[input.argumentIndex]);
} else if (input instanceof BigintInput) {
// These need special handling because BigInts cannot be serialized into JSON, so are stored as strings.
push(concreteInputs, makeBigInt(input.bigintValue));
} else {
let value = propertyValues(input)[0];
if (isUndefined(value)) throw "Unexpectedly obtained 'undefined' as concrete input";
push(concreteInputs, value);
}
}
let handler = actionHandlers[action.operation];
if (isUndefined(handler)) throw "Unhandled operation " + action.operation;
try {
handler(v, concreteInputs);
} catch (e) {
return false;
}
return true;
}
//
// Exploration entrypoint.
//
function explore(id, v, thisValue, args) {
// The given arguments may be used as inputs for the action.
if (isUndefined(args) || args.length < 1) throw "Exploration requires at least one additional argument";
exploreArguments = args;
currentThis = thisValue;
// We may get here recursively for example if a Proxy is being explored which triggers further explore calls during e.g. property enumeration.
// Probably the best way to deal with these cases is to just bail out from recursive explorations.
if (currentlyExploring) return;
currentlyExploring = true;
// Check if we already have a result for this id, and if so repeat the same action again. Otherwise, explore.
let action;
if (hasActionFor(id)) {
action = getActionFor(id);
} else {
action = exploreValue(id, v);
recordAction(id, action);
}
// Now perform the selected action on the value.
let success = perform(v, action);
// If the action failed, mark this explore operation as failing so it won't be retried.
if (!success) {
recordFailure(id);
}
currentlyExploring = false;
}
function exploreWithErrorHandling(id, v, thisValue, args) {
try {
explore(id, v, thisValue, args);
} catch (e) {
let line = tryHasProperty('line', e) ? tryGetProperty('line', e) : tryGetProperty('lineNumber', e);
if (isNumber(line)) {
reportError("In line " + line + ": " + e);
} else {
reportError(e);
}
}
}
return exploreWithErrorHandling;
})();
"""
static let exploreFunc = "explore"
}
| apache-2.0 | e5f4aee8f64986822c0a32c2525a2f79 | 47.812709 | 546 | 0.572433 | 4.414255 | false | false | false | false |
lokinfey/MyPerfectframework | Examples/Authenticator/Authenticator Client/ViewController.swift | 1 | 982 | //
// ViewController.swift
// Authenticator Client
//
// Created by Kyle Jessup on 2015-11-11.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction
func unwindToView(unwindSegue: UIStoryboardSegue) {
}
}
| apache-2.0 | 49a5c7e527d280c2621dc37c3074908a | 24.153846 | 80 | 0.609582 | 4.762136 | false | false | false | false |
matthewpurcell/firefox-ios | Utils/Extensions/UIImageExtensions.swift | 5 | 1512 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
private let imageLock = NSLock()
extension UIImage {
/// Despite docs that say otherwise, UIImage(data: NSData) isn't thread-safe (see bug 1223132).
/// As a workaround, synchronize access to this initializer.
/// This fix requires that you *always* use this over UIImage(data: NSData)!
public static func imageFromDataThreadSafe(data: NSData) -> UIImage? {
imageLock.lock()
let image = UIImage(data: data)
imageLock.unlock()
return image
}
public static func createWithColor(size: CGSize, color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
let rect = CGRect(origin: CGPointZero, size: size)
color.setFill()
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public func createScaled(size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
drawInRect(CGRect(origin: CGPoint(x: 0, y: 0), size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
| mpl-2.0 | f221c7582e2423df540478e952b85fb2 | 37.769231 | 99 | 0.687169 | 4.909091 | false | false | false | false |
to4iki/conference-app-2017-ios | conference-app-2017/presentation/viewController/InformationViewController+QRCodeReader.swift | 1 | 3266 | import UIKit
import AVFoundation
import QRCodeReader
extension InformationViewController {
func presentQRCodeReader(animated: Bool, completion: (() -> Void)?) {
guard checkScanPermissions() else { return }
present(readerViewController, animated: animated, completion: completion)
}
fileprivate func presentOpenURLDialog(url: URL) {
let alert = UIAlertController(title: "Result", message: url.absoluteString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Open", style: .default, handler: { [weak self] _ in
self?.presentSafariViewController(url: url, animated: true) })
)
present(alert, animated: true, completion: nil)
}
private func openSettingApp() {
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
} else {
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
}
}
private func checkScanPermissions() -> Bool {
do {
return try QRCodeReader.supportsMetadataObjectTypes()
} catch let error as NSError {
log.error("error: \(error.localizedDescription)")
var alert = Alert.Builder().set(title: "Error")
switch error.code {
case -11852:
let action = UIAlertAction(title: "Setting", style: .default, handler: { _ in
DispatchQueue.main.async {
self.openSettingApp()
}
})
alert = alert
.set(message: error.localizedDescription)
.set(action: action)
.set(action: UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
case -11814:
alert = alert
.set(message: error.localizedDescription)
.set(action: UIAlertAction(title: "OK", style: .cancel, handler: nil))
default:
alert = alert
.set(message: error.localizedDescription)
.set(action: UIAlertAction(title: "OK", style: .cancel, handler: nil))
}
alert.present(animated: true, completion: nil)
return false
}
}
}
// MARK: - QRCodeReaderViewControllerDelegate
extension InformationViewController: QRCodeReaderViewControllerDelegate {
func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
reader.stopScanning()
dismiss(animated: false) { [weak self] in
guard let url = URL(string: result.value) else { return }
self?.presentOpenURLDialog(url: url)
}
}
func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) {
if let cameraName = newCaptureDevice.device.localizedName {
log.debug("Switching capturing to: \(cameraName)")
}
}
func readerDidCancel(_ reader: QRCodeReaderViewController) {
reader.stopScanning()
dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | 005715731d62100bd33551018e898397 | 39.825 | 111 | 0.609308 | 5.111111 | false | false | false | false |
Under100/ABOnboarding | Pod/Classes/ABOnboardingSettings.swift | 1 | 1230 | //
// ABOnboardingSettings.swift
// ABOnboarding
//
// Created by Adam Boyd on 2016-04-02.
//
//
import Foundation
import UIKit
public struct ABOnboardingSettings {
//Background and text
public static var OnboardingBackground = UIColor.whiteColor()
public static var OnboardingNextButtonBackground = UIColor.whiteColor()
public static var OnboardingText = UIColor.grayColor()
public static var OnboardingLaterText = UIColor.grayColor()
public static var BackgroundWhileOnboarding = UIColor.blackColor().colorWithAlphaComponent(0.85)
public static var Font = UIFont.systemFontOfSize(16)
//Rounded button
public static var ButtonBackgroundNormal = UIColor.redColor()
public static var ButtonBackgroundHighlighted = UIColor.clearColor()
public static var ButtonTextNormal = UIColor.whiteColor()
public static var ButtonTextHighlighted = UIColor.grayColor()
public static var ButtonBorderNormal = UIColor.clearColor()
public static var ButtonBorderHighlighted = UIColor.grayColor()
public static var ViewToShowOnboarding: UIView?
public static var AnimationDuration: NSTimeInterval = 0.5
public static var TouchesDisabledOnUncoveredRect: Bool = true
} | mit | 2925ec5d921c1da3d7cd770d471c9480 | 37.46875 | 100 | 0.768293 | 5 | 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.