hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
fc4caac59b1eb743cf07a136fded9edd4e81e38e | 3,731 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
// swiftlint:disable cyclomatic_complexity
extension Amplify {
/// Resets the state of the Amplify framework.
///
/// Internally, this method:
/// - Invokes `reset` on each configured category, which clears that categories registered plugins.
/// - Releases each configured category, and replaces the instances referred to by the static accessor properties
/// (e.g., `Amplify.Hub`) with new instances. These instances must subsequently have providers added, and be
/// configured prior to use.
static func reset() {
// Looping through all categories to ensure we don't accidentally forget a category at some point in the future
let group = DispatchGroup()
for categoryType in CategoryType.allCases {
switch categoryType {
case .analytics:
reset(Analytics, in: group) { group.leave() }
case .api:
reset(API, in: group) { group.leave() }
case .auth:
reset(Auth, in: group) { group.leave() }
case .dataStore:
reset(DataStore, in: group) { group.leave() }
case .geo:
reset(Geo, in: group) { group.leave() }
case .storage:
reset(Storage, in: group) { group.leave() }
case .predictions:
reset(Predictions, in: group) { group.leave() }
case .hub, .logging:
// Hub and Logging should be reset after all other categories
break
}
}
group.wait()
for categoryType in CategoryType.allCases {
switch categoryType {
case .hub:
reset(Hub, in: group) { group.leave() }
case .logging:
reset(Logging, in: group) { group.leave() }
default:
break
}
}
if #available(iOS 13.0.0, *) {
devMenu = nil
}
group.wait()
// Initialize Logging and Hub first, to ensure their default plugins are registered and available to other
// categories during their initialization and configuration phases.
Logging = LoggingCategory()
Hub = HubCategory()
// Switch over all category types to ensure we don't forget any
for categoryType in CategoryType.allCases.filter({ $0 != .logging && $0 != .hub }) {
switch categoryType {
case .logging, .hub:
// Initialized above
break
case .analytics:
Analytics = AnalyticsCategory()
case .api:
API = AmplifyAPICategory()
case .auth:
Auth = AuthCategory()
case .dataStore:
DataStore = DataStoreCategory()
case .geo:
Geo = GeoCategory()
case .predictions:
Predictions = PredictionsCategory()
case .storage:
Storage = StorageCategory()
}
}
isConfigured = false
}
/// If `candidate` is `Resettable`, `enter()`s `group`, then invokes `candidate.reset(onComplete)` on a background
/// queue. If `candidate` is not resettable, exits without invoking `onComplete`.
private static func reset(_ candidate: Any, in group: DispatchGroup, onComplete: @escaping BasicClosure) {
guard let resettable = candidate as? Resettable else {
return
}
group.enter()
resettable.reset(onComplete: onComplete)
}
}
| 34.229358 | 119 | 0.560172 |
5bcd1bff24035be986894db870216b4492b2608e | 278 | class RoundRect: Locus {
let rect: Rect
let rx: Double
let ry: Double
init(rect: Rect, rx: Double = 0, ry: Double = 0) {
self.rect = rect
self.rx = rx
self.ry = ry
}
override func bounds() -> Rect {
return rect
}
}
| 16.352941 | 54 | 0.510791 |
e4130c5cdf245cd29575ae60b2fc3247c5a3e723 | 18,737 | //
// CastClient.swift
// OpenCastSwift
//
// Created by Miles Hollingsworth on 4/22/18
// Copyright © 2018 Miles Hollingsworth. All rights reserved.
//
import Foundation
import SwiftProtobuf
import SwiftyJSON
public enum CastPayload {
case json([String: Any])
case data(Data)
init(_ json: [String: Any]) {
self = .json(json)
}
init(_ data: Data) {
self = .data(data)
}
}
typealias CastMessage = Extensions_Api_CastChannel_CastMessage
public typealias CastResponseHandler = (Result<JSON, CastError>) -> Void
public enum CastError: Error {
case connection(String)
case write(String)
case session(String)
case request(String)
case launch(String)
case load(String)
}
public class CastRequest: NSObject {
var id: Int
var namespace: String
var destinationId: String
var payload: CastPayload
init(id: Int, namespace: String, destinationId: String, payload: [String: Any]) {
self.id = id
self.namespace = namespace
self.destinationId = destinationId
self.payload = CastPayload(payload)
}
init(id: Int, namespace: String, destinationId: String, payload: Data) {
self.id = id
self.namespace = namespace
self.destinationId = destinationId
self.payload = CastPayload(payload)
}
}
@objc public protocol CastClientDelegate: class {
@objc optional func castClient(_ client: CastClient, willConnectTo device: CastDevice)
@objc optional func castClient(_ client: CastClient, didConnectTo device: CastDevice)
@objc optional func castClient(_ client: CastClient, didDisconnectFrom device: CastDevice)
@objc optional func castClient(_ client: CastClient, connectionTo device: CastDevice, didFailWith error: Error?)
@objc optional func castClient(_ client: CastClient, deviceStatusDidChange status: CastStatus)
@objc optional func castClient(_ client: CastClient, mediaStatusDidChange status: CastMediaStatus)
}
public final class CastClient: NSObject, RequestDispatchable, Channelable {
public let device: CastDevice
public weak var delegate: CastClientDelegate?
public var connectedApp: CastApp?
public private(set) var currentStatus: CastStatus? {
didSet {
guard let status = currentStatus else { return }
if oldValue != status {
DispatchQueue.main.async {
self.delegate?.castClient?(self, deviceStatusDidChange: status)
self.statusDidChange?(status)
}
}
}
}
public private(set) var currentMediaStatus: CastMediaStatus? {
didSet {
guard let status = currentMediaStatus else { return }
if oldValue != status {
DispatchQueue.main.async {
self.delegate?.castClient?(self, mediaStatusDidChange: status)
self.mediaStatusDidChange?(status)
}
}
}
}
public private(set) var currentMultizoneStatus: CastMultizoneStatus?
public var statusDidChange: ((CastStatus) -> Void)?
public var mediaStatusDidChange: ((CastMediaStatus) -> Void)?
public init(device: CastDevice) {
self.device = device
super.init()
}
deinit {
disconnect()
}
// MARK: - Socket Setup
public var isConnected = false {
didSet {
if oldValue != isConnected {
if isConnected {
DispatchQueue.main.async { self.delegate?.castClient?(self, didConnectTo: self.device) }
} else {
DispatchQueue.main.async { self.delegate?.castClient?(self, didDisconnectFrom: self.device) }
}
}
}
}
private var inputStream: InputStream! {
didSet {
if let inputStream = inputStream {
reader = CastV2PlatformReader(stream: inputStream)
} else {
reader = nil
}
}
}
private var outputStream: OutputStream!
fileprivate lazy var socketQueue = DispatchQueue.global(qos: .userInitiated)
public func connect() {
socketQueue.async {
do {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let settings: [String: Any] = [
kCFStreamSSLValidatesCertificateChain as String: false,
kCFStreamSSLLevel as String: kCFStreamSocketSecurityLevelTLSv1,
kCFStreamPropertyShouldCloseNativeSocket as String: true
]
CFStreamCreatePairWithSocketToHost(nil, self.device.hostName as CFString, UInt32(self.device.port), &readStream, &writeStream)
guard let readStreamRetained = readStream?.takeRetainedValue() else {
throw CastError.connection("Unable to create input stream")
}
guard let writeStreamRetained = writeStream?.takeRetainedValue() else {
throw CastError.connection("Unable to create output stream")
}
DispatchQueue.main.async { self.delegate?.castClient?(self, willConnectTo: self.device) }
CFReadStreamSetProperty(readStreamRetained, CFStreamPropertyKey(kCFStreamPropertySSLSettings), settings as CFTypeRef?)
CFWriteStreamSetProperty(writeStreamRetained, CFStreamPropertyKey(kCFStreamPropertySSLSettings), settings as CFTypeRef?)
self.inputStream = readStreamRetained
self.outputStream = writeStreamRetained
self.inputStream.delegate = self
self.inputStream.schedule(in: .current, forMode: RunLoop.Mode.default)
self.outputStream.schedule(in: .current, forMode: RunLoop.Mode.default)
self.inputStream.open()
self.outputStream.open()
RunLoop.current.run()
} catch {
DispatchQueue.main.async { self.delegate?.castClient?(self, connectionTo: self.device, didFailWith: error as NSError) }
}
}
}
public func disconnect() {
if isConnected {
isConnected = false
}
channels.values.forEach(remove)
socketQueue.async {
if self.inputStream != nil {
self.inputStream.close()
self.inputStream.remove(from: RunLoop.current, forMode: RunLoop.Mode.default)
self.inputStream = nil
}
if self.outputStream != nil {
self.outputStream.close()
self.outputStream.remove(from: RunLoop.current, forMode: RunLoop.Mode.default)
self.outputStream = nil
}
}
}
// MARK: - Socket Lifecycle
private func write(data: Data) throws {
var payloadSize = UInt32(data.count).bigEndian
let packet = NSMutableData(bytes: &payloadSize, length: MemoryLayout<UInt32>.size)
packet.append(data)
let streamBytes = packet.bytes.bindMemory(to: UInt8.self, capacity: data.count)
if outputStream.write(streamBytes, maxLength: packet.length) < 0 {
if let error = outputStream.streamError {
throw CastError.write("Error writing \(packet.length) byte(s) to stream: \(error)")
} else {
throw CastError.write("Unknown error writing \(packet.length) byte(s) to stream")
}
}
}
fileprivate func sendConnectMessage() throws {
guard outputStream != nil else { return }
_ = connectionChannel
DispatchQueue.main.async {
_ = self.receiverControlChannel
_ = self.mediaControlChannel
_ = self.heartbeatChannel
if self.device.capabilities.contains(.multizoneGroup) {
_ = self.multizoneControlChannel
}
}
}
private var reader: CastV2PlatformReader?
fileprivate func readStream() {
do {
reader?.readStream()
while let payload = reader?.nextMessage() {
let message = try CastMessage(serializedData: payload)
guard let channel = channels[message.namespace] else {
print("No channel attached for namespace \(message.namespace)")
return
}
switch message.payloadType {
case .string:
if let messageData = message.payloadUtf8.data(using: .utf8) {
let json = JSON(messageData)
channel.handleResponse(json,
sourceId: message.sourceID)
if let requestId = json[CastJSONPayloadKeys.requestId].int {
callResponseHandler(for: requestId, with: Result.success(json))
}
} else {
NSLog("Unable to get UTF8 JSON data from message")
}
case .binary:
channel.handleResponse(message.payloadBinary,
sourceId: message.sourceID)
}
}
} catch {
NSLog("Error reading: \(error)")
}
}
//MARK: - Channelable
var channels = [String: CastChannel]()
private lazy var heartbeatChannel: HeartbeatChannel = {
let channel = HeartbeatChannel()
self.add(channel: channel)
return channel
}()
private lazy var connectionChannel: DeviceConnectionChannel = {
let channel = DeviceConnectionChannel()
self.add(channel: channel)
return channel
}()
private lazy var receiverControlChannel: ReceiverControlChannel = {
let channel = ReceiverControlChannel()
self.add(channel: channel)
return channel
}()
private lazy var mediaControlChannel: MediaControlChannel = {
let channel = MediaControlChannel()
self.add(channel: channel)
return channel
}()
private lazy var multizoneControlChannel: MultizoneControlChannel = {
let channel = MultizoneControlChannel()
self.add(channel: channel)
return channel
}()
// MARK: - Request response
private lazy var currentRequestId = Int(arc4random_uniform(800))
func nextRequestId() -> Int {
currentRequestId += 1
return currentRequestId
}
private let senderName: String = "sender-\(UUID().uuidString)"
private var responseHandlers = [Int: CastResponseHandler]()
func send(_ request: CastRequest, response: CastResponseHandler?) {
if let response = response {
responseHandlers[request.id] = response
}
do {
let messageData = try CastMessage.encodedMessage(payload: request.payload,
namespace: request.namespace,
sourceId: senderName,
destinationId: request.destinationId)
try write(data: messageData)
} catch {
callResponseHandler(for: request.id, with: Result.failure(.request(error.localizedDescription)))
}
}
private func callResponseHandler(for requestId: Int, with result: Result<JSON, CastError>) {
DispatchQueue.main.async {
if let handler = self.responseHandlers.removeValue(forKey: requestId) {
handler(result)
}
}
}
// MARK: - Public messages
public func getAppAvailability(apps: [CastApp], completion: @escaping (Result<AppAvailability, CastError>) -> Void) {
guard outputStream != nil else { return }
receiverControlChannel.getAppAvailability(apps: apps, completion: completion)
}
public func join(app: CastApp? = nil, completion: @escaping (Result<CastApp, CastError>) -> Void) {
guard outputStream != nil,
let target = app ?? currentStatus?.apps.first else {
completion(Result.failure(CastError.session("No Apps Running")))
return
}
if target == connectedApp {
completion(Result.success(target))
} else if let existing = currentStatus?.apps.first(where: { $0.id == target.id }) {
connect(to: existing)
completion(Result.success(existing))
} else {
receiverControlChannel.requestStatus { [weak self] result in
switch result {
case .success(let status):
guard let app = status.apps.first else {
completion(Result.failure(CastError.launch("Unable to get launched app instance")))
return
}
self?.connect(to: app)
completion(Result.success(app))
case .failure(let error):
completion(Result.failure(error))
}
}
}
}
public func launch(appId: String, completion: @escaping (Result<CastApp, CastError>) -> Void) {
guard outputStream != nil else { return }
receiverControlChannel.launch(appId: appId) { [weak self] result in
switch result {
case .success(let app):
self?.connect(to: app)
fallthrough
default:
completion(result)
}
}
}
public func stopCurrentApp() {
guard outputStream != nil, let app = currentStatus?.apps.first else { return }
receiverControlChannel.stop(app: app)
}
public func leave(_ app: CastApp) {
guard outputStream != nil else { return }
connectionChannel.leave(app)
connectedApp = nil
}
public func load(media: CastMedia, with app: CastApp, completion: @escaping (Result<CastMediaStatus, CastError>) -> Void) {
guard outputStream != nil else { return }
mediaControlChannel.load(media: media, with: app, completion: completion)
}
public func requestMediaStatus(for app: CastApp, completion: ((Result<CastMediaStatus, CastError>) -> Void)? = nil) {
guard outputStream != nil else { return }
mediaControlChannel.requestMediaStatus(for: app)
}
private func connect(to app: CastApp) {
guard outputStream != nil else { return }
connectionChannel.connect(to: app)
connectedApp = app
}
public func pause() {
guard outputStream != nil, let app = connectedApp else { return }
if let mediaStatus = currentMediaStatus {
mediaControlChannel.sendPause(for: app, mediaSessionId: mediaStatus.mediaSessionId)
} else {
mediaControlChannel.requestMediaStatus(for: app) { result in
switch result {
case .success(let mediaStatus):
self.mediaControlChannel.sendPause(for: app, mediaSessionId: mediaStatus.mediaSessionId)
case .failure(let error):
print(error)
}
}
}
}
public func play() {
guard outputStream != nil, let app = connectedApp else { return }
if let mediaStatus = currentMediaStatus {
mediaControlChannel.sendPlay(for: app, mediaSessionId: mediaStatus.mediaSessionId)
} else {
mediaControlChannel.requestMediaStatus(for: app) { result in
switch result {
case .success(let mediaStatus):
self.mediaControlChannel.sendPlay(for: app, mediaSessionId: mediaStatus.mediaSessionId)
case .failure(let error):
print(error)
}
}
}
}
public func stop() {
guard outputStream != nil, let app = connectedApp else { return }
if let mediaStatus = currentMediaStatus {
mediaControlChannel.sendStop(for: app, mediaSessionId: mediaStatus.mediaSessionId)
} else {
mediaControlChannel.requestMediaStatus(for: app) { result in
switch result {
case .success(let mediaStatus):
self.mediaControlChannel.sendStop(for: app, mediaSessionId: mediaStatus.mediaSessionId)
case .failure(let error):
print(error)
}
}
}
}
public func seek(to currentTime: Float) {
guard outputStream != nil, let app = connectedApp else { return }
if let mediaStatus = currentMediaStatus {
mediaControlChannel.sendSeek(to: currentTime, for: app, mediaSessionId: mediaStatus.mediaSessionId)
} else {
mediaControlChannel.requestMediaStatus(for: app) { result in
switch result {
case .success(let mediaStatus):
self.mediaControlChannel.sendSeek(to: currentTime, for: app, mediaSessionId: mediaStatus.mediaSessionId)
case .failure(let error):
print(error)
}
}
}
}
public func setVolume(_ volume: Float) {
guard outputStream != nil else { return }
receiverControlChannel.setVolume(volume)
}
public func setMuted(_ muted: Bool) {
guard outputStream != nil else { return }
receiverControlChannel.setMuted(muted)
}
public func setVolume(_ volume: Float, for device: CastMultizoneDevice) {
guard device.capabilities.contains(.multizoneGroup) else {
print("Attempted to set zone volume on non-multizone device")
return
}
multizoneControlChannel.setVolume(volume, for: device)
}
public func setMuted(_ isMuted: Bool, for device: CastMultizoneDevice) {
guard device.capabilities.contains(.multizoneGroup) else {
print("Attempted to mute zone on non-multizone device")
return
}
multizoneControlChannel.setMuted(isMuted, for: device)
}
}
extension CastClient: StreamDelegate {
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event.openCompleted:
guard !isConnected else { return }
socketQueue.async {
do {
try self.sendConnectMessage()
} catch {
NSLog("Error sending connect message: \(error)")
}
}
case Stream.Event.errorOccurred:
NSLog("Stream error occurred: \(aStream.streamError.debugDescription)")
DispatchQueue.main.async {
self.delegate?.castClient?(self, connectionTo: self.device, didFailWith: aStream.streamError)
}
case Stream.Event.hasBytesAvailable:
socketQueue.async {
self.readStream()
}
case Stream.Event.endEncountered:
NSLog("Input stream ended")
disconnect()
default: break
}
}
}
extension CastClient: ReceiverControlChannelDelegate {
func channel(_ channel: ReceiverControlChannel, didReceive status: CastStatus) {
currentStatus = status
}
}
extension CastClient: MediaControlChannelDelegate {
func channel(_ channel: MediaControlChannel, didReceive mediaStatus: CastMediaStatus) {
currentMediaStatus = mediaStatus
}
}
extension CastClient: HeartbeatChannelDelegate {
func channelDidConnect(_ channel: HeartbeatChannel) {
if !isConnected {
isConnected = true
}
}
func channelDidTimeout(_ channel: HeartbeatChannel) {
disconnect()
currentStatus = nil
currentMediaStatus = nil
connectedApp = nil
}
}
extension CastClient: MultizoneControlChannelDelegate {
func channel(_ channel: MultizoneControlChannel, added device: CastMultizoneDevice) {
}
func channel(_ channel: MultizoneControlChannel, updated device: CastMultizoneDevice) {
}
func channel(_ channel: MultizoneControlChannel, removed deviceId: String) {
}
func channel(_ channel: MultizoneControlChannel, didReceive status: CastMultizoneStatus) {
currentMultizoneStatus = status
}
}
| 29.788553 | 134 | 0.653627 |
790031a8226ff0a3a900288147f1df9eccdc3019 | 20,616 | //
// SAIInputAccessoryViewLayout.swift
// SAIInputBar
//
// Created by SAGESSE on 8/3/16.
// Copyright © 2016-2017 SAGESSE. All rights reserved.
//
import UIKit
internal class SAIInputAccessoryViewLayout: UICollectionViewLayout {
class Line {
var frame: CGRect
var inset: UIEdgeInsets
var section: Int
var attributes: [Attributes]
var cacheMaxWidth: CGFloat?
var cacheMaxHeight: CGFloat?
init(_ firstItem: Attributes, _ inset: UIEdgeInsets = .zero) {
self.frame = firstItem.frame
self.section = firstItem.indexPath.section
self.inset = inset
self.attributes = [firstItem]
}
func addItem(_ item: Attributes, _ spacing: CGFloat) {
let x = min(frame.minX, item.frame.minX)
let y = min(frame.minY, item.frame.minY)
let width = frame.width + spacing + item.size.width
let height = max(frame.height, item.size.height)
frame = CGRect(x: x, y: y, width: width, height: height)
attributes.append(item)
}
func canAddItem(_ item: Attributes, _ width: CGFloat, _ spacing: CGFloat) -> Bool {
let nWidth = frame.width + spacing + item.size.width
return nWidth <= width - inset.left - inset.right
}
func move(toPoint point: CGPoint) {
let dx = point.x - frame.minX
let dy = point.y - frame.minY
attributes.forEach {
$0.frame = $0.frame.offsetBy(dx: dx, dy: dy)
}
frame.origin = point
}
func layout(atPoint point: CGPoint, maxWidth: CGFloat, maxHeight: CGFloat, _ spacing: CGFloat) {
// 如果布局没有改变直接移动就好了
if cacheMaxWidth == maxWidth && cacheMaxHeight == maxHeight {
move(toPoint: point)
return
}
frame.origin = point
var left: CGFloat = 0
var right: CGFloat = 0
var sp: CGFloat = -1
var lsp: CGFloat = inset.left
var rsp: CGFloat = inset.right
var centerCount = 0
var centerWidth = CGFloat(0)
// vertical alignment
let alignY = { (item: Attributes) -> CGFloat in
if item.alignemt.contains(.Top) {
// aligned to the top
return 0
}
if item.alignemt.contains(.VResize) {
// resize
return 0
}
if item.alignemt.contains(.Bottom) {
// aligned to the bottom
return maxHeight - item.size.height
}
// aligned to the center
return (maxHeight - item.size.height) / 2
}
// 从右边开始计算一直到第一个非Right的元素
_ = attributes.reversed().index {
if $0.alignemt.contains(.Right) {
// aligned to the right
let nx = point.x + (maxWidth - right - rsp - $0.size.width)
let ny = point.y + (alignY($0))
$0.frame = CGRect(x: nx, y: ny, width: $0.size.width, height: $0.size.height)
right = $0.size.width + rsp + right
rsp = spacing
return false
}
if $0.alignemt.contains(.HCenter) {
centerCount += 1
centerWidth += $0.size.width
return false
}
return true
}
// 然后从左边开始计算到右边第一个非right
_ = attributes.index {
if $0.alignemt.contains(.Right) {
return true
}
if $0.alignemt.contains(.Left) {
// aligned to the left
let nx = point.x + (left + lsp)
let ny = point.y + (alignY($0))
$0.frame = CGRect(x: nx, y: ny, width: $0.size.width, height: $0.size.height)
left = left + lsp + $0.size.width
lsp = spacing
} else if $0.alignemt.contains(.HResize) {
// resize
let nx = point.x + (left + lsp)
let ny = point.y + (alignY($0))
let nwidth = maxWidth - left - lsp - right - rsp
let nheight = max(maxHeight, $0.size.height)
$0.frame = CGRect(x: nx, y: ny, width: nwidth, height: nheight)
left = left + lsp + nwidth
lsp = spacing
} else {
// NOTE: center must be calculated finally
if sp < 0 {
sp = (maxWidth - right - left - centerWidth) / CGFloat(centerCount + 1)
}
// aligned to the center
let nx = point.x + (left + sp)
let ny = point.y + (alignY($0))
$0.frame = CGRect(x: nx, y: ny, width: $0.size.width, height: $0.size.height)
left = left + sp + $0.size.width
}
return false
}
// 缓存
cacheMaxWidth = maxWidth
cacheMaxHeight = maxHeight
}
}
struct Alignment: OptionSet {
var rawValue: Int
static var None = Alignment(rawValue: 0x0000)
static var Top = Alignment(rawValue: 0x0100)
static var Bottom = Alignment(rawValue: 0x0200)
static var VCenter = Alignment(rawValue: 0x0400)
static var VResize = Alignment(rawValue: 0x0800)
static var Left = Alignment(rawValue: 0x0001)
static var Right = Alignment(rawValue: 0x0002)
static var HCenter = Alignment(rawValue: 0x0004)
static var HResize = Alignment(rawValue: 0x0008)
}
class Attributes: UICollectionViewLayoutAttributes {
var item: SAIInputItem?
var alignemt: Alignment = .None
var cacheSize: CGSize?
}
// MARK: Property
var minimumLineSpacing: CGFloat = 8
var minimumInteritemSpacing: CGFloat = 8
var contentInsets: UIEdgeInsets {
if isIPhoneX {
return UIEdgeInsets.init(top: 8, left: 10, bottom: 20, right: 10)
}
return UIEdgeInsets.init(top: 8, left: 10, bottom: 8, right: 10)
}
// MARK: Invalidate
override func prepare() {
super.prepare()
}
override var collectionViewContentSize: CGSize {
return collectionView?.frame.size ?? CGSize.zero
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if collectionView?.frame.width != newBounds.width {
return true
}
return false
}
override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) {
super.invalidateLayout(with: context)
_invalidateLayoutCache(context.invalidateEverything)
}
// MAKR: Layout
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return _layoutIfNeed(inRect: rect)
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return _layoutAttributesForItemAtIndexPath(indexPath)
}
// MARK: Change Animation
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
super.prepare(forCollectionViewUpdates: updateItems)
updateItems.forEach {
switch $0.updateAction {
case .insert:
add.insert($0.indexPathAfterUpdate!)
case .delete:
rm.insert($0.indexPathBeforeUpdate!)
case .reload:
reload.insert($0.indexPathAfterUpdate!)
//rm.insert($0.indexPathBeforeUpdate!)
default:
break
}
}
}
override func finalizeCollectionViewUpdates() {
super.finalizeCollectionViewUpdates()
reload = []
add = []
rm = []
}
override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if add.contains(itemIndexPath) {
// 新增, 使用默认动画
add.remove(itemIndexPath)
return nil
}
let attr = _layoutAttributesForItemAtIndexPath(itemIndexPath)
if reload.contains(itemIndexPath) {
let attro = _layoutAttributesForItemAtOldIndexPath(itemIndexPath)?.copy() as? Attributes
attro?.alpha = 0
reload.remove(itemIndexPath)
return attro
}
return attr
}
override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if rm.contains(itemIndexPath) {
// 删除, 使用默认动画
rm.remove(itemIndexPath)
return nil
}
let attr = _layoutAttributesForItemAtOldIndexPath(itemIndexPath)
if reload.contains(itemIndexPath) {
let attrn = _layoutAttributesForItemAtIndexPath(itemIndexPath)?.copy() as? Attributes
attrn?.alpha = 0
return attrn
}
//attr?.alpha = 1
return attr
}
func sizeThatFits(_ maxSize: CGSize, atPosition position: SAIInputItemPosition) -> CGSize {
if let size = _cacheLayoutSizes[position] {
return size
}
let maxRect = CGRect(x: 0, y: 0, width: maxSize.width, height: maxSize.height)
let mls = minimumLineSpacing
let newSize = _lines(atPosition: position, inRect: maxRect).reduce(CGSize(width: 0, height: -mls)) {
CGSize(width: max($0.width, $1.frame.width),
height: $0.height + mls + $1.frame.height)
}
let size = CGSize(width: newSize.width, height: max(newSize.height, 0))
_cacheLayoutSizes[position] = size
return size
}
func invalidateLayout(atPosition position: SAIInputItemPosition) {
_invalidateLayoutAllCache(atPosition: position)
}
func invalidateLayoutIfNeeded(atPosition position: SAIInputItemPosition) {
guard let attributes = _cacheLayoutAllAttributes[position] else {
return
}
var itemIsChanged = false
var sizeIsChanged = false
var boundsIsChanged = false
let barItems = _barItems(atPosition: position)
// 数量不同. 重置
if attributes.count != barItems.count {
itemIsChanged = true
} else {
for index in 0 ..< attributes.count {
let attr = attributes[index]
let item = barItems[index]
if attr.item != item {
itemIsChanged = true
}
if attr.cacheSize != item.size {
sizeIsChanged = true
attr.cacheSize = nil
}
}
}
if let lines = _cacheLayoutAllLines[position] {
lines.forEach {
if $0.cacheMaxWidth != nil && $0.cacheMaxWidth != collectionView?.frame.width {
boundsIsChanged = true
}
}
}
if itemIsChanged {
_invalidateLayoutAllCache(atPosition: position)
} else if sizeIsChanged {
_invalidateLayoutLineCache(atPosition: position)
} else if boundsIsChanged {
_invalidateLayoutLineCache(atPosition: position)
} else {
// no changed
}
}
// MARK: private
private func _layoutIfNeed(inRect rect: CGRect) -> [Attributes] {
if let attributes = _cacheLayoutedAttributes {
return attributes
}
let mis = minimumInteritemSpacing // 列间隔
let mls = minimumLineSpacing // 行间隔
var y = contentInsets.top
var attributes = [Attributes]()
[.top, .center, .bottom].forEach {
_lines(atPosition: $0, inRect: rect).forEach {
$0.layout(atPoint: CGPoint(x: 0, y: y), maxWidth: rect.width, maxHeight: $0.frame.height, mis)
y = y + mls + $0.frame.height
attributes.append(contentsOf: $0.attributes)
}
}
// cache => save
_cacheLayoutAllAttributesOfPrevious = _cacheLayoutAllAttributesOfCurrent
_cacheLayoutAllAttributesOfCurrent = _cacheLayoutAllAttributes
_cacheLayoutedAttributes = attributes
return attributes
}
private func _layoutAttributesForItemAtIndexPath(_ indexPath: IndexPath) -> Attributes? {
if let position = SAIInputItemPosition(rawValue: (indexPath as NSIndexPath).section) {
if let attributes = _cacheLayoutAllAttributesOfCurrent[position], (indexPath as NSIndexPath).item < attributes.count {
return attributes[(indexPath as NSIndexPath).item]
}
}
return nil
}
private func _layoutAttributesForItemAtOldIndexPath(_ indexPath: IndexPath) -> Attributes? {
if let position = SAIInputItemPosition(rawValue: (indexPath as NSIndexPath).section) {
if let attributes = _cacheLayoutAllAttributesOfPrevious[position], (indexPath as NSIndexPath).item < attributes.count {
return attributes[(indexPath as NSIndexPath).item]
}
}
return nil
}
private func _linesWithAttributes(_ attributes: [Attributes], inRect rect: CGRect) -> [Line] {
return attributes.reduce([Line]()) {
// update cache
if $1.cacheSize == nil || $1.cacheSize != $1.item?.size {
$1.cacheSize = $1.item?.size
$1.size = $1.cacheSize ?? CGSize.zero
}
// check the width, if you can't hold, then create a new line
guard let line = $0.last, line.canAddItem($1, rect.width, minimumInteritemSpacing) else {
var lines = $0
lines.append(Line($1, contentInsets))
return lines
}
line.addItem($1, minimumInteritemSpacing)
return $0
}
}
private func _attributesWithBarItems(_ barItems: [SAIInputItem], atPosition position: SAIInputItemPosition) -> [Attributes] {
// 查找左对齐和右对齐的item
let ax = barItems.enumerated().reduce((-1, barItems.count)) {
if $1.element.alignment.rawValue & 0x00FF == 1 {
return (max($0.0, $1.offset), barItems.count)
}
if $1.element.alignment.rawValue & 0x00FF == 2 {
return ($0.0, min($0.1, $1.offset))
}
return $0
}
return barItems.enumerated().map {
let idx = IndexPath(item: $0, section: position.rawValue)
let attr = Attributes(forCellWith: idx)
attr.item = $1
attr.size = $1.size
attr.cacheSize = $1.size
attr.alignemt = Alignment(rawValue: $1.alignment.rawValue)
// 额外处理水平对齐
if $0 <= ax.0 {
attr.alignemt.formUnion(.Left)
} else if $0 >= ax.1 {
attr.alignemt.formUnion(.Right)
} else {
attr.alignemt.formUnion(.HCenter)
}
// 额外处理垂直对齐
if attr.alignemt.rawValue & 0xFF00 == 0 {
attr.alignemt.formUnion(.Bottom)
}
// 特殊处理
if position == .center {
// 强制resize
attr.alignemt = [.HResize, .VResize]
} else if position == .left {
// 强制左对齐
attr.alignemt.formUnion(.Left)
} else if position == .right {
// 强制右对齐
attr.alignemt.formUnion(.Right)
}
return attr
}
}
private func _lines(atPosition position: SAIInputItemPosition, inRect rect: CGRect) -> [Line] {
if let lines = _cacheLayoutAllLines[position] {
return lines
}
let attributes = { () -> [Attributes] in
if position == .center {
let a1 = self._attributes(atPosition: .left)
let a2 = self._attributes(atPosition: .center)
let a3 = self._attributes(atPosition: .right)
return a1 + a2 + a3
}
return self._attributes(atPosition: position)
}()
let lines = _linesWithAttributes(attributes, inRect: rect)
_cacheLayoutAllLines[position] = lines
return lines
}
private func _attributes(atPosition position: SAIInputItemPosition) -> [Attributes] {
if let attributes = _cacheLayoutAllAttributes[position] {
return attributes
}
let barItems = _barItems(atPosition: position)
let attributes = _attributesWithBarItems(barItems, atPosition: position)
_cacheLayoutAllAttributes[position] = attributes
return attributes
}
private func _barItems(atPosition position: SAIInputItemPosition) -> [SAIInputItem] {
// 如果不是这样的话... 直接报错(高耦合, 反正不重用)
let ds = collectionView?.dataSource as! SAIInputAccessoryView
return ds.barItems(atPosition: position)
}
private func _invalidateLayoutCache(_ force: Bool) {
guard !force else {
_invalidateLayoutAllCache()
return
}
// 计算出变更的点
[.top, .left, .center, .right, .bottom].forEach {
invalidateLayoutIfNeeded(atPosition: $0)
}
}
private func _invalidateLayoutAllCache() {
_cacheLayoutSizes.removeAll(keepingCapacity: true)
_cacheLayoutAllLines.removeAll(keepingCapacity: true)
_cacheLayoutAllAttributes.removeAll(keepingCapacity: true)
_cacheLayoutedAttributes = nil
}
private func _invalidateLayoutAllCache(atPosition position: SAIInputItemPosition) {
_cacheLayoutSizes.removeValue(forKey: position)
_cacheLayoutAllLines.removeValue(forKey: position)
_cacheLayoutAllAttributes.removeValue(forKey: position)
// center总是要清的
if position == .left || position == .right {
_cacheLayoutSizes.removeValue(forKey: .center)
_cacheLayoutAllLines.removeValue(forKey: .center)
_cacheLayoutAllAttributes.removeValue(forKey: .center)
}
_cacheLayoutedAttributes = nil
}
private func _invalidateLayoutLineCache(atPosition position: SAIInputItemPosition) {
_cacheLayoutSizes.removeValue(forKey: position)
_cacheLayoutAllLines.removeValue(forKey: position)
// center总是要清的
if position == .left || position == .right {
_cacheLayoutSizes.removeValue(forKey: .center)
_cacheLayoutAllLines.removeValue(forKey: .center)
_cacheLayoutAllAttributes[.center]?.forEach {
$0.cacheSize = nil
}
}
_cacheLayoutedAttributes = nil
}
// MARK: Cache
var rm: Set<IndexPath> = []
var add: Set<IndexPath> = []
var reload: Set<IndexPath> = []
var _cacheLayoutAllAttributesOfCurrent: [SAIInputItemPosition: [Attributes]] = [:]
var _cacheLayoutAllAttributesOfPrevious: [SAIInputItemPosition: [Attributes]] = [:]
var _cacheLayoutSizes: [SAIInputItemPosition: CGSize] = [:]
var _cacheLayoutAllLines: [SAIInputItemPosition: [Line]] = [:]
var _cacheLayoutAllAttributes: [SAIInputItemPosition: [Attributes]] = [:]
var _cacheLayoutedAttributes: [Attributes]?
// MARK: Init
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
}
}
| 36.553191 | 131 | 0.545256 |
e25eac2925f9c6d87d008c496eea6089cdd8a759 | 2,539 | //
// ModelBuilderTests.swift
// WistiaKit
//
// Created by Daniel Spinosa on 5/26/16.
// Copyright © 2016 Wistia, Inc. All rights reserved.
//
import XCTest
@testable import WistiaKitCore
@testable import WistiaKit
class ModelBuilderTests: XCTestCase {
let wAPI = WistiaAPI(apiToken:"1511ac67c0213610d9370ef12349c6ac828a18f6405154207b44f3a7e3a29e93")
//MARK: - Project
func testProjectBuildsMediasWhenIncluded() {
let expectation = self.expectation(description: "created project with media")
wAPI.showProject(forHash: "8q6efplb9n") { project, error in
if let medias = project?.medias , medias.count > 0 {
expectation.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
//MARK: - Media
func testDateFormat() {
let expectation = self.expectation(description: "media has non-nil dates")
wAPI.showMedia(forHash: "aza8hcsnd8") { media, error in
if media?.created != nil && media?.updated != nil {
expectation.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testSphericalDecoding() {
let expectationA = self.expectation(description: "media is not known to be spherical")
let expectationB = self.expectation(description: "mediaInfo is spherical")
// Media from public API doesn't have spherical
wAPI.showMedia(forHash: "vd1mwopfjz") { media, error in
XCTAssert(error == nil)
if media!.spherical == nil {
expectationA.fulfill()
}
}
// Media from MediaInfo should have spherical attribute (required for playback)
WistiaAPI.mediaInfo(for: "vd1mwopfjz") { media, error in
XCTAssert(error == nil)
if media!.isSpherical() {
expectationB.fulfill()
}
else {
XCTAssert(media!.isSpherical(), "Media should be spherical")
}
}
waitForExpectations(timeout: 3, handler: nil)
}
//MARK: - Captions
func testValidCaptions() {
let expectation = self.expectation(description: "captions are parsed")
WistiaAPI.captions(for: "8tjg8ftj2p") { captions, error in
XCTAssertNil(error)
if captions.count > 0 && captions[0].captionSegments.count > 0 {
expectation.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
}
| 29.183908 | 101 | 0.60575 |
9b262a19257b0abdff6cbe4e7cabfbf86738c0c2 | 4,804 | //
// AAExtension+UITabBar.swift
// AAExtensions
//
// Created by M. Ahsan Ali on 12/05/2019.
//
//
// 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:- UITabBar
public extension AA where Base: UITabBar {
func setColors(
background: UIColor? = nil,
selectedBackground: UIColor? = nil,
item: UIColor? = nil,
selectedItem: UIColor? = nil) {
if let color = background { base.barTintColor = color }
if let color = selectedItem { base.tintColor = color }
base.backgroundImage = UIImage()
base.isTranslucent = false
guard let barItems = base.items else { return }
if let selectedbg = selectedBackground {
let rect = CGSize(width: base.frame.width/CGFloat(barItems.count), height: base.frame.height)
base.selectionIndicatorImage = { (color: UIColor, size: CGSize) -> UIImage in
UIGraphicsBeginImageContextWithOptions(size, false, 1)
color.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() }
UIGraphicsEndImageContext()
guard let aCgImage = image.cgImage else { return UIImage() }
return UIImage(cgImage: aCgImage)
}(selectedbg, rect)
}
if let itemColor = item {
for barItem in barItems as [UITabBarItem] {
guard let image = barItem.image else { continue }
barItem.image = { (image: UIImage, color: UIColor) -> UIImage in
UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
color.setFill()
guard let context = UIGraphicsGetCurrentContext() else {
return image
}
context.translateBy(x: 0, y: image.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
guard let mask = image.cgImage else { return image }
context.clip(to: rect, mask: mask)
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}(image, itemColor).withRenderingMode(.alwaysOriginal)
barItem.setTitleTextAttributes([.foregroundColor: itemColor], for: .normal)
if let selected = selectedItem {
barItem.setTitleTextAttributes([.foregroundColor: selected], for: .selected)
}
}
}
}
}
public extension AA where Base: UITabBarController {
func visibility(_ isHidden: Bool, animated: Bool = true, duration: TimeInterval = 0.3) {
let tabBar = base.tabBar
let view = base.view!
if (tabBar.isHidden == isHidden) { return }
if !isHidden { tabBar.isHidden = false }
let height = tabBar.frame.size.height
let offsetY = view.frame.height - (isHidden ? 0 : height)
let duration = (animated ? duration : 0.0)
let frame = CGRect(origin: CGPoint(x: tabBar.frame.minX, y: offsetY), size: tabBar.frame.size)
UIView.animate(withDuration: duration, animations: {
tabBar.frame = frame
}) { _ in
tabBar.isHidden = isHidden
}
}
}
| 43.672727 | 105 | 0.601166 |
398e17b56e9e4649de4aea01e71dc1be41613531 | 802 | //
// Boar_ReactiveIOSTests.swift
// Boar-ReactiveIOSTests
//
// Created by Peter Ovchinnikov on 1/22/18.
// Copyright © 2018 Peter Ovchinnikov. All rights reserved.
//
import XCTest
import Boar_ReactiveIOS
public class ModernCtrlVC: VCService {
public func reload() {
}
public func reload(code: String) {
}
}
protocol Controller {
}
public class ModernCtrl: UIViewController, VCLifeCycle {
public func advise(viewModel: ModernCtrlVC) {
}
public typealias ViewModel = ModernCtrlVC
}
class UIViewControllerTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testExample() {
}
}
| 14.581818 | 60 | 0.600998 |
56c16ff9d8211f5d6559552c39df9b8603d0c624 | 3,362 | //
// MarsRoverClient.swift
// Astronomy
//
// Created by Andrew R Madsen on 9/5/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import Foundation
class MarsRoverClient {
func fetchMarsRover(named name: String,
using session: URLSession = URLSession.shared,
completion: @escaping (MarsRover?, Error?) -> Void) {
let url = self.url(forInfoForRover: name)
fetch(from: url, using: session) { (dictionary: [String : MarsRover]?, error: Error?) in
guard let rover = dictionary?["photo_manifest"] else {
completion(nil, error)
return
}
completion(rover, nil)
}
}
func fetchPhotos(from rover: MarsRover,
onSol sol: Int,
using session: URLSession = URLSession.shared,
completion: @escaping ([MarsPhotoReference]?, Error?) -> Void) {
let url = self.url(forPhotosfromRover: rover.name, on: sol)
fetch(from: url, using: session) { (dictionary: [String : [MarsPhotoReference]]?, error: Error?) in
guard let photos = dictionary?["photos"] else {
completion(nil, error)
return
}
completion(photos, nil)
}
}
// MARK: - Private
private func fetch<T: Codable>(from url: URL,
using session: URLSession = URLSession.shared,
completion: @escaping (T?, Error?) -> Void) {
session.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError(domain: "com.LambdaSchool.Astronomy.ErrorDomain", code: -1, userInfo: nil))
return
}
do {
let jsonDecoder = MarsPhotoReference.jsonDecoder
let decodedObject = try jsonDecoder.decode(T.self, from: data)
completion(decodedObject, nil)
} catch {
completion(nil, error)
}
}.resume()
}
private let baseURL = URL(string: "https://api.nasa.gov/mars-photos/api/v1")!
private let apiKey = "qzGsj0zsKk6CA9JZP1UjAbpQHabBfaPg2M5dGMB7"
private func url(forInfoForRover roverName: String) -> URL {
var url = baseURL
url.appendPathComponent("manifests")
url.appendPathComponent(roverName)
let urlComponents = NSURLComponents(url: url, resolvingAgainstBaseURL: true)!
urlComponents.queryItems = [URLQueryItem(name: "api_key", value: apiKey)]
return urlComponents.url!
}
private func url(forPhotosfromRover roverName: String, on sol: Int) -> URL {
var url = baseURL
url.appendPathComponent("rovers")
url.appendPathComponent(roverName)
url.appendPathComponent("photos")
let urlComponents = NSURLComponents(url: url, resolvingAgainstBaseURL: true)!
urlComponents.queryItems = [URLQueryItem(name: "sol", value: String(sol)),
URLQueryItem(name: "api_key", value: apiKey)]
return urlComponents.url!
}
}
| 36.945055 | 115 | 0.562463 |
9082c86db10b30eddaed0ebe59b3be77f05d2e9f | 352 | //
// APIResult.swift
// CloudSquad
//
// Created by Alberto Lourenço on 2/15/20.
// Copyright © 2020 Alberto Lourenço. All rights reserved.
//
import Foundation
struct APIResult: Codable {
var result: Bool!
var message: String!
enum CodingKeys: String, CodingKey {
case result
case message
}
}
| 16 | 59 | 0.616477 |
db3f22c314ce8aa4a7af0a360118420a7998ec4f | 2,392 |
class OrderBook
{
var bids : [Order]
var asks : [Order]
public init()
{
bids = []
asks = []
}
public func insert(order: Order) -> [Trade]
{
let trades = match(order: order)
if order.quantity > 0
{
insert(order, inSide: &bids, where: { $0.price < order.price })
}
if order.quantity < 0
{
insert(order, inSide: &asks, where: { $0.price > order.price })
}
return trades
}
private func match(order: Order) -> [Trade]
{
var trades : [Trade] = []
if order.quantity > 0
{
trades += match(order, against: &asks, where: { $0.price <= order.price })
}
if order.quantity < 0
{
trades += match(order, against: &bids, where: { $0.price >= order.price })
}
return trades
}
private func insert(_ order: Order, inSide side: inout [Order], where condition: (Order) -> Bool)
{
if let index = side.firstIndex(where: condition)
{
side.insert(order, at: index)
}
else
{
side.append(order)
}
}
private func match(_ order: Order, against side: inout [Order], where condition: (Order) -> Bool) -> [Trade]
{
var trades : [Trade] = []
let sign = (order.quantity > 0 ? 1 : -1)
for other_order in side.filter(condition)
{
if order.quantity == 0
{
break
}
let trade = execute(order, with: other_order)
trades.append(trade)
order.quantity -= sign * trade.quantity
other_order.quantity += sign * trade.quantity
}
side = side.filter() { $0.quantity != 0 }
return trades
}
private func execute(_ order: Order, with other: Order) -> Trade
{
let trade = Trade()
trade.instrument = order.instrument
trade.quantity = min(abs(order.quantity), abs(other.quantity))
trade.price = other.price
if order.quantity > 0
{
trade.buyer = order.participant
trade.seller = other.participant
}
else
{
trade.buyer = other.participant
trade.seller = order.participant
}
return trade
}
}
| 22.566038 | 112 | 0.498746 |
ab6f29c0ef696259583587872d0d82842a16ef1b | 3,328 | //
// DownloadImageService.swift
// FlickerPhotoSearch
//
// Created by Yash Awasthi on 26/06/2020.
// Copyright © 2020 Yash Awasthi. All rights reserved.
//
import Foundation
final class DownloadImageService {
private init() { }
static let shared = DownloadImageService()
private var coreImageOperationQueue: OperationQueue = {
let imageQueue = OperationQueue()
imageQueue.name = Constants.kOperationQueueName
imageQueue.qualityOfService = .userInteractive
return imageQueue
}()
private let imageDataCache = NSCache<NSString, NSData>()
func getImage(from url: URL,
indexPath: IndexPath?,
completion: @escaping CoreImageCompletion) {
if let cachedImageData = imageDataCache.object(forKey: url.absoluteString as NSString) {
// MARK: If image is available in the Cache get a copy from there.
// print(" GOT IMAGE FROM CACHE ")
completion(cachedImageData as Data, indexPath, url)
}else{
if Reachability.currentReachabilityStatus == .notReachable {
completion(nil,nil,url)
return
}
// MARK: Boosting up the priority for the images which are enqueued and being downloaded already.
if let firstOperation = getHigherPriorityCoreOperation(with: url) {
// print(" CHANGED PRIORITY - V.HIGH")
firstOperation.queuePriority = .veryHigh
}else{
// MARK: The images which were never enqueued are being downloaded and processed here,
let imageOperation = CoreImageOperation(url: url, indexPath: indexPath)
if indexPath == nil {
// print(" CHANGED PRIORITY - HIGH")
imageOperation.queuePriority = .high
}
imageOperation.onCompletion = { (data, index, key) in
if let imageData = data {
self.imageDataCache.setObject(imageData as NSData, forKey: key.absoluteString as NSString)
}
completion(data, index, key)
}
// MARK: Submitting the operation to the Queue
coreImageOperationQueue.addOperation(imageOperation)
}
}
}
func prolongDownloadForImages(with url: URL) {
guard let firstOperation = getHigherPriorityCoreOperation(with: url) else { return }
firstOperation.queuePriority = .low
}
func cancelQueuedOperations(){
coreImageOperationQueue.cancelAllOperations()
}
fileprivate func getHigherPriorityCoreOperation(with url: URL) -> CoreImageOperation? {
guard let coreImageOperations = coreImageOperationQueue.operations as? [CoreImageOperation] else { return nil }
guard let firstOperation = coreImageOperations
.filter({ $0.url.absoluteString == url.absoluteString && $0.isFinished == false && $0.isExecuting == true }).first else { return nil }
return firstOperation
}
}
| 38.252874 | 142 | 0.579327 |
468fe8ebe8bed9fd72ffa6ee6c08480b51052b78 | 901 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import func libc.getenv
import func libc.setenv
import func libc.unsetenv
import var libc.errno
public func getenv(_ key: String) -> String? {
let out = libc.getenv(key)
return out == nil ? nil : String(validatingUTF8: out!) //FIXME locale may not be UTF8
}
public func setenv(_ key: String, value: String) throws {
guard libc.setenv(key, value, 1) == 0 else {
throw SystemError.setenv(errno, key)
}
}
public func unsetenv(_ key: String) throws {
guard libc.unsetenv(key) == 0 else {
throw SystemError.unsetenv(errno, key)
}
}
| 28.15625 | 90 | 0.710322 |
2824457496acbae508527ecd5d9c820f2b2481d5 | 1,065 | //
// INVCouponType.swift
// MtsInvestGrpcService
//
// Created by Юрий Султанов on 27.07.2021.
//
public enum INVCouponType {
case couponRangeType(INVRangeCoupon)
case couponFixType(INVFixCoupon)
}
extension INVCouponType: Equatable {
public static func == (lhs: INVCouponType, rhs: INVCouponType) -> Bool {
switch (lhs, rhs) {
case (.couponRangeType(let left), .couponRangeType(let right)):
return left == right
case (.couponFixType(let left), .couponFixType(let right)):
return left == right
default:
return false
}
}
}
extension INVCouponType {
init?(from grpcType: Ru_Mts_Trading_Grpc_Pub_Instruments_V2_BookBuilding.OneOf_Type?) {
guard let grpcType = grpcType else { return nil }
switch grpcType {
case .couponFixType(let fixCoupon):
self = .couponFixType(INVFixCoupon(from: fixCoupon))
case .couponRangeType(let rangeCoupon):
self = .couponRangeType(INVRangeCoupon(from: rangeCoupon))
}
}
}
| 28.783784 | 91 | 0.650704 |
4681ffccabf36b84bb4b1c1e4f4000e30f7eec8d | 2,667 | //
// AppFonts.swift
// Gorilla
//
// Created by Daniel Tarazona on 12/7/19.
// Copyright © 2019 Gorilla. All rights reserved.
//
import Foundation
import UIKit.UIFont
let fontFamily = "Helvetica"
final class AppFonts {
struct Title {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 32)
static let light = UIFont(name: "\(fontFamily)-Light", size: 32)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 32)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 32)
}
struct Subtitle {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 27)
static let light = UIFont(name: "\(fontFamily)-Light", size: 27)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 27)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 27)
}
struct Heading1 {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 22)
static let light = UIFont(name: "\(fontFamily)-Light", size: 22)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 22)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 22)
}
struct Heading2 {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 20)
static let light = UIFont(name: "\(fontFamily)-Light", size: 20)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 20)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 20)
}
struct Heading3 {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 18)
static let light = UIFont(name: "\(fontFamily)-Light", size: 18)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 18)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 18)
}
struct Heading4 {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 16)
static let light = UIFont(name: "\(fontFamily)-Light", size: 16)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 16)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 16)
}
struct Heading5 {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 14)
static let light = UIFont(name: "\(fontFamily)-Light", size: 14)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 14)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 14)
}
struct Heading6 {
static let bold = UIFont(name: "\(fontFamily)-Bold", size: 12)
static let light = UIFont(name: "\(fontFamily)-Light", size: 12)
static let medium = UIFont(name: "\(fontFamily)-Medium", size: 12)
static let regular = UIFont(name: "\(fontFamily)-Regular", size: 12)
}
}
| 36.534247 | 72 | 0.652793 |
33da0059b6787d4747061e74df529ce563c1c641 | 424 | //
// DBFMCollectionViewCell.swift
// DB-Time
//
// Created by Mazy on 2018/5/4.
// Copyright © 2018 Mazy. All rights reserved.
//
import UIKit
class DBFMCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
iconImageView.layer.cornerRadius = (SCREEN_WIDTH - 40)/6
}
}
| 20.190476 | 64 | 0.681604 |
614b874af243373ebf4dbe8d639e3e6f1a595d6c | 11,815 | //
// VGSTextField.swift
// VGSCollectSDK
//
// Created by Vitalii Obertynskyi on 8/14/19.
// Copyright © 2019 Vitalii Obertynskyi. All rights reserved.
//
#if os(iOS)
import UIKit
#endif
/// An object that displays an editable text area in user interface.
public class VGSTextField: UIView {
private(set) weak var vgsCollector: VGSCollect?
internal var textField = MaskedTextField(frame: .zero)
internal var focusStatus: Bool = false
internal var isRequired: Bool = false
internal var isRequiredValidOnly: Bool = false
internal var isDirty: Bool = false
internal var fieldType: FieldType = .none
internal var fieldName: String!
internal var token: String?
internal var horizontalConstraints = [NSLayoutConstraint]()
internal var verticalConstraint = [NSLayoutConstraint]()
internal var validationRules = VGSValidationRuleSet()
// MARK: - UI Attributes
/// Textfield placeholder string.
public var placeholder: String? {
didSet { textField.placeholder = placeholder }
}
/// Textfield attributedPlaceholder string.
public var attributedPlaceholder: NSAttributedString? {
didSet {
textField.attributedPlaceholder = attributedPlaceholder
}
}
/// `UIEdgeInsets` for text and placeholder inside `VGSTextField`.
public var padding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) {
didSet { setMainPaddings() }
}
/// The technique to use for aligning the text.
public var textAlignment: NSTextAlignment = .natural {
didSet { textField.textAlignment = textAlignment }
}
/// Sets when the clear button shows up. Default is `UITextField.ViewMode.never`
public var clearButtonMode: UITextField.ViewMode = .never {
didSet { textField.clearButtonMode = clearButtonMode }
}
/// Identifies whether the text object should disable text copying and in some cases hide the text being entered. Default is false.
public var isSecureTextEntry: Bool = false {
didSet { textField.isSecureTextEntry = isSecureTextEntry }
}
/// Indicates whether `VGSTextField ` should automatically update its font when the device’s `UIContentSizeCategory` is changed.
public var adjustsFontForContentSizeCategory: Bool = false {
didSet { textField.adjustsFontForContentSizeCategory = adjustsFontForContentSizeCategory }
}
/// Input Accessory View
public var keyboardAccessoryView: UIView? {
didSet { textField.inputAccessoryView = keyboardAccessoryView }
}
/// Determines whether autocorrection is enabled or disabled during typing.
public var autocorrectionType: UITextAutocorrectionType = .default {
didSet {
textField.autocorrectionType = autocorrectionType
}
}
// MARK: - Functional Attributes
/// Specifies `VGSTextField` configuration parameters to work with `VGSCollect`.
public var configuration: VGSConfiguration? {
didSet {
guard let configuration = configuration else { return }
// config text field
fieldName = configuration.fieldName
isRequired = configuration.isRequired
isRequiredValidOnly = configuration.isRequiredValidOnly
fieldType = configuration.type
textField.keyboardType = configuration.keyboardType ?? configuration.type.keyboardType
textField.returnKeyType = configuration.returnKeyType ?? .default
textField.keyboardAppearance = configuration.keyboardAppearance ?? .default
if let pattern = configuration.formatPattern {
textField.formatPattern = pattern
} else {
textField.formatPattern = configuration.type.defaultFormatPattern
}
if let divider = configuration.divider {
textField.divider = divider
} else {
textField.divider = configuration.type.defaultDivider
}
/// Validation
if let rules = configuration.validationRules {
validationRules = rules
} else {
validationRules = fieldType.defaultValidation
}
if let collector = configuration.vgsCollector {
vgsCollector = collector
collector.registerTextFields(textField: [self])
VGSAnalyticsClient.shared.trackFormEvent(collector.formAnalyticsDetails, type: .fieldInit, extraData: ["field": fieldType.stringIdentifier])
}
}
}
/// Delegates `VGSTextField` editing events. Default is `nil`.
public weak var delegate: VGSTextFieldDelegate?
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
mainInitialization()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
mainInitialization()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Manage input
/// Set textfield default text.
/// - Note: This will not change `State.isDirty` attribute.
/// - Discussion: probably you should want to set field configuration before setting default value, so the input format will be update as required.
public func setDefaultText(_ text: String?) {
updateTextFieldInput(text)
}
/// :nodoc: Set textfield text.
public func setText(_ text: String?) {
isDirty = true
updateTextFieldInput(text)
}
/// Removes input from field.
public func cleanText() {
updateTextFieldInput("")
}
internal func getOutputText() -> String? {
if let config = configuration as? FormatConvertable, let input = textField.getSecureTextWithDivider, let outputFormat = config.outputFormat, let inputFormat = config.inputFormat {
return config.convertor.convert(input, inputFormat: inputFormat, outputFormat: outputFormat)
}
return textField.getSecureTextWithDivider
}
}
// MARK: - UIResponder methods
extension VGSTextField {
/// Make `VGSTextField` focused.
@discardableResult override public func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
/// Remove focus from `VGSTextField`.
@discardableResult override public func resignFirstResponder() -> Bool {
return textField.resignFirstResponder()
}
/// Check if `VGSTextField` is focused.
override public var isFirstResponder: Bool {
return textField.isFirstResponder
}
}
// MARK: - Textfiled delegate
extension VGSTextField: UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
textFieldValueChanged()
delegate?.vgsTextFieldDidBeginEditing?(self)
}
@objc func textFieldDidChange(_ textField: UITextField) {
isDirty = true
textFieldValueChanged()
delegate?.vgsTextFieldDidChange?(self)
}
public func textFieldDidEndEditing(_ textField: UITextField) {
textFieldValueChanged()
delegate?.vgsTextFieldDidEndEditing?(self)
}
@objc func textFieldDidEndEditingOnExit(_ textField: UITextField) {
textFieldValueChanged()
delegate?.vgsTextFieldDidEndEditingOnReturn?(self)
}
}
// MARK: - private API
internal extension VGSTextField {
@objc
func mainInitialization() {
// set main style for view
mainStyle()
// add UI elements
buildTextFieldUI()
// add otextfield observers and delegates
addTextFieldObservers()
}
@objc
func buildTextFieldUI() {
textField.translatesAutoresizingMaskIntoConstraints = false
addSubview(textField)
setMainPaddings()
}
@objc
func addTextFieldObservers() {
//delegates
textField.addSomeTarget(self, action: #selector(textFieldDidBeginEditing), for: .editingDidBegin)
//Note: .allEditingEvents doesn't work proparly when set text programatically. Use setText instead!
textField.addSomeTarget(self, action: #selector(textFieldDidEndEditing), for: .editingDidEnd)
textField.addSomeTarget(self, action: #selector(textFieldDidEndEditingOnExit), for: .editingDidEndOnExit)
NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChange), name: UITextField.textDidChangeNotification, object: textField)
// tap gesture for update focus state
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(focusOn))
textField.addGestureRecognizer(tapGesture)
}
@objc
func setMainPaddings() {
NSLayoutConstraint.deactivate(verticalConstraint)
NSLayoutConstraint.deactivate(horizontalConstraints)
let views = ["view": self, "textField": textField]
horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(padding.left)-[textField]-\(padding.right)-|",
options: .alignAllCenterY,
metrics: nil,
views: views)
NSLayoutConstraint.activate(horizontalConstraints)
verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(padding.top)-[textField]-\(padding.bottom)-|",
options: .alignAllCenterX,
metrics: nil,
views: views)
NSLayoutConstraint.activate(verticalConstraint)
self.layoutIfNeeded()
}
@objc
func textFieldValueChanged() {
// update format pattern after field input changed
updateFormatPattern()
// update status
vgsCollector?.updateStatus(for: self)
}
func updateFormatPattern() {
// update card number and cvc format dynamically based on card brand
if self.fieldType == .cardNumber, let cardState = self.state as? CardState {
if let cardModel = VGSPaymentCards.getCardModelFromAvailableModels(brand: cardState.cardBrand) {
self.textField.formatPattern = cardModel.formatPattern
} else {
self.textField.formatPattern = VGSPaymentCards.unknown.formatPattern
}
// change cvc format pattern and validation rules based on card brand
if let cvcField = self.vgsCollector?.storage.textFields.filter({ $0.fieldType == .cvc }).first {
cvcField.textField.formatPattern = cardState.cardBrand.cvcFormatPattern
cvcField.validationRules = self.getCVCValidationRules(cardBrand: cardState.cardBrand)
}
}
textField.updateTextFormat()
}
// change focus here
@objc
func focusOn() {
// change status
textField.becomeFirstResponder()
textFieldValueChanged()
}
/// This will update format pattern and notify about the change
func updateTextFieldInput(_ text: String?) {
/// clean previous format pattern and add new based on content after text is set
if self.fieldType == .cardNumber {
textField.formatPattern = ""
}
textField.secureText = text
// this will update card textfield icons and dynamic format pattern
textFieldValueChanged()
delegate?.vgsTextFieldDidChange?(self)
}
}
// MARK: - Main style for text field
extension UIView {
func mainStyle() {
clipsToBounds = true
layer.borderColor = UIColor.lightGray.cgColor
layer.borderWidth = 1
layer.cornerRadius = 4
}
}
| 36.692547 | 183 | 0.655692 |
f7d846f51ada36d3b9e4d819fccdd60c98fa46d4 | 1,836 | // Copyright 2020-2021 Dave Verwer, Sven A. Schmidt, and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Fluent
import SQLKit
struct RemoveVersionCountFromStats: AsyncMigration {
let dropSQL: SQLQueryString = "DROP MATERIALIZED VIEW stats"
func prepare(on database: Database) async throws {
guard let db = database as? SQLDatabase else {
fatalError("Database must be an SQLDatabase ('as? SQLDatabase' must succeed)")
}
try await db.raw(dropSQL).run()
try await db.raw(
"""
-- v1
CREATE MATERIALIZED VIEW stats AS
SELECT
NOW() AS date,
(SELECT COUNT(*) FROM packages) AS package_count
""").run()
}
func revert(on database: Database) async throws {
guard let db = database as? SQLDatabase else {
fatalError("Database must be an SQLDatabase ('as? SQLDatabase' must succeed)")
}
try await db.raw(dropSQL).run()
try await db.raw(
"""
-- v0
CREATE MATERIALIZED VIEW stats AS
SELECT
NOW() AS date,
(SELECT COUNT(*) FROM packages) AS package_count,
(SELECT COUNT(*) FROM versions) AS version_count
""").run()
}
}
| 34 | 90 | 0.626362 |
b9673c4f4611c2405d2865e41e78f075f895fed2 | 7,050 |
// RUN: %target-swift-emit-silgen -module-name switch_multiple_entry_address_only %s | %FileCheck %s
enum E {
case a(Any)
case b(Any)
case c(Any)
}
// CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only8takesAnyyyypF : $@convention(thin) (@in_guaranteed Any) -> ()
func takesAny(_ x: Any) {}
// CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only0B9LabelsLet1eyAA1EO_tF : $@convention(thin) (@in_guaranteed E) -> ()
func multipleLabelsLet(e: E) {
// CHECK: bb0
// CHECK: [[X_PHI:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[E_COPY:%.*]] = alloc_stack $E
// CHECK-NEXT: copy_addr %0 to [initialization] [[E_COPY]]
// CHECK-NEXT: switch_enum_addr [[E_COPY]] : $*E, case #E.a!enumelt.1: bb1, case #E.b!enumelt.1: bb2, default bb4
// CHECK: bb1:
// CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.a!enumelt.1
// CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]]
// CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]]
// CHECK-NEXT: destroy_addr [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb3
// CHECK: bb2:
// CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.b!enumelt.1
// CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]]
// CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]]
// CHECK-NEXT: destroy_addr [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK: [[FN:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF
// CHECK-NEXT: apply [[FN]]([[X_PHI]]
// CHECK-NEXT: destroy_addr [[X_PHI]]
// CHECK-NEXT: br bb5
// CHECK: bb4:
// CHECK-NEXT: destroy_addr [[E_COPY]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb5
// CHECK: bb5:
// CHECK-NEXT: dealloc_stack [[X_PHI]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
switch e {
case .a(let x), .b(let x):
takesAny(x)
default:
break
}
}
// CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only0B9LabelsVar1eyAA1EO_tF : $@convention(thin) (@in_guaranteed E) -> ()
func multipleLabelsVar(e: E) {
// CHECK: bb0
// CHECK: [[X_PHI:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[E_COPY:%.*]] = alloc_stack $E
// CHECK-NEXT: copy_addr %0 to [initialization] [[E_COPY]]
// CHECK-NEXT: switch_enum_addr [[E_COPY]] : $*E, case #E.a!enumelt.1: bb1, case #E.b!enumelt.1: bb2, default bb4
// CHECK: bb1:
// CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.a!enumelt.1
// CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]]
// CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]]
// CHECK-NEXT: destroy_addr [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb3
// CHECK: bb2:
// CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.b!enumelt.1
// CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]]
// CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]]
// CHECK-NEXT: destroy_addr [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_box ${ var Any }, var, name "x"
// CHECK-NEXT: [[BOX_PAYLOAD:%.*]] = project_box [[ANY_BOX]] : ${ var Any }, 0
// CHECK-NEXT: copy_addr [take] [[X_PHI]] to [initialization] [[BOX_PAYLOAD]]
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [unknown] [[BOX_PAYLOAD]]
// CHECK-NEXT: [[ANY_STACK:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [[ACCESS]] to [initialization] [[ANY_STACK]]
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK: [[FN:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF
// CHECK-NEXT: apply [[FN]]([[ANY_STACK]]
// CHECK-NEXT: destroy_addr [[ANY_STACK]]
// CHECK-NEXT: dealloc_stack [[ANY_STACK]]
// CHECK-NEXT: destroy_value [[ANY_BOX]]
// CHECK-NEXT: br bb5
// CHECK: bb4:
// CHECK-NEXT: destroy_addr [[E_COPY]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb5
// CHECK: bb5:
// CHECK-NEXT: dealloc_stack [[X_PHI]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
switch e {
case .a(var x), .b(var x):
takesAny(x)
default:
break
}
}
// CHECK-LABEL: sil hidden @$s34switch_multiple_entry_address_only20fallthroughWithValue1eyAA1EO_tF : $@convention(thin) (@in_guaranteed E) -> ()
func fallthroughWithValue(e: E) {
// CHECK: bb0
// CHECK: [[X_PHI:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[E_COPY:%.*]] = alloc_stack $E
// CHECK-NEXT: copy_addr %0 to [initialization] [[E_COPY]]
// CHECK-NEXT: switch_enum_addr [[E_COPY]] : $*E, case #E.a!enumelt.1: bb1, case #E.b!enumelt.1: bb2, default bb4
// CHECK: bb1:
// CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.a!enumelt.1
// CHECK-NEXT: [[ORIGINAL_ANY_BOX:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ORIGINAL_ANY_BOX]]
// CHECK: [[FN1:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF
// CHECK-NEXT: apply [[FN1]]([[ORIGINAL_ANY_BOX]]
// CHECK-NEXT: copy_addr [[ORIGINAL_ANY_BOX]] to [initialization] [[X_PHI]]
// CHECK-NEXT: destroy_addr [[ORIGINAL_ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[ORIGINAL_ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb3
// CHECK: bb2:
// CHECK-NEXT: [[E_PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[E_COPY]] : $*E, #E.b!enumelt.1
// CHECK-NEXT: [[ANY_BOX:%.*]] = alloc_stack $Any
// CHECK-NEXT: copy_addr [take] [[E_PAYLOAD]] to [initialization] [[ANY_BOX]]
// CHECK-NEXT: copy_addr [[ANY_BOX]] to [initialization] [[X_PHI]]
// CHECK-NEXT: destroy_addr [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[ANY_BOX]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK: [[FN2:%.*]] = function_ref @$s34switch_multiple_entry_address_only8takesAnyyyypF
// CHECK-NEXT: apply [[FN2]]([[X_PHI]]
// CHECK-NEXT: destroy_addr [[X_PHI]]
// CHECK-NEXT: br bb5
// CHECK: bb4:
// CHECK-NEXT: destroy_addr [[E_COPY]]
// CHECK-NEXT: dealloc_stack [[E_COPY]]
// CHECK-NEXT: br bb5
// CHECK: bb5:
// CHECK-NEXT: dealloc_stack [[X_PHI]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
switch e {
case .a(let x):
takesAny(x)
fallthrough
case .b(let x):
takesAny(x)
default:
break
}
}
| 38.736264 | 145 | 0.633191 |
fc5c3a04e8326d2cecc88682549d58ef4e3a5cc9 | 4,166 | //
// JCIdentityVerificationViewController.swift
// JChat
//
// Created by JIGUANG on 2017/4/5.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
class JCGroupJoinVerificationVC: CTViewController {
var tableView : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UserDefaults.standard.set(0, forKey: kUnreadGroupInvitationCount)
}
private var infos = [JCGroupJoinInfoModel]()
// MARK: - private func
private func _init() {
self.title = "群通知"
view.backgroundColor = .white
tableView = UITableView.init(frame: .zero, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(JCVerificationCell.self, forCellReuseIdentifier: "JCVerificationCell")
self.view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
}
_getData()
}
@objc func _getData() {
if let list = CacheClass.arrayForEnumKey(CacheClass.stringForEnumKey(.username)) as? [[String:Any]] {
let modelArray = NSArray.yy_modelArray(with: JCGroupJoinInfoModel.self, json: list)
infos = modelArray as! [JCGroupJoinInfoModel]
tableView.reloadData()
}
}
}
extension JCGroupJoinVerificationVC: JCVerificationCellDelegate {
func clickAcceptButtonAt(info:JCGroupJoinInfoModel)
{
let user = JMSGUser.init(uid: info.uid)
JMSGGroup.processApplyJoinEventID(info.eventID, gid: info.groupID, join: user!, apply: user!, isAgree: true, reason: nil) { (result, error) in
info.state = 1
self.tableView.reloadData()
if let list = MJOCManager.arrayOrDic(with: self.infos) as? [[String:Any]] {
print("================= \(list)")
CacheClass.setObject(list, forEnumKey: CacheClass.stringForEnumKey(.username))
}
}
}
}
extension JCGroupJoinVerificationVC:UITableViewDelegate,UITableViewDataSource {
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return infos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "JCVerificationCell", for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? JCVerificationCell else {
return
}
cell.isGrouJoin = true
cell.delegate = self
let dic = infos[indexPath.row]
cell.bindDataGroup(dic)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 65
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
infos.remove(at: indexPath.row)
tableView.reloadData()
if let list = MJOCManager.arrayOrDic(with: infos) as? [[String:Any]] {
print("================= \(list)")
CacheClass.setObject(list, forEnumKey: CacheClass.stringForEnumKey(.username))
}
}
}
}
| 32.294574 | 150 | 0.6265 |
383abcfe7fc4c64f4cfabb4fea9c58c31643b0d8 | 5,021 | // Copyright 2022 Pera Wallet, LDA
// 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.
// AnnouncementViewTheme.swift
import Foundation
import MacaroonUIKit
import UIKit
protocol AnnouncementViewTheme: StyleSheet, LayoutSheet {
var background: ViewStyle { get }
var backgroundImage: ImageSource? { get }
var corner: Corner { get }
var stackViewEdgeInset: LayoutMargins { get }
var stackViewLayoutMargins: LayoutMargins { get }
var stackViewItemSpacing: LayoutMetric { get }
var stackViewButtonSpacing: LayoutMetric { get }
var title: TextStyle { get }
var subtitle: TextStyle { get }
var action: ButtonStyle { get }
var actionEdgeInsets: LayoutPaddings { get }
var actionHeight: LayoutMetric { get }
var close: ButtonStyle { get }
var closeMargins: LayoutMargins { get }
var closeSize: LayoutSize { get }
}
struct GenericAnnouncementViewTheme: AnnouncementViewTheme {
var background: ViewStyle
var backgroundImage: ImageSource? = nil
var corner: Corner
var stackViewEdgeInset: LayoutMargins
var stackViewLayoutMargins: LayoutMargins
var stackViewItemSpacing: LayoutMetric
var stackViewButtonSpacing: LayoutMetric
var title: TextStyle
var subtitle: TextStyle
var action: ButtonStyle
var actionEdgeInsets: LayoutPaddings
var actionHeight: LayoutMetric
var close: ButtonStyle
var closeMargins: LayoutMargins
var closeSize: LayoutSize
init(
_ family: LayoutFamily
) {
self.background = [
.backgroundColor(AppColors.Components.Banner.background)
]
self.corner = Corner(radius: 4)
self.stackViewEdgeInset = (24, 24, 28, 24)
self.stackViewLayoutMargins = (0, 0, 0, 0)
self.stackViewItemSpacing = 12
self.stackViewButtonSpacing = 16
self.title = [
.font(Fonts.DMSans.medium.make(15)),
.textOverflow(FittingText()),
.textColor(AppColors.Components.Banner.text)
]
self.subtitle = [
.font(Fonts.DMSans.regular.make(13)),
.textOverflow(FittingText()),
.textColor(AppColors.Components.Banner.text)
]
self.action = [
.backgroundImage([.normal("banner-cta-background")]),
.font(Fonts.DMSans.medium.make(13))
]
self.actionEdgeInsets = (0, 16, 0, 16)
self.actionHeight = 44
self.close = [
.backgroundImage([.normal("icon-generic-close-banner")])
]
self.closeMargins = (8, .noMetric, .noMetric, 8)
self.closeSize = (24, 24)
}
}
struct GovernanceAnnouncementViewTheme: AnnouncementViewTheme {
var background: ViewStyle
var backgroundImage: ImageSource?
var corner: Corner
var stackViewEdgeInset: LayoutMargins
var stackViewLayoutMargins: LayoutMargins
var stackViewItemSpacing: LayoutMetric
var stackViewButtonSpacing: LayoutMetric
var title: TextStyle
var subtitle: TextStyle
var action: ButtonStyle
var actionEdgeInsets: LayoutPaddings
var actionHeight: LayoutMetric
var close: ButtonStyle
var closeMargins: LayoutMargins
var closeSize: LayoutSize
init(
_ family: LayoutFamily
) {
self.background = [
.backgroundColor(AppColors.Components.Banner.governanceBackground)
]
self.backgroundImage = AssetImageSource(asset: UIImage(named: "background-governance-image"))
self.corner = Corner(radius: 4)
self.stackViewEdgeInset = (24, 24, 28, 80)
self.stackViewLayoutMargins = (0, 0, 0, 0)
self.stackViewItemSpacing = 12
self.stackViewButtonSpacing = 16
self.title = [
.font(Fonts.DMSans.medium.make(15)),
.textOverflow(FittingText()),
.textColor(AppColors.Components.Banner.governanceText)
]
self.subtitle = [
.font(Fonts.DMSans.regular.make(13)),
.textOverflow(FittingText()),
.textColor(AppColors.Components.Banner.governanceText)
]
self.action = [
.backgroundImage([.normal("banner-cta-background")]),
.font(Fonts.DMSans.medium.make(13))
]
self.actionEdgeInsets = (0, 16, 0, 16)
self.actionHeight = 44
self.close = [
.backgroundImage([.normal("icon-governance-close-banner")])
]
self.closeMargins = (8, .noMetric, .noMetric, 8)
self.closeSize = (24, 24)
}
}
| 35.111888 | 101 | 0.660227 |
fbaf6d1cf40c104dcf4feeced0e066d40fd3cd1a | 1,805 | //
// AppearanceProvider.swift
// swift-2048
//
// Created by Austin Zheng on 6/3/14.
// Copyright (c) 2014 Austin Zheng. Released under the terms of the MIT license.
//
import UIKit
protocol AppearanceProviderProtocol: class {
func tileColor(value: Int) -> UIColor
func numberColor(value: Int) -> UIColor
func fontForNumbers() -> UIFont
}
class AppearanceProvider: AppearanceProviderProtocol {
// Provide a tile color for a given value
func tileColor(value: Int) -> UIColor {
switch value {
case 2:
return UIColor(red: 238.0/255.0, green: 228.0/255.0, blue: 218.0/255.0, alpha: 1.0)
case 4:
return UIColor(red: 237.0/255.0, green: 224.0/255.0, blue: 200.0/255.0, alpha: 1.0)
case 8:
return UIColor(red: 242.0/255.0, green: 177.0/255.0, blue: 121.0/255.0, alpha: 1.0)
case 16:
return UIColor(red: 245.0/255.0, green: 149.0/255.0, blue: 99.0/255.0, alpha: 1.0)
case 32:
return UIColor(red: 246.0/255.0, green: 124.0/255.0, blue: 95.0/255.0, alpha: 1.0)
case 64:
return UIColor(red: 246.0/255.0, green: 94.0/255.0, blue: 59.0/255.0, alpha: 1.0)
case 128, 256, 512, 1024, 2048:
return UIColor(red: 237.0/255.0, green: 207.0/255.0, blue: 114.0/255.0, alpha: 1.0)
default:
return UIColor.whiteColor()
}
}
// Provide a numeral color for a given value
func numberColor(value: Int) -> UIColor {
switch value {
case 2, 4:
return UIColor(red: 119.0/255.0, green: 110.0/255.0, blue: 101.0/255.0, alpha: 1.0)
default:
return UIColor.whiteColor()
}
}
// Provide the font to be used on the number tiles
func fontForNumbers() -> UIFont {
if let font = UIFont(name: "HelveticaNeue-Bold", size: 20) {
return font
}
return UIFont.systemFontOfSize(20)
}
}
| 30.59322 | 89 | 0.638781 |
90a0f0f31a8fb066efeaeffbb2a54a5a826db9cd | 3,010 | //
// Hash.swift
// MultistageBar
//
// Created by x on 2020/10/27.
// Copyright © 2020 x. All rights reserved.
//
import Foundation
import CommonCrypto
class Hash {
typealias shaFunc = (_ data: UnsafeRawPointer?, _ len: CC_LONG, _ md: UnsafeMutablePointer<UInt8>?) -> UnsafeMutablePointer<UInt8>?
enum Style {
case sha1
case sha256
case sha512
var digestLength: UInt32 {
switch self {
case .sha1:
return UInt32(CC_SHA1_DIGEST_LENGTH)
case .sha256:
return UInt32(CC_SHA256_DIGEST_LENGTH)
case .sha512:
return UInt32(CC_SHA512_DIGEST_LENGTH)
}
}
var SHA: shaFunc {
switch self {
case .sha1:
return CC_SHA1
case .sha256:
return CC_SHA256
case .sha512:
return CC_SHA512
}
}
var HMACAlgorithm: CCHmacAlgorithm {
let result: Int
switch self {
case .sha1:
result = kCCHmacAlgSHA1
case .sha256:
result = kCCHmacAlgSHA256
case .sha512:
result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm.init(result)
}
}
static func sha(str: String, type: Hash.Style) -> String? {
guard let temp = str.data(using: .utf8, allowLossyConversion: true) else {return nil}
return sha(data: temp, type: type)
}
static func sha(data: Data, type: Hash.Style) -> String? {
let desLength = Int(type.digestLength)
let resultPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: desLength)
defer {
resultPointer.deallocate()
}
_ = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
type.SHA(bytes.baseAddress, CC_LONG(data.count), resultPointer)
}
var result: String = ""
for i in 0..<desLength {
let temp = String.init(format: "%02x", resultPointer[i])
result += temp
}
return result
}
static func hmacSha(str: String, key: String, type: Hash.Style) -> String? {
let desLength = Int(type.digestLength)
let resultPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: desLength)
defer {
resultPointer.deallocate()
}
let keyPointer = key.cString(using: String.Encoding.utf8)!
let keyLength = key.lengthOfBytes(using: String.Encoding.utf8)
let strPointer = str.cString(using: .utf8)!
let strLength = str.lengthOfBytes(using: .utf8)
CCHmac(type.HMACAlgorithm, keyPointer, keyLength, strPointer, strLength, resultPointer)
var result: String = ""
for i in 0..<desLength {
let temp = String.init(format: "%02x", resultPointer[i])
result += temp
}
return result
}
}
| 32.365591 | 135 | 0.560797 |
d6e24b7dbc3220af67ff5a6d5a28bf9fad12fe2b | 2,926 | //
// PreferencesViewModelSpec.swift
// Rocket.Chat
//
// Created by Rafael Ramos on 31/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import XCTest
@testable import Rocket_Chat
class PreferencesViewModelSpec: XCTestCase {
let info = Bundle.main.infoDictionary
let model = PreferencesViewModel()
override func setUp() {
super.setUp()
UserDefaults.group.set(["en"], forKey: "AppleLanguages")
}
func testAppVersion() {
let version = info?["CFBundleShortVersionString"] as? String
XCTAssertEqual(model.version, version, "show app version")
}
func testBuildVersion() {
let build = info?["CFBundleVersion"] as? String
XCTAssertEqual(model.build, build, "show build version")
}
func testFormattedAppVersion() {
let build = info?["CFBundleVersion"] as? String ?? ""
let version = info?["CFBundleShortVersionString"] as? String ?? ""
let formatted = "Version: \(version) (\(build))"
XCTAssertEqual(model.formattedVersion, formatted, "show app version and build")
}
func testLicenseURL() {
let url = URL(string: "https://github.com/RocketChat/Rocket.Chat.iOS/blob/develop/LICENSE")
let modelURL = model.licenseURL
XCTAssertEqual(modelURL?.absoluteString, url?.absoluteString, "show license url")
}
func testLicenseURLNotNit() {
XCTAssertNotNil(model.licenseURL, "license URL is not nil")
}
func testCanChangeAppIcon() {
// Since we are running tests on iOS 10.3 it should always return true
XCTAssertTrue(model.canChangeAppIcon, "invalid value for canChangeAppIcon")
}
func testNumberOfRowsInSection() {
XCTAssertTrue(model.numberOfSections == 4, "incorrect sections number")
XCTAssertTrue(model.numberOfRowsInSection(0) == 1, "incorrect rows number")
XCTAssertTrue(model.numberOfRowsInSection(1) == 4, "incorrect rows number")
XCTAssertTrue(model.numberOfRowsInSection(2) == 2, "incorrect rows number")
XCTAssertTrue(model.numberOfRowsInSection(3) == 1, "incorrect rows number")
}
func testStringsOverall() {
XCTAssertNotNil(model.title)
XCTAssertNotEqual(model.title, "")
XCTAssertNotNil(model.contactus)
XCTAssertNotEqual(model.contactus, "")
XCTAssertNotNil(model.license)
XCTAssertNotEqual(model.license, "")
XCTAssertNotNil(model.supportEmail)
XCTAssertNotEqual(model.supportEmail, "")
XCTAssertNotNil(model.supportEmailBody)
XCTAssertNotEqual(model.supportEmailBody, "")
XCTAssertNotNil(model.supportEmailSubject)
XCTAssertNotEqual(model.supportEmailSubject, "")
XCTAssertNotNil(model.appicon)
XCTAssertNotEqual(model.appicon, "")
XCTAssertNotNil(model.webBrowser)
XCTAssertNotEqual(model.webBrowser, "")
}
}
| 32.153846 | 99 | 0.677375 |
4a30032f2e6ef7d54671fa65fe76ab1364c61556 | 2,973 | // -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// FIXME: the test is too slow when the standard library is not optimized.
// REQUIRES: optimized_stdlib
import StdlibUnittest
import StdlibCollectionUnittest
var SliceTests = TestSuite("Collection")
let prefix: [Int] = []
let suffix: [Int] = []
func makeCollection(elements: [OpaqueValue<Int>])
-> Slice<MinimalCollection<OpaqueValue<Int>>> {
var baseElements = prefix.map(OpaqueValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(OpaqueValue.init))
let base = MinimalCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: prefix.count)
let endIndex = base.index(
base.startIndex,
offsetBy: prefix.count + elements.count)
return Slice(base: base, bounds: startIndex..<endIndex)
}
func makeCollectionOfEquatable(elements: [MinimalEquatableValue])
-> Slice<MinimalCollection<MinimalEquatableValue>> {
var baseElements = prefix.map(MinimalEquatableValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init))
let base = MinimalCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: prefix.count)
let endIndex = base.index(
base.startIndex,
offsetBy: prefix.count + elements.count)
return Slice(base: base, bounds: startIndex..<endIndex)
}
func makeCollectionOfComparable(elements: [MinimalComparableValue])
-> Slice<MinimalCollection<MinimalComparableValue>> {
var baseElements = prefix.map(MinimalComparableValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init))
let base = MinimalCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: prefix.count)
let endIndex = base.index(
base.startIndex,
offsetBy: prefix.count + elements.count)
return Slice(base: base, bounds: startIndex..<endIndex)
}
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap
resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap
SliceTests.addCollectionTests(
"Slice_Of_MinimalCollection_WithSuffix.swift.",
makeCollection: makeCollection,
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: 6
)
runAllTests()
| 34.976471 | 86 | 0.739993 |
39ab32cfe41a3bd2d785a7515551cad19a35db3e | 8,100 | //
// User.swift
// Hangover
//
// Created by Peter Sobot on 6/8/15.
// Copyright © 2015 Peter Sobot. All rights reserved.
//
import Cocoa
class User {
static let DEFAULT_NAME = "Unknown"
// A chat user.
// Handles full_name or first_name being nil by creating an approximate
// first_name from the full_name, or setting both to DEFAULT_NAME.
let id: UserID
let full_name: String
let first_name: String
let photo_url: String?
let emails: [String]
let isSelf: Bool
init(user_id: UserID, full_name: String?=nil, first_name: String?=nil, photo_url: String?, emails: [String], is_self: Bool) {
// Initialize a User.
self.id = user_id
self.full_name = full_name == nil ? User.DEFAULT_NAME : full_name!
self.first_name = first_name == nil ? self.full_name.componentsSeparatedByString(" ").first! : first_name!
if let photo_url = photo_url {
self.photo_url = "https:" + photo_url
} else {
self.photo_url = nil
}
self.emails = emails
self.isSelf = is_self
}
convenience init(entity: CLIENT_ENTITY, self_user_id: UserID?) {
// Initialize from a ClientEntity.
// If self_user_id is nil, assume this is the self user.
let user_id = UserID(chat_id: entity.id.chat_id as String, gaia_id: entity.id.gaia_id as String)
var is_self = false
if let sui = self_user_id {
is_self = sui == user_id
} else {
is_self = true
}
self.init(user_id: user_id,
full_name: entity.properties.display_name as String?,
first_name: entity.properties.first_name as String?,
photo_url: entity.properties.photo_url as String?,
emails: entity.properties.emails.map { $0 as! String },
is_self: is_self
)
}
convenience init(conv_part_data: CLIENT_CONVERSATION_PARTICIPANT_DATA, self_user_id: UserID?) {
// Initialize from ClientConversationParticipantData.
// If self_user_id is nil, assume this is the self user.
let user_id = UserID(chat_id: conv_part_data.id.chat_id as String, gaia_id: conv_part_data.id.gaia_id as String)
var is_self = false
if let sui = self_user_id {
is_self = sui == user_id
} else {
is_self = true
}
self.init(user_id: user_id,
full_name: conv_part_data.fallback_name as? String,
first_name: nil,
photo_url: nil,
emails: [],
is_self: is_self
)
}
var image: NSImage? {
get {
return ImageCache.sharedInstance.getImage(forUser: self)
}
}
}
let ClientStateUpdatedNotification = "ClientStateUpdated"
let ClientStateUpdatedNewStateKey = "ClientStateNewState"
class UserList : NSObject {
// Collection of User instances.
private let client: Client
private let self_user: User
private var user_dict: [UserID : User]
init(client: Client, self_entity: CLIENT_ENTITY, entities: [CLIENT_ENTITY], conv_parts: [CLIENT_CONVERSATION_PARTICIPANT_DATA]) {
// Initialize the list of Users.
// Creates users from the given ClientEntity and
// ClientConversationParticipantData instances. The latter is used only as
// a fallback, because it doesn't include a real first_name.
self.client = client
self.self_user = User(entity: self_entity, self_user_id: nil)
self.user_dict = [self.self_user.id: self.self_user]
super.init()
// Add each entity as a new User.
for entity in entities {
let user = User(entity: entity, self_user_id: self.self_user.id)
self.user_dict[user.id] = user
}
// Add each conversation participant as a new User if we didn't already
// add them from an entity.
for participant in conv_parts {
self.add_user_from_conv_part(participant)
}
print("UserList initialized with \(user_dict.count) users.")
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("on_state_update_notification:"),
name: ClientStateUpdatedNotification,
object: self.client
)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func get_user(user_id: UserID) -> User {
// Return a User by their UserID.
// Raises KeyError if the User is not available.
if let elem = self.user_dict[user_id] {
return elem
} else {
print("UserList returning unknown User for UserID \(user_id)")
return User(user_id: user_id,
full_name: User.DEFAULT_NAME,
first_name: nil,
photo_url: nil,
emails: [],
is_self: false
)
}
}
func get_all() -> [User] {
// Returns all the users known
return Array(self.user_dict.values)
}
func add_user_from_conv_part(conv_part: CLIENT_CONVERSATION_PARTICIPANT_DATA) -> User {
// Add new User from ClientConversationParticipantData
let user = User(conv_part_data: conv_part, self_user_id: self.self_user.id)
if self.user_dict[user.id] == nil {
print("Adding fallback User: \(user)")
self.user_dict[user.id] = user
}
return user
}
func on_state_update_notification(notification: NSNotification) {
if let userInfo = notification.userInfo, state_update = userInfo[ClientStateUpdatedNewStateKey as NSString] {
on_state_update(state_update as! CLIENT_STATE_UPDATE)
}
}
private func on_state_update(state_update: CLIENT_STATE_UPDATE) {
// Receive a ClientStateUpdate
if let conversation = state_update.client_conversation {
self.handle_client_conversation(conversation)
}
}
private func handle_client_conversation(client_conversation: CLIENT_CONVERSATION) {
// Receive ClientConversation and update list of users
for participant in client_conversation.participant_data {
self.add_user_from_conv_part(participant)
}
}
}
func buildUserList(client: Client, initial_data: InitialData, cb: (UserList) -> Void) {
// Return UserList from initial contact data and an additional request.
// The initial data contains the user's contacts, but there may be conversions
// containing users that are not in the contacts. This function takes care of
// requesting data for those users and constructing the UserList.
let all_entities = initial_data.entities + [initial_data.self_entity]
let present_user_ids = Set(all_entities.map {
UserID(chat_id: $0.id.chat_id as String, gaia_id: $0.id.gaia_id as String)
})
var required_user_ids = Set<UserID>()
for conv_state in initial_data.conversation_states {
required_user_ids = required_user_ids.union(Set(conv_state.conversation.participant_data.map {
UserID(chat_id: $0.id.chat_id as String, gaia_id: $0.id.gaia_id as String)
}))
}
let missing_user_ids = required_user_ids.subtract(present_user_ids)
if missing_user_ids.count > 0 {
print("Need to request additional users: \(missing_user_ids)")
client.getEntitiesByID(missing_user_ids.map { $0.chat_id }) { missing_entities in
print("Received additional users: \(missing_entities)")
cb(UserList(
client: client,
self_entity: initial_data.self_entity,
entities: initial_data.entities + missing_entities.entities,
conv_parts: initial_data.conversation_participants
))
}
} else {
cb(UserList(
client: client,
self_entity: initial_data.self_entity,
entities: initial_data.entities,
conv_parts: initial_data.conversation_participants
))
}
} | 36.32287 | 133 | 0.639877 |
094ae187ec813f3008bc1a2743d9ee6539ef7173 | 663 | //
// ContactsTableViewCell.swift
// Simplytics_Example
//
// Created by Quinton Wall on 11/24/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class ContactsTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
public var contactid: String?
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
}
@IBAction func infoButtonTapped(_ sender: Any) {
}
}
| 20.71875 | 65 | 0.660633 |
0819cb14798e3142522d019ef741e70bde60c94b | 5,181 | //
// detailsVC.swift
// CoreDataExample
//
// Created by Halil Özel on 2.07.2018.
// Copyright © 2018 Halil Özel. All rights reserved.
//
import UIKit
import CoreData // CoreData'ya ait yapıları kullanmamızı sağlıyor.
class detailsVC: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameText: UITextField!
@IBOutlet weak var cityNameText: UITextField!
@IBOutlet weak var dateText: UITextField!
var chosenTeams = ""
override func viewDidLoad() {
super.viewDidLoad()
if chosenTeams != ""{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Teams")
// name değeri chosenTeams değerine eşitse getir. Filtre uygulandı.
fetchRequest.predicate = NSPredicate(format: "name = %@", self.chosenTeams)
fetchRequest.returnsObjectsAsFaults = false
do{
let results = try context.fetch(fetchRequest)
if results.count > 0 {
for result in results as! [NSManagedObject]{
if let name = result.value(forKey: "name") as? String{
nameText.text = name
}
if let cityName = result.value(forKey: "cityname") as? String{
cityNameText.text = cityName
}
if let date = result.value(forKey: "date") as? Int{
dateText.text = String(date)
}
if let dataImage = result.value(forKey: "image") as? Data{
let image = UIImage(data: dataImage)
self.imageView.image = image
}
}
}
}catch{
print("Error")
}
}
imageView.isUserInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(detailsVC.selectedImage))
imageView.addGestureRecognizer(gestureRecognizer)
}
@objc func selectedImage(){ // resim secme islemi yapılıyor.
let picker = UIImagePickerController() // picker nesnesi olusturuldu.
picker.delegate = self
picker.sourceType = .photoLibrary // daha önceden cekilmis fotoları kutuphaneden alır.
picker.allowsEditing = true // resimlere edit işlemi yapsın mı ?
present(picker, animated: true, completion: nil) // Bir denetleyici modu sunar.
}
// image secildikten sonraki işlemler
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imageView.image = info[UIImagePickerControllerEditedImage] as? UIImage //sectiğin yapı resim
self.dismiss(animated: true, completion: nil) // sectikten sonra kapat
}
@IBAction func saveClicked(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate //app delegate değişkeni olarak tanımladık.
let context = appDelegate.persistentContainer.viewContext // context değeri tanımlanıyor.
// core data işleminde kullanılacak yapı eşleniyor.
let newTeams = NSEntityDescription.insertNewObject(forEntityName: "Teams", into: context)
// attributes
// string ifadeleri kayıt etme
newTeams.setValue(nameText.text, forKey: "name")
newTeams.setValue(cityNameText.text, forKey: "cityname")
// integer ifadeyi kayıt etme
if let year = Int(dateText.text!){
newTeams.setValue(year, forKey: "date")
}
// image ifadeyi kayıt etme
let data = UIImageJPEGRepresentation(imageView.image!, 0.5) // ikinci parametre sıkıstırma miktarı
newTeams.setValue(data, forKey: "image")
do{ // bir hata olursa
try context.save() // context değerini kayıt et
print("succesful")
}catch{ // hatayı bastır
print("error")
}
// burada verilen değeri karşı tarafta eşleyip sayfası yenileme işlemi yapacağız.
NotificationCenter.default.post(name: NSNotification.Name(rawValue : "newTeams"), object: nil)
self.navigationController?.popViewController(animated: true) // bulunduğun yerden bir öncekine git.
}
}
| 35.979167 | 119 | 0.550473 |
38805bf7b4432644410eb45fa1d8f17fb46cf865 | 6,976 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import XCTest
class TestSearchTopicsOnline: TestOnlineHome {
private var search: Search!
private var trendingTopics: TrendingTopicsFeed!
override func setUp() {
super.setUp()
feedName = "SearchTopics"
search = Search(app)
trendingTopics = TrendingTopicsFeed(app)
}
override func openScreen() {
navigate(to: .search)
search.search(feedName, for: .topics)
sleep(1)
}
func testSearchQuerySavedToHistory() {
openScreen()
// we should already have at least one item in search
let searchHistory = search.getHistory()
XCTAssertTrue(searchHistory.getItemsCount() != 0)
let lastSearchQuery = searchHistory.getItem(at: 0).getQuery()
XCTAssertEqual(feedName, lastSearchQuery)
}
func testSearchFromSearchHistory() {
openScreen()
let searchHistoryItem = search.getHistory().getItem(at: 0)
let searchQuery = searchHistoryItem.getQuery()
searchHistoryItem.asUIElement().tap()
let (index, post) = feed.getRandomItem()
XCTAssertEqual(post.getTitle().label, "\(searchQuery)\(index)")
}
func testTrendingTopicsSource() {
navigate(to: .search)
let (index, topic) = trendingTopics.getRandomItem()
XCTAssertEqual("#hashtag\(index)", topic.getName())
}
func testSearchByTrendingTopic() {
navigate(to: .search)
let (_, topic) = trendingTopics.getRandomItem()
let topicName = topic.getName()
topic.asUIElement().tap()
let (index, post) = feed.getRandomItem()
XCTAssertEqual(post.getTitle().label, "\(topicName)\(index)")
}
}
class TestSearchTopicsOffline: TestOfflineHome {
private var search: Search!
private var trendingTopics: TrendingTopicsFeed!
override func setUp() {
super.setUp()
feedName = "SearchTopics"
search = Search(app)
trendingTopics = TrendingTopicsFeed(app)
}
override func openScreen() {
navigate(to: .search)
search.search(feedName, for: .topics)
sleep(1)
}
func testSearchQuerySavedToHistory() {
navigate(to: .search)
makePullToRefreshWithoutReachability(with: trendingTopics.asUIElement())
search.search("OfflineSearch", for: .topics)
let history = search.getHistory()
XCTAssertEqual("OfflineSearch", history.getItem(at: 0).getQuery())
}
func testSearchFromSearchHistory() {
openScreen()
var needReachabilityDisabling = true
for _ in 1...2 {
// load topics online on first iteration
let searchHistoryItem = search.getHistory().getItem(at: 0)
let searchQuery = searchHistoryItem.getQuery()
searchHistoryItem.asUIElement().tap()
if needReachabilityDisabling {
makePullToRefreshWithoutReachability(with: feed.asUIElement())
needReachabilityDisabling = false
continue
}
let (index, post) = feed.getRandomItem()
XCTAssertEqual(post.getTitle().label, "\(searchQuery)\(index)")
}
}
func testTrendingTopicsSource() {
navigate(to: .search)
makePullToRefreshWithoutReachability(with: trendingTopics.asUIElement())
let (index, topic) = trendingTopics.getRandomItem()
XCTAssertEqual("#hashtag\(index)", topic.getName())
}
func testSearchByTrendingTopic() {
navigate(to: .search)
var needReachabilityDisabling = true
for _ in 1...2 {
let topic = trendingTopics.getItem(at: 0)
let topicName = topic.getName()
topic.asUIElement().tap()
if needReachabilityDisabling {
makePullToRefreshWithoutReachability(with: trendingTopics.asUIElement())
needReachabilityDisabling = false
search.clear()
navigate(to: .home)
navigate(to: .search)
continue
}
let (index, post) = feed.getRandomItem()
XCTAssertEqual(post.getTitle().label, "\(topicName)\(index)")
}
}
}
class TestSearchPeopleOnline: TestFollowersOnline {
private var search: Search!
override func setUp() {
super.setUp()
feedName = "SearchPeople "
feedHandle = "SearchPeople"
search = Search(app)
}
override func openScreen() {
navigate(to: .search)
search.search(feedName, for: .people)
sleep(1)
}
func testSuggestedUsersSource() {
navigate(to: .search)
search.select(item: .people)
let (index, follower) = followersFeed.getRandomItem()
XCTAssertTrue(follower.isExists("Suggested User\(index)"))
}
func testSuggestedUserFollowing() {
navigate(to: .search)
search.select(item: .people)
feedHandle = "SuggestedUser"
let (index, follower) = followersFeed.getRandomItem()
follower.follow()
checkIsFollowed(follower, at: index)
follower.follow()
checkIsUnfollowed(follower, at: index)
}
}
class TestSearchPeopleOffline: TestFollowersOffline {
private var search: Search!
override func setUp() {
super.setUp()
feedName = "SearchPeople "
feedHandle = "SearchPeople"
search = Search(app)
}
override func openScreen() {
navigate(to: .search)
search.search(feedName, for: .people)
sleep(1)
}
func testSuggestedUsersSource() {
navigate(to: .search)
search.select(item: .people)
makePullToRefreshWithoutReachability(with: followersFeed.asUIElement())
let (index, follower) = followersFeed.getRandomItem()
XCTAssertTrue(follower.isExists("Suggested User\(index)"))
}
func testSuggestedUserFollowing() {
navigate(to: .search)
search.select(item: .people)
feedHandle = "SuggestedUser"
makePullToRefreshWithoutReachability(with: followersFeed.asUIElement())
sleep(1)
let (index, follower) = followersFeed.getRandomItem()
follower.follow()
checkIsFollowed(follower, at: index)
follower.follow()
checkIsUnfollowed(follower, at: index)
}
}
| 27.904 | 91 | 0.582569 |
fea79f48513840c73a46ab8b7daa65650138b6e3 | 3,197 | //
// RxTest.swift
// RxTests
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTests
import Foundation
#if TRACE_RESOURCES
#elseif RELEASE
#elseif os(Linux)
#else
let failure = unhandled_case()
#endif
// because otherwise OSX unit tests won't run
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
class RxTest
: XCTestCase {
#if os(Linux)
var allTests : [(String, () throws -> Void)] = []
#endif
fileprivate var startResourceCount: Int32 = 0
var accumulateStatistics: Bool {
return true
}
#if TRACE_RESOURCES
static var totalNumberOfAllocations: Int64 = 0
static var totalNumberOfAllocatedBytes: Int64 = 0
var startNumberOfAllocations: Int64 = 0
var startNumberOfAllocatedBytes: Int64 = 0
#endif
#if os(Linux)
func setUp() {
setUpActions()
}
func tearDown() {
tearDownActions()
}
#else
override func setUp() {
super.setUp()
setUpActions()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
tearDownActions()
}
#endif
}
extension RxTest {
struct Defaults {
static let created = 100
static let subscribed = 200
static let disposed = 1000
}
func sleep(_ time: TimeInterval) {
RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: time))
}
func setUpActions(){
#if TRACE_RESOURCES
self.startResourceCount = resourceCount
//registerMallocHooks()
(startNumberOfAllocatedBytes, startNumberOfAllocations) = getMemoryInfo()
#endif
}
func tearDownActions() {
#if TRACE_RESOURCES
// give 5 sec to clean up resources
for _ in 0..<30 {
if self.startResourceCount < resourceCount {
// main schedulers need to finish work
print("Waiting for resource cleanup ...")
RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate(timeIntervalSinceNow: 0.05) as Date)
}
else {
break
}
}
XCTAssertEqual(self.startResourceCount, resourceCount)
let (endNumberOfAllocatedBytes, endNumberOfAllocations) = getMemoryInfo()
let (newBytes, newAllocations) = (endNumberOfAllocatedBytes - startNumberOfAllocatedBytes, endNumberOfAllocations - startNumberOfAllocations)
if accumulateStatistics {
RxTest.totalNumberOfAllocations += newAllocations
RxTest.totalNumberOfAllocatedBytes += newBytes
}
print("allocatedBytes = \(newBytes), allocations = \(newAllocations) (totalBytes = \(RxTest.totalNumberOfAllocatedBytes), totalAllocations = \(RxTest.totalNumberOfAllocations))")
#endif
}
}
| 26.865546 | 190 | 0.612449 |
6ab0ccb26b9ce9b82fa08c7e96cb78fddf4c580d | 4,572 | // Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
/// Give a chance to react when coach marks are displayed
public protocol CoachMarksControllerDelegate: class {
func coachMarksController(_ coachMarksController: CoachMarksController,
configureOrnamentsOfOverlay overlay: UIView)
func coachMarksController(_ coachMarksController: CoachMarksController,
willLoadCoachMarkAt index: Int) -> Bool
func coachMarksController(_ coachMarksController: CoachMarksController,
willShow coachMark: inout CoachMark,
beforeChanging change: ConfigurationChange,
at index: Int)
func coachMarksController(_ coachMarksController: CoachMarksController,
didShow coachMark: CoachMark,
afterChanging change: ConfigurationChange,
at index: Int)
func coachMarksController(_ coachMarksController: CoachMarksController,
willHide coachMark: CoachMark,
at index: Int)
func coachMarksController(_ coachMarksController: CoachMarksController,
didHide coachMark: CoachMark,
at index: Int)
func coachMarksController(_ coachMarksController: CoachMarksController,
didEndShowingBySkipping skipped: Bool)
func shouldHandleOverlayTap(in coachMarksController: CoachMarksController,
at index: Int) -> Bool
}
public extension CoachMarksControllerDelegate {
func coachMarksController(_ coachMarksController: CoachMarksController,
configureOrnamentsOfOverlay overlay: UIView) { }
func coachMarksController(_ coachMarksController: CoachMarksController,
willLoadCoachMarkAt index: Int) -> Bool {
return true
}
func coachMarksController(_ coachMarksController: CoachMarksController,
willShow coachMark: inout CoachMark,
afterSizeTransition: Bool,
at index: Int) { }
func coachMarksController(_ coachMarksController: CoachMarksController,
didShow coachMark: CoachMark,
afterSizeTransition: Bool,
at index: Int) { }
func coachMarksController(_ coachMarksController: CoachMarksController,
willShow coachMark: inout CoachMark,
beforeChanging change: ConfigurationChange,
at index: Int) { }
func coachMarksController(_ coachMarksController: CoachMarksController,
didShow coachMark: CoachMark,
afterChanging change: ConfigurationChange,
at index: Int) { }
func coachMarksController(_ coachMarksController: CoachMarksController,
willHide coachMark: CoachMark,
at index: Int) { }
func coachMarksController(_ coachMarksController: CoachMarksController,
didHide coachMark: CoachMark,
at index: Int) { }
func coachMarksController(_ coachMarksController: CoachMarksController,
didEndShowingBySkipping skipped: Bool) { }
func shouldHandleOverlayTap(in coachMarksController: CoachMarksController,
at index: Int) -> Bool {
return true
}
}
protocol CoachMarksControllerProxyDelegate: class {
func configureOrnaments(ofOverlay: UIView)
func willLoadCoachMark(at index: Int) -> Bool
func willShow(coachMark: inout CoachMark, afterSizeTransition: Bool, at index: Int)
func didShow(coachMark: CoachMark, afterSizeTransition: Bool, at index: Int)
func willShow(coachMark: inout CoachMark, beforeChanging change: ConfigurationChange,
at index: Int)
func didShow(coachMark: CoachMark, afterChanging change: ConfigurationChange, at index: Int)
func willHide(coachMark: CoachMark, at index: Int)
func didHide(coachMark: CoachMark, at index: Int)
func didEndShowingBySkipping(_ skipped: Bool)
func shouldHandleOverlayTap(at index: Int) -> Bool
}
| 42.728972 | 96 | 0.615923 |
8ab1e0919dec1b045c17e092a966294746f3a967 | 2,917 | //
// UIView+Transform.swift
// Resizable
//
// Created by Caroline on 6/09/2014.
// Copyright (c) 2014 Caroline. All rights reserved.
//
//Credits:
//Erica Sadun: http://www.informit.com/articles/article.aspx?p=1951182
//Brad Larson / Magnus: http://stackoverflow.com/a/5666430/359578
import Foundation
import UIKit
extension UIView {
func offsetPointToParentCoordinates(_ point: CGPoint) -> CGPoint {
return CGPoint(x: point.x + self.center.x, y: point.y + self.center.y)
}
func pointInViewCenterTerms(_ point:CGPoint) -> CGPoint {
return CGPoint(x: point.x - self.center.x, y: point.y - self.center.y)
}
func pointInTransformedView(_ point: CGPoint) -> CGPoint {
let offsetItem = self.pointInViewCenterTerms(point)
let updatedItem = offsetItem.applying(self.transform)
let finalItem = self.offsetPointToParentCoordinates(updatedItem)
return finalItem
}
func originalFrame() -> CGRect {
let currentTransform = self.transform
self.transform = CGAffineTransform.identity
let originalFrame = self.frame
self.transform = currentTransform
return originalFrame
}
//These four methods return the positions of view elements
//with respect to the current transformation
func transformedTopLeft() -> CGPoint {
let frame = self.originalFrame()
let point = frame.origin
return self.pointInTransformedView(point)
}
func transformedTopRight() -> CGPoint {
let frame = self.originalFrame()
var point = frame.origin
point.x += frame.size.width
return self.pointInTransformedView(point)
}
func transformedBottomRight() -> CGPoint {
let frame = self.originalFrame()
var point = frame.origin
point.x += frame.size.width
point.y += frame.size.height
return self.pointInTransformedView(point)
}
func transformedBottomLeft() -> CGPoint {
let frame = self.originalFrame()
var point = frame.origin
point.y += frame.size.height
return self.pointInTransformedView(point)
}
func transformedRotateHandle() -> CGPoint {
let frame = self.originalFrame()
var point = frame.origin
point.x += frame.size.width + 40
point.y += frame.size.height / 2
return self.pointInTransformedView(point)
}
func setAnchorPoint(_ anchorPoint:CGPoint) {
var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)
newPoint = newPoint.applying(self.transform)
oldPoint = oldPoint.applying(self.transform)
var position = self.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
self.layer.position = position
self.layer.anchorPoint = anchorPoint
}
}
| 29.765306 | 135 | 0.70072 |
39a5139113e5888947ed8b0a7c7a139ada1be0c8 | 1,423 | //
// RequestHistory'.swift
// NetAnalyser
//
// Created by Lucas Paim on 04/05/20.
//
import Foundation
public struct RequestHistory {
public let startTime: Date
public let endTime: Date
public let httpStatus: Int?
public let body: String?
public let response: String?
public let errorDescription: String?
public let curl: String?
public let request: Request
public let id: Int?
public init(request: Request, startTime: Date, endTime: Date, httpStatus: Int?,
body: String?, response: String?,
errorDescription: String?, curl: String?) {
self.startTime = startTime
self.endTime = endTime
self.httpStatus = httpStatus
self.body = body
self.response = response
self.errorDescription = errorDescription
self.curl = curl
self.request = request
self.id = nil
}
init(request: Request, startTime: Date, endTime: Date, httpStatus: Int?,
body: String?, response: String?,
errorDescription: String?, curl: String?, id: Int) {
self.startTime = startTime
self.endTime = endTime
self.httpStatus = httpStatus
self.body = body
self.response = response
self.errorDescription = errorDescription
self.curl = curl
self.request = request
self.id = id
}
}
| 26.351852 | 83 | 0.607871 |
713baf5360e4a94f8aaa4b4aa404a10999b90d84 | 1,026 | //
// VaporExtTests.swift
// VaporExt
//
// Created by Gustavo Perdomo on 07/28/18.
// Copyright © 2018 Vapor Community. All rights reserved.
//
import XCTest
@testable import VaporExt
final class StubTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(true, true)
}
func testLinuxTestSuiteIncludesAllTests() throws {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let thisClass = type(of: self)
let linuxCount = thisClass.allTests.count
let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount)
XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests")
#endif
}
static let allTests = [
("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests),
("testExample", testExample)
]
}
| 29.314286 | 110 | 0.67154 |
e69f5ad59f2a9c1b15ccb2ba9aaf851f47b8a055 | 1,796 | // Copyright © MonitorControl. @JoniVR, @theOneyouseek, @waydabber and others
import Cocoa
public extension NSScreen {
var displayID: CGDirectDisplayID {
return (self.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID)!
}
var vendorNumber: UInt32? {
switch CGDisplayVendorNumber(self.displayID) {
case 0xFFFF_FFFF:
return nil
case let vendorNumber:
return vendorNumber
}
}
var modelNumber: UInt32? {
switch CGDisplayModelNumber(self.displayID) {
case 0xFFFF_FFFF:
return nil
case let modelNumber:
return modelNumber
}
}
var serialNumber: UInt32? {
switch CGDisplaySerialNumber(self.displayID) {
case 0x0000_0000:
return nil
case let serialNumber:
return serialNumber
}
}
var displayName: String? {
var servicePortIterator = io_iterator_t()
let status = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"), &servicePortIterator)
guard status == KERN_SUCCESS else {
return nil
}
defer {
assert(IOObjectRelease(servicePortIterator) == KERN_SUCCESS)
}
while case let object = IOIteratorNext(servicePortIterator), object != 0 {
let dict = (IODisplayCreateInfoDictionary(object, UInt32(kIODisplayOnlyPreferredName)).takeRetainedValue() as NSDictionary as? [String: AnyObject])!
if dict[kDisplayVendorID] as? UInt32 == self.vendorNumber, dict[kDisplayProductID] as? UInt32 == self.modelNumber, dict[kDisplaySerialNumber] as? UInt32 == self.serialNumber {
if let productName = dict["DisplayProductName"] as? [String: String], let firstKey = Array(productName.keys).first {
return productName[firstKey]!
}
}
}
return nil
}
}
| 28.967742 | 181 | 0.704343 |
0e1f1cd70ad5c8a4f87ce41cafac8093c66e833d | 2,287 | //
// SceneDelegate.swift
// Prework
//
// Created by Cole Perez on 9/22/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.150943 | 147 | 0.712287 |
23b1cc1654dd941b64e01925cf84b791ca2a0715 | 3,848 | //
// MGPageInfo.swift
// mgbaseproject
//
// Created by Magical Water on 2018/1/30.
// Copyright © 2018年 Magical Water. All rights reserved.
//
import Foundation
import UIKit
/*
頁面相關資訊, 通常與 MGUrlRequest 綁一起
*/
public class MGPageInfo {
//頁面實體化的 story board
public var page: UIStoryboard
//在story board裡面有多個vc, 此時要借用idientfier判別是哪個vc
public var pageIdientfier: String?
//頁面的類型, 為裝載 Fragment 的 view id
public var containerId: String
//頁面的標籤, 判別頁面的tag
//因此每個頁面都必須設置
public var pageTag: String
//頁面的標題
public var pageTitle: String
//此次跳轉是否加入歷史紀錄, 歷史紀錄用來返回上一頁
public var inHistory: Bool
//是否為返回上一頁, 不可主動設定, 此參數給 FgtManager 在跳回上一頁時設定
public var isPageBack: Bool = false
//此頁面是否需要登入
public var needLogin: Bool
//頁面是否為節點, 若是節點則會清除掉之前所有的歷史跳轉
public var isChainNode: Bool
//此次跳轉資料是否可重複使用
public var dataReuse: Bool
//有任何東西需要攜帶的直接放入此array
private var attachData: [String:Any] = [:]
private init(_ page: UIStoryboard,
idientifier: String?,
containerId: String,
pageTag: String,
pageTitle: String,
inHistory: Bool,
needLogin: Bool,
isNode: Bool,
dataReuse: Bool) {
self.page = page
self.pageIdientfier = idientifier
self.containerId = containerId
self.pageTag = pageTag
self.pageTitle = pageTitle
self.inHistory = inHistory
self.needLogin = needLogin
self.isChainNode = isNode
self.dataReuse = dataReuse
}
public func addAttachData(_ key: String, data: Any) {
attachData[key] = data
}
public func getAttachData<T>(_ key: String) -> T? {
return attachData[key] as? T
}
public class MGPageInfoBuilder {
private var page: UIStoryboard!
private var pageIdientfier: String?
private var containerId: String = ""
private var pageTag: String = ""
private var pageTitle: String = ""
private var inHistory: Bool = true
private var needLogin: Bool = false
private var isChainNode: Bool = false
private var dataReuse: Bool = true
public init() {}
public func setPage(_ page: UIStoryboard, idientfier: String? = nil) -> MGPageInfoBuilder {
self.page = page
self.pageIdientfier = idientfier
return self
}
public func setContainer(_ viewId: String) -> MGPageInfoBuilder {
self.containerId = viewId
return self
}
public func setPageTitle(_ title: String) -> MGPageInfoBuilder {
self.pageTitle = title
return self
}
public func setPageTag(_ tag: String) -> MGPageInfoBuilder {
self.pageTag = tag
return self
}
public func setHistory(_ inHistory: Bool) -> MGPageInfoBuilder {
self.inHistory = inHistory
return self
}
public func setNeedLogin(_ login: Bool) -> MGPageInfoBuilder {
self.needLogin = login
return self
}
public func setChainNode(_ isNode: Bool) -> MGPageInfoBuilder {
self.isChainNode = isNode
return self
}
public func setDataReuse(_ reuseable: Bool) -> MGPageInfoBuilder {
self.dataReuse = reuseable
return self
}
public func build() -> MGPageInfo {
return MGPageInfo.init(page, idientifier: pageIdientfier, containerId: containerId,
pageTag: pageTag, pageTitle: pageTitle, inHistory: inHistory,
needLogin: needLogin, isNode: isChainNode, dataReuse: dataReuse)
}
}
}
| 26.537931 | 99 | 0.594335 |
bf36e9d7cd48e244fc5d25991cd80ccee2c58c8b | 3,297 | //
// View+FWFramework.swift
// FWFramework
//
// Created by wuyong on 2020/11/9.
// Copyright © 2020 wuyong.site. All rights reserved.
//
#if canImport(SwiftUI)
import SwiftUI
// MARK: - FWNavigationBarModifier
/// 导航栏背景色修改器
@available(iOS 13.0, *)
public struct FWNavigationBarModifier: ViewModifier {
var backgroundColor: UIColor?
public init(backgroundColor: UIColor?) {
self.backgroundColor = backgroundColor
}
public func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
Color(self.backgroundColor ?? .clear)
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
// MARK: - FWLineShape
/// 线条形状,用于分割线、虚线等。自定义路径形状:Path { (path) in ... }
@available(iOS 13.0, *)
public struct FWLineShape: Shape {
public var axes: Axis.Set = .horizontal
public func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 0, y: 0))
if axes == .horizontal {
path.addLine(to: CGPoint(x: rect.width, y: 0))
} else {
path.addLine(to: CGPoint(x: 0, y: rect.height))
}
return path
}
}
// MARK: - FWRoundedCornerShape
/// 不规则圆角形状
@available(iOS 13.0, *)
public struct FWRoundedCornerShape: Shape {
public var radius: CGFloat = 0
public var corners: UIRectCorner = .allCorners
public func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
return Path(path.cgPath)
}
}
@available(iOS 13.0, *)
public extension View {
/// 设置导航栏通用样式。背景色有值时为全局样式,无法修改;为nil时透明,需各页面设置;文字颜色有值时为全局样式
func fwNavigationBarAppearance(backgroundColor: UIColor?, titleColor: UIColor?) -> some View {
let coloredAppearance = UINavigationBarAppearance()
coloredAppearance.configureWithTransparentBackground()
if let backgroundColor = backgroundColor {
coloredAppearance.backgroundColor = backgroundColor
}
if let titleColor = titleColor {
coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor]
coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor]
UINavigationBar.appearance().tintColor = titleColor
}
UINavigationBar.appearance().standardAppearance = coloredAppearance
UINavigationBar.appearance().compactAppearance = coloredAppearance
UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
return self
}
/// 设置单个页面导航栏背景色,未指定通用样式时生效
func fwNavigationBarColor(backgroundColor: UIColor?) -> some View {
self.modifier(FWNavigationBarModifier(backgroundColor: backgroundColor))
}
/// 设置不规则圆角效果
func fwCornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape(FWRoundedCornerShape(radius: radius, corners: corners))
}
/// 转换为AnyView
func fwEraseToAnyView() -> AnyView {
AnyView(self)
}
}
#endif
| 29.702703 | 130 | 0.635729 |
0a3ed308eb3bba22776eb9d495d694f378a9460d | 2,205 | //
// AppDelegate.swift
// GettingStarted
//
// Created by Guillermo Alcalá Gamero on 15/12/2018.
// Copyright © 2018 Guillermo Alcalá Gamero. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.914894 | 285 | 0.75737 |
398d9fd6fba8f3cc2cc871be51619978eca06e64 | 5,029 | import Cocoa
import os.log
///
/// The Application Delegate of this application.
///
/// HINT: The application main class is MyCloudNotes. This class should only
/// handle GUI aspects of the application.
///
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Application
///
/// The main application.
///
private var myCloudNotes: MyCloudNotes { get { return MyCloudNotes.shared } }
// MARK: - Views
///
/// The ViewController.
///
/// Used to access the 'Notes Controller'. The value is injected by the
/// ViewController.
///
/// HINT: What is the 'right' method to access another controller?
/// In this case a menu entry is connected to an action in this class.
/// The action redirects to the other controller and its
/// NSArrayController (IBOutlet).
///
var viewController: ViewController?
/// The main window
///
private var window: NSWindow { get { return NSApplication.shared.mainWindow! } }
///
/// The MenuItem to trigger a synchronization
///
@IBOutlet weak var synchronizationMenuItem: NSMenuItem!
///
/// Notification Center.
///
let notificationCenter = NotificationCenter.default
// MARK: -
///
/// Remove all observers
///
deinit {
removeObserverForStatusOfSynchronizationMenuItem()
}
// MARK: - NSApplicationDelegate
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
addObserverForStatusOfSynchronizationMenuItem()
if UserDefaults.standard.bool(forKey: UserDefaults.MyCloudNotes.Key.synchronizeOnStartAndQuit) {
// FIXME: Don't use a dummy request to skip the first failed request
//
// The first immediate request (Synchronize on start) of this
// application always fails. To fix this:
// - Fire a 'dummy' request like ping. Helps
// - wait a second. Helps
// - use SessionManager.default in CloudNoteService. Helps.
// But this blocks a custom trust policy. Copying and customizing
// the code of 'SessionManager.default' doesn't help
//
// Scenario: macOS 10.12.6, self signed server certificate from
// self signed trusted certificate authority
// ('always trusted' in macOS keychain)
CloudNotesService.standard.sessionManager
.request(CloudNotesService.Request.ping)
.responseData { response in self.myCloudNotes.synchronizeNotes() }
}
}
///
/// Synchronize notes and saves changes in the application's managed object
/// context before the application terminates.
///
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
///
/// Saves the notes and notifies the application.
///
func finalSave() {
let quitAnyway = self.myCloudNotes.save { error in
return SaveAlert().selectedQuitAnyway()
}
NSApplication.shared.reply(toApplicationShouldTerminate: quitAnyway)
}
if UserDefaults.standard.bool(forKey: UserDefaults.MyCloudNotes.Key.synchronizeOnStartAndQuit) {
myCloudNotes.synchronizeNotes(
success: { finalSave() },
failure: { error in finalSave() } )
} else {
finalSave()
}
return .terminateLater
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
// MARK: - Actions
///
/// Create new note.
///
/// Called from menu entry 'New'.
///
@IBAction func newNote(_ sender: Any) {
viewController?.notesController.add(sender)
}
///
/// Import notes.
///
/// Called from menu entry 'Import…'.
///
@IBAction func importNote(_ sender: Any) {
let panel = NSOpenPanel.forNotes()
panel.beginSheetModal(for: window) { result in
if result == NSApplication.ModalResponse.OK {
self.myCloudNotes.importNotes(urls: panel.urls)
}
}
}
///
/// Export notes.
///
/// Called from menu entry 'Export…'.
///
@IBAction func exportNote(_ sender: Any) {
guard
let selectedObjects = viewController?.notesController.selectedObjects, !selectedObjects.isEmpty,
let note = selectedObjects[0] as? Note else {
os_log("Can't export note. Can't find a selected note.", type: .error)
return
}
let panel = NSSavePanel(note: note)
panel.beginSheetModal(for: window, completionHandler: { result in
if result == NSApplication.ModalResponse.OK {
guard let url = panel.url else {
os_log("Can't export note. The url is corrupt.", type: .error)
return
}
self.myCloudNotes.exportNote(note: note, url: url)
}
})
}
///
/// Synchronize notes.
///
/// Called from menu entry 'Synchronize'.
///
@IBAction func synchronizeNotes(_ sender: NSMenuItem) {
myCloudNotes.synchronizeNotes()
}
///
/// Move focus to search field.
///
/// Called from menu entry 'Find note…'
///
@IBAction func findNote(_ sender: NSMenuItem) {
viewController?.searchField.selectText(sender)
}
}
| 26.192708 | 99 | 0.691986 |
debd02a1896d1beea415b6c55e363b8e4416e49d | 2,234 | // APIs.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
open class OpenAPIClientAPI {
public static var basePath = "http://127.0.0.1:9308"
public static var credential: URLCredential?
public static var customHeaders: [String:String] = [:]
public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory()
public static var apiResponseQueue: DispatchQueue = .main
}
open class RequestBuilder<T> {
var credential: URLCredential?
var headers: [String:String]
public let parameters: [String:Any]?
public let isBody: Bool
public let method: String
public let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
/// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0.
/// If you need to get the request's progress in older OS versions, please use Alamofire http client.
public var onProgressReady: ((Progress) -> ())?
required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
self.headers = headers
addHeaders(OpenAPIClientAPI.customHeaders)
}
open func addHeaders(_ aHeaders:[String:String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
open func execute(_ apiResponseQueue: DispatchQueue = OpenAPIClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result<Response<T>, Error>) -> Void) { }
public func addHeader(name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
open func addCredential() -> Self {
self.credential = OpenAPIClientAPI.credential
return self
}
}
public protocol RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type
func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type
}
| 34.369231 | 174 | 0.68308 |
ed0a34926547bdb3018908f61e67ad1b76321860 | 1,446 | //
// CodableStore+AccessControl.swift
// CodableStoreKit
//
// Created by Sven Tiigi on 19.03.19.
// Copyright © 2019 CodableStoreKit. All rights reserved.
//
import Foundation
// MARK: - CodableStore+AccessControl
public extension CodableStore {
/// The AccessControl
struct AccessControl {
/// The CodableStore
let codableStore: CodableStore<Storable>
/// The SaveableCodableStore
public var saveable: SaveableCodableStore<Storable> {
return .init(self.codableStore)
}
/// The DeletableCodableStore
public var deletable: DeletableCodableStore<Storable> {
return .init(self.codableStore)
}
/// The WritableCodableStore
public var writable: WritableCodableStore<Storable> {
return .init(self.codableStore)
}
/// The ReadableCodableStore
public var readable: ReadableCodableStore<Storable> {
return .init(self.codableStore)
}
/// The ObservableCodableStore
public var observable: ObservableCodableStore<Storable> {
return .init(self.codableStore)
}
}
}
// MARK: - CodableStore+AccessControl Property
public extension CodableStore {
/// The AccessControl
var accessControl: AccessControl {
return .init(codableStore: self)
}
}
| 24.1 | 65 | 0.613416 |
267df6a2a8e8fdbc08648ebbf414b19fcd5ddbfa | 550 | //
// WormholyTests.swift
// Wormholy
//
// Created by Paolo Musolino on {TODAY}.
// Copyright © 2018 Wormholy. All rights reserved.
//
import Foundation
import XCTest
import Wormholy
class WormholyTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
//// XCTAssertEqual(Wormholy().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 22.916667 | 96 | 0.656364 |
29298aa3799575d6cf8e7d24b9b897c73140332f | 1,039 | #if canImport(AppKit)
import AppKit
import ReactiveSwift
extension Reactive where Base: NSTextView {
private var notifications: Signal<Notification, Never> {
#if swift(>=4.0)
let name = NSTextView.didChangeNotification
#else
let name = Notification.Name.NSControlTextDidChange
#endif
return NotificationCenter.default
.reactive
.notifications(forName: name, object: base)
.take(during: lifetime)
}
/// A signal of values in `String` from the text field upon any changes.
public var continuousStringValues: Signal<String, Never> {
return notifications
.map { notification in
let textView = notification.object as! NSTextView
#if swift(>=4.0)
return textView.string
#else
return textView.string ?? ""
#endif
}
}
/// A signal of values in `NSAttributedString` from the text field upon any
/// changes.
public var continuousAttributedStringValues: Signal<NSAttributedString, Never> {
return notifications
.map { ($0.object as! NSTextView).attributedString() }
}
}
#endif
| 25.341463 | 81 | 0.72666 |
d5121120b698092227a5d93abff7f80e35ee2f68 | 555 | //
// ViewController.swift
// Variables
//
// Created by Todd Perkins on 4/19/19.
// Copyright © 2019 Todd Perkins. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let myStr: String = "String Value"
let myInt: Int = 123
label1.text = myStr
label2.text = "\(myInt)"
}
}
| 19.821429 | 58 | 0.621622 |
9bc98b16091239ed49321d6f1a0c495d6db96de6 | 6,940 | import Foundation
import HKDF
import Logging
import SRP
fileprivate let logger = Logger(label: "hap.controllers.pair-setup")
class PairSetupController {
struct Session {
let server: SRP.Server
}
enum Error: Swift.Error {
case invalidParameters
case invalidPairingMethod
case couldNotDecryptMessage
case couldNotDecodeMessage
case couldNotSign
case couldNotEncrypt
case alreadyPaired
case alreadyPairing
case invalidSetupState
case authenticationFailed
}
let device: Device
public init(device: Device) {
self.device = device
}
func startRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8 {
guard let method = data[.pairingMethod]?.first.flatMap({ PairingMethod(rawValue: $0) }) else {
throw Error.invalidParameters
}
// TODO: according to spec, this should be `method == .pairSetup`
guard method == .default else {
throw Error.invalidPairingMethod
}
// If the accessory is already paired it must respond with
// Error_Unavailable
if device.pairingState == .paired {
throw Error.alreadyPaired
}
// If the accessory has received more than 100 unsuccessful
// authentication attempts it must respond with
// Error_MaxTries
// TODO
// If the accessory is currently performing a Pair Setup operation with
// a different controller it must respond with
// Error_Busy
if device.pairingState == .pairing {
throw Error.alreadyPairing
}
// Notify listeners of the pairing event and record the paring state
// swiftlint:disable:next force_try
try! device.changePairingState(.pairing)
let (salt, serverPublicKey) = session.server.getChallenge()
logger.info("Pair setup started")
logger.debug("<-- s \(salt.hex)")
logger.debug("<-- B \(serverPublicKey.hex)")
let result: PairTagTLV8 = [
(.state, Data([PairSetupStep.startResponse.rawValue])),
(.publicKey, serverPublicKey),
(.salt, salt)
]
return result
}
func verifyRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8? {
guard let clientPublicKey = data[.publicKey], let clientKeyProof = data[.proof] else {
logger.warning("Invalid parameters")
throw Error.invalidSetupState
}
logger.debug("--> A \(clientPublicKey.hex)")
logger.debug("--> M \(clientKeyProof.hex)")
guard let serverKeyProof = try? session.server.verifySession(publicKey: clientPublicKey,
keyProof: clientKeyProof)
else {
logger.warning("Invalid PIN")
throw Error.authenticationFailed
}
logger.debug("<-- HAMK \(serverKeyProof.hex)")
let result: PairTagTLV8 = [
(.state, Data([PairSetupStep.verifyResponse.rawValue])),
(.proof, serverKeyProof)
]
return result
}
func keyExchangeRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8 {
guard let encryptedData = data[.encryptedData] else {
throw Error.invalidParameters
}
let encryptionKey = deriveKey(algorithm: .sha512,
seed: session.server.sessionKey!,
info: "Pair-Setup-Encrypt-Info".data(using: .utf8),
salt: "Pair-Setup-Encrypt-Salt".data(using: .utf8),
count: 32)
guard let plaintext = try? ChaCha20Poly1305.decrypt(cipher: encryptedData,
nonce: "PS-Msg05".data(using: .utf8)!,
key: encryptionKey) else {
throw Error.couldNotDecryptMessage
}
guard let data: PairTagTLV8 = try? decode(plaintext) else {
throw Error.couldNotDecodeMessage
}
guard let publicKey = data[.publicKey],
let username = data[.identifier],
let signatureIn = data[.signature]
else {
throw Error.invalidParameters
}
logger.debug("--> identifier \(String(data: username, encoding: .utf8)!)")
logger.debug("--> public key \(publicKey.hex)")
logger.debug("--> signature \(signatureIn.hex)")
let hashIn = deriveKey(algorithm: .sha512,
seed: session.server.sessionKey!,
info: "Pair-Setup-Controller-Sign-Info".data(using: .utf8),
salt: "Pair-Setup-Controller-Sign-Salt".data(using: .utf8),
count: 32) +
username +
publicKey
try Ed25519.verify(publicKey: publicKey, message: hashIn, signature: signatureIn)
let hashOut = deriveKey(algorithm: .sha512,
seed: session.server.sessionKey!,
info: "Pair-Setup-Accessory-Sign-Info".data(using: .utf8),
salt: "Pair-Setup-Accessory-Sign-Salt".data(using: .utf8),
count: 32) +
device.identifier.data(using: .utf8)! +
device.publicKey
guard let signatureOut = try? Ed25519.sign(privateKey: device.privateKey, message: hashOut) else {
throw Error.couldNotSign
}
let resultInner: PairTagTLV8 = [
(.identifier, device.identifier.data(using: .utf8)!),
(.publicKey, device.publicKey),
(.signature, signatureOut)
]
logger.debug("<-- identifier \(self.device.identifier)")
logger.debug("<-- public key \(self.device.publicKey.hex)")
logger.debug("<-- signature \(signatureOut.hex)")
logger.info("Pair setup completed")
guard let encryptedResultInner = try? ChaCha20Poly1305.encrypt(message: encode(resultInner),
nonce: "PS-Msg06".data(using: .utf8)!,
key: encryptionKey)
else {
throw Error.couldNotEncrypt
}
// At this point, the pairing has completed. The first controller is granted admin role.
device.add(pairing: Pairing(identifier: username, publicKey: publicKey, role: .admin))
let resultOuter: PairTagTLV8 = [
(.state, Data([PairSetupStep.keyExchangeResponse.rawValue])),
(.encryptedData, encryptedResultInner)
]
return resultOuter
}
}
| 38.131868 | 109 | 0.558934 |
7a83672446de050e476d447e550b58a3d8c10b0d | 1,475 | /*
Copyright (c) 2021 Swift Models Generated from JSON powered by http://www.json4swift.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For support, please feel free to contact me at https://www.linkedin.com/in/syedabsar
*/
import Foundation
import ObjectMapper
struct Vnext : Mappable {
var address : String?
var port : Int?
var users : [Users]?
init?(map: Map) {
}
mutating func mapping(map: Map) {
address <- map["address"]
port <- map["port"]
users <- map["users"]
}
} | 44.69697 | 460 | 0.767458 |
21a3fb4cd0c2ae22ff25368342858438c5514774 | 2,238 | import Fluent
import FluentSQLite
import Leaf
import Vapor
/// Called before your application initializes.
///
/// [Learn More →](https://docs.vapor.codes/3.0/getting-started/structure/#configureswift)
public func configure(
_ config: inout Config,
_ env: inout Environment,
_ services: inout Services
) throws {
// Register routes to the router
let router = EngineRouter.default()
try routes(router)
services.register(router, as: Router.self)
// Configure the rest of your application here
try services.register(LeafProvider())
config.prefer(LeafRenderer.self, for: ViewRenderer.self)
// Configure Directory Path
let directoryConfig = DirectoryConfig.detect()
services.register(directoryConfig)
// Register providers first
try services.register(FluentProvider())
// Configure a SQLite database
var databaseConfig = DatabasesConfig()
let db = try SQLiteDatabase(storage: .file(path: "\(directoryConfig.workDir)juices.db"))
// Register the configured SQLite database to the database config.
databaseConfig.add(database: db, as: .sqlite)
services.register(databaseConfig)
// Configure migrations
var migrationConfig = MigrationConfig()
migrationConfig.add(model: Juice.self, database: .sqlite)
migrationConfig.add(model: Order.self, database: .sqlite)
services.register(migrationConfig)
// Register middleware
var middlewares = MiddlewareConfig() // Create _empty_ middleware config
let corsConfiguration = CORSMiddleware.Configuration(
allowedOrigin: .all,
allowedMethods: [.GET, .POST, .PUT, .OPTIONS, .DELETE, .PATCH],
allowedHeaders: [.accept, .authorization, .contentType, .origin, .xRequestedWith, .userAgent, .accessControlAllowOrigin]
) // CORS Allow Control Acces Cross Origin Policy
let corsMiddleware = CORSMiddleware(configuration: corsConfiguration)
middlewares.use(corsMiddleware) // Allow Control Access Cross Origin
middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
services.register(middlewares)
}
| 36.688525 | 128 | 0.72252 |
0821c23929b8a812488df9cfd0775c6e4fb45f82 | 451 | //
// SectionData.swift
// FlightInfo
//
// Created by Kevin Smith on 22/7/18.
// Copyright © 2018 Kevin Smith. All rights reserved.
//
import UIKit
class SectionData: NSObject {
@objc var subTitle:String = ""
@objc var title:String = ""
@objc var icon:String = ""
@objc var standByIcon:String = ""
init(dictionary:[String : AnyObject]) {
super.init()
self.setValuesForKeys(dictionary)
}
}
| 18.791667 | 54 | 0.609756 |
e0860afda9a29210346f00e068a1b442a70af340 | 573 | //
// Copyright (c) Vatsal Manot
//
import Swift
@propertyWrapper
public struct LazyImmutable<Value> {
private var _wrappedValue: Value?
public private(set) var wasInitialized: Bool = false
public var wrappedValue: Value {
get {
guard let _wrappedValue = _wrappedValue else {
fatalError()
}
return _wrappedValue
} set {
guard !wasInitialized else {
fatalError()
}
_wrappedValue = newValue
}
}
public init() {
}
}
| 17.363636 | 58 | 0.541012 |
33c0c0f76a67f5570955716d81664b275d9122cf | 1,418 | //
// NameViewModel.swift
// RxController_Example
//
// Created by Meng Li on 2019/04/16.
// Copyright © 2019 XFLAG. All rights reserved.
//
import RxSwift
import RxController
import Fakery
struct NameEvent {
static let firstName = RxControllerEvent.identifier()
static let lastName = RxControllerEvent.identifier()
}
class NameViewModel: RxViewModel {
let firstNameViewModel = FirstNameViewModel()
let lastNameViewModel = LastNameViewModel()
override init() {
super.init()
addChildren(firstNameViewModel, lastNameViewModel)
}
private let faker = Faker(locale: "nb-NO")
func updateName() {
let firstName = faker.name.firstName()
let lastName = faker.name.lastName()
parentEvents.accept(InfoEvent.name.event(firstName + " " + lastName))
events.accept(NameEvent.firstName.event(firstName))
events.accept(NameEvent.lastName.event(lastName))
}
var name: Observable<String?> {
return Observable.merge(
parentEvents.value(of: InfoEvent.name),
Observable.combineLatest(
events.unwrappedValue(of: NameEvent.firstName),
events.unwrappedValue(of: NameEvent.lastName)
).map { $0 + " " + $1 }
)
}
var number: Observable<String?> {
return parentEvents.value(of: InfoEvent.number)
}
}
| 26.259259 | 77 | 0.638928 |
d92e110f80b12e66e8e84a8a5c7e5564b68b6dac | 655 | //
// BaseViewModel.swift
// CleanerKit
//
// Created by PFXStudio on 2020/04/11.
// Copyright © 2020 PFXStudio. All rights reserved.
//
import Foundation
import RxSwift
protocol RxViewModelProtocol {
associatedtype Input
associatedtype Output
associatedtype Dependency
var input: Input! { get }
var output: Output! { get }
func deinitialize()
}
class RxViewModel: DeinitializableProtocol {
var disposeBag = DisposeBag()
func deinitialize() {
NotificationCenter.default.removeObserver(self)
self.disposeBag = DisposeBag()
}
func initialize() {
self.disposeBag = DisposeBag()
}
}
| 20.46875 | 55 | 0.682443 |
09ac63ef0725b3489d535273b8c1ee1057ff8da5 | 380 |
import CoreData
public extension Query {
public static func require(info:[String:AnyObject?]) -> Query {
var predicates = [NSPredicate]()
for (key, value) in info {
//TODO: NSNull must be handled correctly
predicates.append(key == value)
}
return Compound(type:.AndPredicateType, subpredicates:predicates)
}
}
| 21.111111 | 73 | 0.618421 |
d5feb1db6555c04486324cceccfdc25212f418b9 | 29,038 | //
// PrivateBalanceFetcher.swift
// AlphaWallet
//
// Created by Vladyslav Shepitko on 26.05.2021.
//
import Foundation
import BigInt
import PromiseKit
import Result
import RealmSwift
import SwiftyJSON
protocol PrivateTokensDataStoreDelegate: AnyObject {
func didUpdate(in tokensDataStore: PrivateBalanceFetcher)
func didAddToken(in tokensDataStore: PrivateBalanceFetcher)
}
protocol PrivateBalanceFetcherType: AnyObject {
var delegate: PrivateTokensDataStoreDelegate? { get set }
var erc721TokenIdsFetcher: Erc721TokenIdsFetcher? { get set }
func refreshBalance(updatePolicy: PrivateBalanceFetcher.RefreshBalancePolicy, force: Bool)
}
// swiftlint:disable type_body_length
class PrivateBalanceFetcher: PrivateBalanceFetcherType {
typealias TokenIdMetaData = (contract: AlphaWallet.Address, tokenId: BigUInt, json: String, value: BigInt)
static let fetchContractDataTimeout = TimeInterval(4)
//Unlike `SessionManager.default`, this doesn't add default HTTP headers. It looks like POAP token URLs (e.g. https://api.poap.xyz/metadata/2503/278569) don't like them and return `406` in the JSON. It's strangely not responsible when curling, but only when running in the app
private var sessionManagerWithDefaultHttpHeaders: SessionManager = {
let configuration = URLSessionConfiguration.default
return SessionManager(configuration: configuration)
}()
weak var erc721TokenIdsFetcher: Erc721TokenIdsFetcher?
private lazy var tokenProvider: TokenProviderType = {
return TokenProvider(account: account, server: server, queue: queue)
}()
private let account: Wallet
private let openSea: OpenSea
private let queue: DispatchQueue
private let server: RPCServer
private lazy var etherToken = Activity.AssignedToken(tokenObject: TokensDataStore.etherToken(forServer: server))
private var isRefeshingBalance: Bool = false
weak var delegate: PrivateTokensDataStoreDelegate?
private var enabledObjectsObservation: NotificationToken?
private let tokensDatastore: TokensDataStore
private let assetDefinitionStore: AssetDefinitionStore
init(account: Wallet, tokensDatastore: TokensDataStore, server: RPCServer, assetDefinitionStore: AssetDefinitionStore, queue: DispatchQueue) {
self.account = account
self.server = server
self.queue = queue
self.openSea = OpenSea.createInstance(with: AddressAndRPCServer(address: account.address, server: server))
self.tokensDatastore = tokensDatastore
self.assetDefinitionStore = assetDefinitionStore
//NOTE: fire refresh balance only for initial scope, and while adding new tokens
enabledObjectsObservation = tokensDatastore.enabledObjectResults.observe(on: queue) { [weak self] change in
guard let strongSelf = self else { return }
switch change {
case .initial(let tokenObjects):
let tokenObjects = tokenObjects.map { Activity.AssignedToken(tokenObject: $0) }
strongSelf.refreshBalance(tokenObjects: Array(tokenObjects), updatePolicy: .all, force: true)
case .update(let updates, _, let insertions, _):
let values = updates.map { Activity.AssignedToken(tokenObject: $0) }
let tokenObjects = insertions.map { values[$0] }
guard !tokenObjects.isEmpty else { return }
strongSelf.refreshBalance(tokenObjects: tokenObjects, updatePolicy: .all, force: true)
strongSelf.delegate?.didAddToken(in: strongSelf)
case .error:
break
}
}
}
deinit {
enabledObjectsObservation.flatMap { $0.invalidate() }
}
private func getTokensFromOpenSea() -> OpenSea.PromiseResult {
//TODO when we no longer create multiple instances of TokensDataStore, we don't have to use singleton for OpenSea class. This was to avoid fetching multiple times from OpenSea concurrently
return openSea.makeFetchPromise()
}
func refreshBalance(updatePolicy: RefreshBalancePolicy, force: Bool = false) {
Promise<[Activity.AssignedToken]> { seal in
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return seal.reject(PMKError.cancelled) }
let tokenObjects = strongSelf.tokensDatastore.tokenObjects
seal.fulfill(tokenObjects)
}
}.done(on: queue, { tokenObjects in
self.refreshBalance(tokenObjects: tokenObjects, updatePolicy: .all, force: false)
}).cauterize()
}
private func refreshBalanceForNonErc721Or1155Tokens(tokens: [Activity.AssignedToken]) -> Promise<[PrivateBalanceFetcher.TokenBatchOperation]> {
assert(!tokens.contains { $0.isERC721Or1155AndNotForTickets })
let promises = tokens.map { getBalanceForNonErc721Or1155Tokens(forToken: $0) }
return when(resolved: promises).map { values -> [PrivateBalanceFetcher.TokenBatchOperation] in
return values.compactMap { $0.optionalValue }.compactMap { $0 }
}
}
enum RefreshBalancePolicy {
case eth
case ercTokens
case all
}
private func refreshBalance(tokenObjects: [Activity.AssignedToken], updatePolicy: RefreshBalancePolicy, force: Bool = false) {
guard !isRefeshingBalance || force else { return }
isRefeshingBalance = true
var promises: [Promise<Bool?>] = []
switch updatePolicy {
case .all:
promises += [refreshEthBalance(etherToken: etherToken)]
promises += [refreshBalance(tokenObjects: tokenObjects)]
case .ercTokens:
promises += [refreshBalance(tokenObjects: tokenObjects)]
case .eth:
promises += [refreshEthBalance(etherToken: etherToken)]
}
firstly {
when(resolved: promises).map(on: queue, { values -> Bool? in
//NOTE: taking for first element means that values was updated
return values.compactMap { $0.optionalValue }.compactMap { $0 }.first
})
}.done(on: queue, { balanceValueHasChange in
self.isRefeshingBalance = false
if let value = balanceValueHasChange, value {
self.delegate.flatMap { $0.didUpdate(in: self) }
}
})
}
private func refreshEthBalance(etherToken: Activity.AssignedToken) -> Promise<Bool?> {
let tokensDatastore = self.tokensDatastore
return tokenProvider.getEthBalance(for: account.address).then(on: queue, { balance -> Promise<Bool?> in
tokensDatastore.updateTokenPromise(primaryKey: etherToken.primaryKey, action: .value(balance.value))
}).recover(on: queue, { _ -> Guarantee<Bool?> in
return .value(nil)
})
}
private func refreshBalance(tokenObjects: [Activity.AssignedToken]) -> Promise<Bool?> {
let updateTokens = tokenObjects.filter { $0 != etherToken }
let notErc721Or1155Tokens = updateTokens.filter { !$0.isERC721Or1155AndNotForTickets }
let erc721Or1155Tokens = updateTokens.filter { $0.isERC721Or1155AndNotForTickets }
let promise1 = refreshBalanceForNonErc721Or1155Tokens(tokens: notErc721Or1155Tokens)
let promise2 = refreshBalanceForErc721Or1155Tokens(tokens: erc721Or1155Tokens)
let tokensDatastore = self.tokensDatastore
return when(resolved: [promise1, promise2]).then(on: queue, { value -> Promise<Bool?> in
let resolved = value.compactMap { $0.optionalValue }.flatMap { $0 }
return tokensDatastore.batchUpdateTokenPromise(resolved).recover { _ -> Guarantee<Bool?> in
return .value(nil)
}
})
}
enum TokenBatchOperation {
case add(ERCToken, shouldUpdateBalance: Bool)
case update(tokenObject: Activity.AssignedToken, action: TokensDataStore.TokenUpdateAction)
}
private func getBalanceForNonErc721Or1155Tokens(forToken tokenObject: Activity.AssignedToken) -> Promise<TokenBatchOperation?> {
switch tokenObject.type {
case .nativeCryptocurrency:
return .value(nil)
case .erc20:
return tokenProvider.getERC20Balance(for: tokenObject.contractAddress).map(on: queue, { value -> TokenBatchOperation in
return .update(tokenObject: tokenObject, action: .value(value))
}).recover { _ -> Promise<TokenBatchOperation?> in
return .value(nil)
}
case .erc875:
return tokenProvider.getERC875Balance(for: tokenObject.contractAddress).map(on: queue, { balance -> TokenBatchOperation in
return .update(tokenObject: tokenObject, action: .nonFungibleBalance(balance))
}).recover { _ -> Promise<TokenBatchOperation?> in
return .value(nil)
}
case .erc721, .erc1155:
return .value(nil)
case .erc721ForTickets:
return tokenProvider.getERC721ForTicketsBalance(for: tokenObject.contractAddress).map(on: queue, { balance -> TokenBatchOperation in
return .update(tokenObject: tokenObject, action: .nonFungibleBalance(balance))
}).recover { _ -> Promise<TokenBatchOperation?> in
return .value(nil)
}
}
}
private func refreshBalanceForErc721Or1155Tokens(tokens: [Activity.AssignedToken]) -> Promise<[PrivateBalanceFetcher.TokenBatchOperation]> {
assert(!tokens.contains { !$0.isERC721Or1155AndNotForTickets })
return firstly {
getTokensFromOpenSea()
}.then(on: queue, { [weak self] contractToOpenSeaNonFungibles -> Guarantee<[PrivateBalanceFetcher.TokenBatchOperation]> in
guard let strongSelf = self else { return .value([]) }
let erc721Or1155ContractsFoundInOpenSea = Array(contractToOpenSeaNonFungibles.keys).map { $0 }
let erc721Or1155ContractsNotFoundInOpenSea = tokens.map { $0.contractAddress } - erc721Or1155ContractsFoundInOpenSea
let p1 = strongSelf.updateNonOpenSeaNonFungiblesBalance(contracts: erc721Or1155ContractsNotFoundInOpenSea, tokens: tokens)
let p2 = strongSelf.updateOpenSeaNonFungiblesBalanceAndAttributes(contractToOpenSeaNonFungibles: contractToOpenSeaNonFungibles, tokens: tokens)
return when(resolved: [p1, p2]).map(on: strongSelf.queue, { results -> [PrivateBalanceFetcher.TokenBatchOperation] in
return results.compactMap { $0.optionalValue }.flatMap { $0 }
})
})
}
private func updateNonOpenSeaNonFungiblesBalance(contracts: [AlphaWallet.Address], tokens: [Activity.AssignedToken]) -> Promise<[PrivateBalanceFetcher.TokenBatchOperation]> {
let promises = contracts.map { updateNonOpenSeaNonFungiblesBalance(erc721Or1115ContractNotFoundInOpenSea: $0, tokens: tokens) }
return firstly {
when(fulfilled: promises)
}.map(on: queue, { results in
return results.compactMap { $0 }.flatMap { $0 }
})
}
private func updateNonOpenSeaNonFungiblesBalance(erc721Or1115ContractNotFoundInOpenSea contract: AlphaWallet.Address, tokens: [Activity.AssignedToken]) -> Promise<[TokenBatchOperation]> {
let erc721Promise = updateNonOpenSeaErc721Balance(contract: contract, tokens: tokens)
let erc1155Promise: Promise<TokenBatchOperation?> = Promise.value(nil)
return firstly {
when(fulfilled: [erc721Promise, erc1155Promise]).map(on: queue, { results -> [TokenBatchOperation] in
return results.compactMap { $0 }
})
}
}
private func updateNonOpenSeaErc721Balance(contract: AlphaWallet.Address, tokens: [Activity.AssignedToken]) -> Promise<TokenBatchOperation?> {
guard let erc721TokenIdsFetcher = erc721TokenIdsFetcher else { return Promise { _ in } }
return firstly {
erc721TokenIdsFetcher.tokenIdsForErc721Token(contract: contract, inAccount: account.address)
}.then(on: queue, { tokenIds -> Promise<[String]> in
let guarantees: [Guarantee<String>] = tokenIds.map { self.fetchNonFungibleJson(forTokenId: $0, address: contract, tokens: tokens) }
return when(fulfilled: guarantees)
}).map(on: queue, { jsons -> TokenBatchOperation? in
guard let tokenObject = tokens.first(where: { $0.contractAddress.sameContract(as: contract) }) else {
return nil
}
return .update(tokenObject: tokenObject, action: .nonFungibleBalance(jsons))
}).recover { _ -> Guarantee<TokenBatchOperation?> in
return .value(nil)
}
}
private func updateNonOpenSeaErc1155Balance(contract: AlphaWallet.Address, tokens: [Activity.AssignedToken]) -> Promise<Void> {
guard let contractsTokenIdsAndValue = Erc1155TokenIdsFetcher(address: account.address, server: server).readJson() else {
return .value(())
}
return firstly {
addUnknownErc1155ContractsToDatabase(contractsTokenIdsAndValue: contractsTokenIdsAndValue.tokens, tokens: tokens)
}.then { (contractsTokenIdsAndValue: Erc1155TokenIds.ContractsTokenIdsAndValues) -> Promise<[TokenIdMetaData]> in
self.fetchErc1155NonFungibleJsons(contractsTokenIdsAndValue: contractsTokenIdsAndValue, tokens: tokens)
}.then { (results: [TokenIdMetaData]) -> Promise<Void> in
self.updateErc1155TokenIdBalancesInDatabase(tokenIdsData: results, tokens: tokens)
}
//TODO log error remotely
}
private func addUnknownErc1155ContractsToDatabase(contractsTokenIdsAndValue: Erc1155TokenIds.ContractsTokenIdsAndValues, tokens: [Activity.AssignedToken]) -> Promise<Erc1155TokenIds.ContractsTokenIdsAndValues> {
let tokensDatastore = self.tokensDatastore
return firstly {
functional.fetchUnknownErc1155ContractsDetails(contractsTokenIdsAndValue: contractsTokenIdsAndValue, tokens: tokens, server: server, account: account, assetDefinitionStore: assetDefinitionStore)
}.then(on: .main, { tokensToAdd -> Promise<Erc1155TokenIds.ContractsTokenIdsAndValues> in
let (promise, seal) = Promise<Erc1155TokenIds.ContractsTokenIdsAndValues>.pending()
tokensDatastore.addCustom(tokens: tokensToAdd, shouldUpdateBalance: false)
seal.fulfill(contractsTokenIdsAndValue)
return promise
})
}
private func fetchErc1155NonFungibleJsons(contractsTokenIdsAndValue: Erc1155TokenIds.ContractsTokenIdsAndValues, tokens: [Activity.AssignedToken]) -> Promise<[TokenIdMetaData]> {
var allGuarantees: [Guarantee<TokenIdMetaData>] = .init()
for (contract, tokenIdsAndValues) in contractsTokenIdsAndValue {
let guarantees: [Guarantee<TokenIdMetaData>] = tokenIdsAndValues.map { tokenId, value -> Guarantee<TokenIdMetaData> in
fetchNonFungibleJson(forTokenId: String(tokenId), address: contract, tokens: tokens).map { jsonString -> TokenIdMetaData in
(contract: contract, tokenId: tokenId, json: jsonString, value: value)
}
}
allGuarantees.append(contentsOf: guarantees)
}
return when(fulfilled: allGuarantees)
}
private func updateErc1155TokenIdBalancesInDatabase(tokenIdsData: [TokenIdMetaData], tokens: [Activity.AssignedToken]) -> Promise<Void> {
let (promise, seal) = Promise<Void>.pending()
var contractsTokenIdsAndValue: [AlphaWallet.Address: [BigUInt: String]] = .init()
for (contract, tokenId, json, value) in tokenIdsData {
var tokenIdsAndValue: [BigUInt: String] = contractsTokenIdsAndValue[contract] ?? .init()
tokenIdsAndValue[tokenId] = json
contractsTokenIdsAndValue[contract] = tokenIdsAndValue
}
for (contract, tokenIdsAndJsons) in contractsTokenIdsAndValue {
guard let tokenObject = tokens.first(where: { $0.contractAddress.sameContract(as: contract) }) else {
assertImpossibleCodePath(message: "ERC1155 contract: \(contract.eip55String) not found in database when setting balance for 1155")
return promise
}
let jsons: [String] = Array(tokenIdsAndJsons.values)
tokensDatastore.update(primaryKey: tokenObject.primaryKey, action: .nonFungibleBalance(jsons))
tokensDatastore.update(primaryKey: tokenObject.primaryKey, action: .type(.erc1155))
}
seal.fulfill(())
return promise
}
//Misnomer, we call this "nonFungible", but this includes ERC1155 which can contain (semi-)fungibles, but there's no better name
private func fetchNonFungibleJson(forTokenId tokenId: String, address: AlphaWallet.Address, tokens: [Activity.AssignedToken]) -> Guarantee<String> {
firstly {
Erc721Contract(server: server).getErc721TokenUri(for: tokenId, contract: address)
}.then(on: queue, {
self.fetchTokenJson(forTokenId: tokenId, uri: $0, address: address, tokens: tokens)
}).recover(on: queue, { _ in
return self.generateTokenJsonFallback(forTokenId: tokenId, address: address, tokens: tokens)
})
}
private func fetchTokenJson(forTokenId tokenId: String, uri originalUri: URL, address: AlphaWallet.Address, tokens: [TokenObject]) -> Promise<String> {
struct Error: Swift.Error {
}
let uri = originalUri.rewrittenIfIpfs
return firstly {
//Must not use `SessionManager.default.request` or `Alamofire.request` which uses the former. See comment in var
sessionManagerWithDefaultHttpHeaders.request(uri, method: .get).responseData()
}.map(on: queue, { data, _ in
if let json = try? JSON(data: data) {
if json["error"] == "Internal Server Error" {
throw Error()
} else {
var jsonDictionary = json
if let tokenObject = tokens.first(where: { $0.contractAddress.sameContract(as: address) }) {
//We must make sure the value stored is at least an empty string, never nil because we need to deserialise/decode it
jsonDictionary["tokenId"] = JSON(tokenId)
jsonDictionary["tokenType"] = JSON(TokensDataStore.functional.nonFungibleTokenType(fromTokenType: tokenObject.type).rawValue)
jsonDictionary["contractName"] = JSON(tokenObject.name)
jsonDictionary["symbol"] = JSON(tokenObject.symbol)
jsonDictionary["name"] = JSON(jsonDictionary["name"].stringValue)
jsonDictionary["imageUrl"] = JSON(jsonDictionary["image"].string ?? jsonDictionary["image_url"].string ?? "")
jsonDictionary["thumbnailUrl"] = jsonDictionary["imageUrl"]
//POAP tokens (https://blockscout.com/xdai/mainnet/address/0x22C1f6050E56d2876009903609a2cC3fEf83B415/transactions), eg. https://api.poap.xyz/metadata/2503/278569, use `home_url` as the key for what they should use `external_url` for and they use `external_url` to point back to the token URI
jsonDictionary["externalLink"] = JSON(jsonDictionary["home_url"].string ?? jsonDictionary["external_url"].string ?? "")
}
if let jsonString = jsonDictionary.rawString() {
return jsonString
} else {
throw Error()
}
}
} else {
throw Error()
}
})
}
private func generateTokenJsonFallback(forTokenId tokenId: String, address: AlphaWallet.Address, tokens: [Activity.AssignedToken]) -> Guarantee<String> {
var jsonDictionary = JSON()
if let tokenObject = tokens.first(where: { $0.contractAddress.sameContract(as: address) }) {
jsonDictionary["tokenId"] = JSON(tokenId)
jsonDictionary["tokenType"] = JSON(TokensDataStore.functional.nonFungibleTokenType(fromTokenType: tokenObject.type).rawValue)
jsonDictionary["contractName"] = JSON(tokenObject.name)
jsonDictionary["decimals"] = JSON(0)
jsonDictionary["symbol"] = JSON(tokenObject.symbol)
jsonDictionary["name"] = ""
jsonDictionary["imageUrl"] = ""
jsonDictionary["thumbnailUrl"] = ""
jsonDictionary["externalLink"] = ""
}
return .value(jsonDictionary.rawString()!)
}
private func fetchTokenJson(forTokenId tokenId: String, uri originalUri: URL, address: AlphaWallet.Address, tokens: [Activity.AssignedToken]) -> Promise<String> {
struct Error: Swift.Error {
}
let uri = originalUri.rewrittenIfIpfs
return firstly {
//Must not use `SessionManager.default.request` or `Alamofire.request` which uses the former. See comment in var
sessionManagerWithDefaultHttpHeaders.request(uri, method: .get).responseData()
}.map(on: queue, { data, _ in
if let json = try? JSON(data: data) {
if json["error"] == "Internal Server Error" {
throw Error()
} else {
var jsonDictionary = json
if let tokenObject = tokens.first(where: { $0.contractAddress.sameContract(as: address) }) {
jsonDictionary["tokenType"] = JSON(TokensDataStore.functional.nonFungibleTokenType(fromTokenType: tokenObject.type).rawValue)
//We must make sure the value stored is at least an empty string, never nil because we need to deserialise/decode it
jsonDictionary["contractName"] = JSON(tokenObject.name)
jsonDictionary["symbol"] = JSON(tokenObject.symbol)
jsonDictionary["tokenId"] = JSON(tokenId)
jsonDictionary["decimals"] = JSON(jsonDictionary["decimals"].intValue ?? 0)
jsonDictionary["name"] = JSON(jsonDictionary["name"].stringValue)
jsonDictionary["imageUrl"] = JSON(jsonDictionary["image"].string ?? jsonDictionary["image_url"].string ?? "")
jsonDictionary["thumbnailUrl"] = jsonDictionary["imageUrl"]
//POAP tokens (https://blockscout.com/xdai/mainnet/address/0x22C1f6050E56d2876009903609a2cC3fEf83B415/transactions), eg. https://api.poap.xyz/metadata/2503/278569, use `home_url` as the key for what they should use `external_url` for and they use `external_url` to point back to the token URI
jsonDictionary["externalLink"] = JSON(jsonDictionary["home_url"].string ?? jsonDictionary["external_url"].string ?? "")
}
if let jsonString = jsonDictionary.rawString() {
return jsonString
} else {
throw Error()
}
}
} else {
throw Error()
}
})
}
private func updateOpenSeaNonFungiblesBalanceAndAttributes(contractToOpenSeaNonFungibles: [AlphaWallet.Address: [OpenSeaNonFungible]], tokens: [Activity.AssignedToken]) -> Promise<[TokenBatchOperation]> {
return Promise<[TokenBatchOperation]> { seal in
var actions: [TokenBatchOperation] = []
for (contract, openSeaNonFungibles) in contractToOpenSeaNonFungibles {
var listOfJson = [String]()
var anyNonFungible: OpenSeaNonFungible?
for each in openSeaNonFungibles {
if let encodedJson = try? JSONEncoder().encode(each), let jsonString = String(data: encodedJson, encoding: .utf8) {
anyNonFungible = each
listOfJson.append(jsonString)
} else {
//no op
}
}
let tokenType: TokenType
if let anyNonFungible = anyNonFungible {
tokenType = anyNonFungible.tokenType.asTokenType
} else {
//Default to ERC721 because this is what we supported (from OpenSea) before adding ERC1155 support
tokenType = .erc721
}
if let tokenObject = tokens.first(where: { $0.contractAddress.sameContract(as: contract) }) {
switch tokenObject.type {
case .nativeCryptocurrency, .erc721, .erc875, .erc721ForTickets, .erc1155:
break
case .erc20:
tokensDatastore.update(primaryKey: tokenObject.primaryKey, action: .type(tokenType))
actions += [.update(tokenObject: tokenObject, action: .type(tokenType))]
}
actions += [.update(tokenObject: tokenObject, action: .nonFungibleBalance(listOfJson))]
if let anyNonFungible = anyNonFungible {
actions += [.update(tokenObject: tokenObject, action: .name(anyNonFungible.contractName))]
}
} else {
let token = ERCToken(
contract: contract,
server: server,
name: openSeaNonFungibles[0].contractName,
symbol: openSeaNonFungibles[0].symbol,
decimals: 0,
type: tokenType,
balance: listOfJson
)
actions += [.add(token, shouldUpdateBalance: tokenType.shouldUpdateBalanceWhenDetected)]
}
}
seal.fulfill(actions)
}
}
func writeJsonForTransactions(toUrl url: URL) {
guard let transactionStorage = erc721TokenIdsFetcher as? TransactionsStorage else { return }
transactionStorage.writeJsonForTransactions(toUrl: url)
}
}
extension PrivateBalanceFetcher {
class functional {}
}
fileprivate extension PrivateBalanceFetcher.functional {
static func fetchUnknownErc1155ContractsDetails(contractsTokenIdsAndValue: Erc1155TokenIds.ContractsTokenIdsAndValues, tokens: [Activity.AssignedToken], server: RPCServer, account: Wallet, assetDefinitionStore: AssetDefinitionStore) -> Promise<[ERCToken]> {
let contractsToAdd: [AlphaWallet.Address] = contractsTokenIdsAndValue.keys.filter { contract in
!tokens.contains(where: { $0.contractAddress.sameContract(as: contract) })
}
guard !contractsToAdd.isEmpty else {
return Promise<[ERCToken]>.value(.init())
}
let (promise, seal) = Promise<[ERCToken]>.pending()
//Can't use `DispatchGroup` because `ContractDataDetector.fetch()` doesn't call `completion` once and only once
var contractsProcessed: Set<AlphaWallet.Address> = .init()
var erc1155TokensToAdd: [ERCToken] = .init()
func markContractProcessed(_ contract: AlphaWallet.Address) {
contractsProcessed.insert(contract)
if contractsProcessed.count == contractsToAdd.count {
seal.fulfill(erc1155TokensToAdd)
}
}
for each in contractsToAdd {
ContractDataDetector(address: each, account: account, server: server, assetDefinitionStore: assetDefinitionStore).fetch { data in
switch data {
case .name, .symbol, .balance, .decimals:
break
case .nonFungibleTokenComplete(let name, let symbol, let balance, let tokenType):
let token = ERCToken(
contract: each,
server: server,
name: name,
symbol: symbol,
//Doesn't matter for ERC1155 since it's not used at the token level
decimals: 0,
type: tokenType,
balance: balance
)
erc1155TokensToAdd.append(token)
markContractProcessed(each)
case .fungibleTokenComplete:
markContractProcessed(each)
case .delegateTokenComplete:
markContractProcessed(each)
case .failed:
//TODO we are ignoring `.failed` here because it is called multiple times and we need to wait until `ContractDataDetector.fetch()`'s `completion` is called once and only once
break
}
}
}
return promise
}
}
// swiftlint:enable type_body_length
| 52.892532 | 316 | 0.642434 |
4802de4c9b93db6cfe0d21c54b93f85aeac2420d | 766 | //
// ListViewController.swift
// ShoppingList
//
// Created by Juliana de Carvalho on 2020-10-30.
// Copyright © 2020 Juliana de Carvalho. All rights reserved.
//
import UIKit
class ListViewController: UIViewController {
@IBAction func close{
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 21.885714 | 106 | 0.652742 |
64c527e3b45f236c312e7364309d01bbf1dd02fc | 1,061 | //
// Data+MultipartFormElement.swift
// ThunderRequest
//
// Created by Simon Mitchell on 11/12/2018.
// Copyright © 2018 threesidedcube. All rights reserved.
//
import Foundation
extension Data: MultipartFormElement {
public func multipartDataWith(boundary: String, key: String) -> Data? {
return multipartDataWith(boundary: boundary, key: key, contentType: mimeType, fileExtension: fileExtension)
}
func multipartDataWith(boundary: String, key: String, contentType: String, fileExtension: String?) -> Data? {
var elementString = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(key)\"; filename=\"filename\(fileExtension != nil ? ".\(fileExtension!)" : "")\"\r\n"
elementString.append("Content-Type: \(contentType)\r\n")
elementString.append("Content-Transfer-Encoding: binary\r\n\r\n")
var data = elementString.data(using: .utf8)
data?.append(self)
data?.append("\r\n")
data?.append("--\(boundary)")
return data
}
}
| 34.225806 | 172 | 0.644675 |
38742d36643dbb010b6f210b484c0f166ab89486 | 8,955 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Traditional C-style assert with an optional message.
///
/// Use this function for internal sanity checks that are active
/// during testing but do not impact performance of shipping code.
/// To check for invalid usage in Release builds; see `precondition`.
///
/// * In playgrounds and -Onone builds (the default for Xcode's Debug
/// configuration): if `condition` evaluates to false, stop program
/// execution in a debuggable state after printing `message`.
///
/// * In -O builds (the default for Xcode's Release configuration),
/// `condition` is not evaluated, and there are no effects.
///
/// * In -Ounchecked builds, `condition` is not evaluated, but the
/// optimizer may assume that it *would* evaluate to `true`. Failure
/// to satisfy that assumption in -Ounchecked builds is a serious
/// programming error.
@_transparent
public func assert(
@autoclosure condition: () -> Bool,
@autoclosure _ message: () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
// Only assert in debug mode.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_assertionFailed("assertion failed", message(), file, line)
}
}
}
/// Check a necessary condition for making forward progress.
///
/// Use this function to detect conditions that must prevent the
/// program from proceeding even in shipping code.
///
/// * In playgrounds and -Onone builds (the default for Xcode's Debug
/// configuration): if `condition` evaluates to false, stop program
/// execution in a debuggable state after printing `message`.
///
/// * In -O builds (the default for Xcode's Release configuration):
/// if `condition` evaluates to false, stop program execution.
///
/// * In -Ounchecked builds, `condition` is not evaluated, but the
/// optimizer may assume that it *would* evaluate to `true`. Failure
/// to satisfy that assumption in -Ounchecked builds is a serious
/// programming error.
@swift3_migration(renamed="require")
@_transparent
public func precondition(
@autoclosure condition: () -> Bool,
@autoclosure _ message: () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_assertionFailed("precondition failed", message(), file, line)
}
} else if _isReleaseAssertConfiguration() {
let error = !condition()
Builtin.condfail(error._value)
}
}
/// Indicate that an internal sanity check failed.
///
/// Use this function to stop the program, without impacting the
/// performance of shipping code, when control flow is not expected to
/// reach the call (e.g. in the `default` case of a `switch` where you
/// have knowledge that one of the other cases must be satisfied). To
/// protect code from invalid usage in Release builds; see
/// `preconditionFailure`.
///
/// * In playgrounds and -Onone builds (the default for Xcode's Debug
/// configuration) stop program execution in a debuggable state
/// after printing `message`.
///
/// * In -O builds, has no effect.
///
/// * In -Ounchecked builds, the optimizer may assume that this
/// function will never be called. Failure to satisfy that assumption
/// is a serious programming error.
@inline(__always)
public func assertionFailure(
@autoclosure message: () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
if _isDebugAssertConfiguration() {
_assertionFailed("fatal error", message(), file, line)
}
else if _isFastAssertConfiguration() {
_conditionallyUnreachable()
}
}
/// Indicate that a precondition was violated.
///
/// Use this function to stop the program when control flow can only
/// reach the call if your API was improperly used.
///
/// * In playgrounds and -Onone builds (the default for Xcode's Debug
/// configuration), stop program execution in a debuggable state
/// after printing `message`.
///
/// * In -O builds (the default for Xcode's Release configuration),
/// stop program execution.
///
/// * In -Ounchecked builds, the optimizer may assume that this
/// function will never be called. Failure to satisfy that assumption
/// is a serious programming error.
@swift3_migration(renamed="requirementFailure")
@_transparent @noreturn
public func preconditionFailure(
@autoclosure message: () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
_assertionFailed("fatal error", message(), file, line)
} else if _isReleaseAssertConfiguration() {
Builtin.int_trap()
}
_conditionallyUnreachable()
}
/// Unconditionally print a `message` and stop execution.
@_transparent @noreturn
public func fatalError(
@autoclosure message: () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
_assertionFailed("fatal error", message(), file, line)
}
/// Library precondition checks.
///
/// Library precondition checks are enabled in debug mode and release mode. When
/// building in fast mode they are disabled. In release mode they don't print
/// an error message but just trap. In debug mode they print an error message
/// and abort.
@_transparent
public func _precondition(
@autoclosure condition: () -> Bool, _ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_fatalErrorMessage("fatal error", message, file, line)
}
} else if _isReleaseAssertConfiguration() {
let error = !condition()
Builtin.condfail(error._value)
}
}
@_transparent @noreturn
public func _preconditionFailure(
message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line) {
_precondition(false, message, file:file, line: line)
_conditionallyUnreachable()
}
/// If `error` is true, prints an error message in debug mode, traps in release
/// mode, and returns an undefined error otherwise.
/// Otherwise returns `result`.
@_transparent
public func _overflowChecked<T>(
args: (T, Bool),
file: StaticString = #file, line: UInt = #line
) -> T {
let (result, error) = args
if _isDebugAssertConfiguration() {
if _branchHint(error, false) {
_fatalErrorMessage("fatal error", "Overflow/underflow", file, line)
}
} else {
Builtin.condfail(error._value)
}
return result
}
/// Debug library precondition checks.
///
/// Debug library precondition checks are only on in debug mode. In release and
/// in fast mode they are disabled. In debug mode they print an error message
/// and abort.
/// They are meant to be used when the check is not comprehensively checking for
/// all possible errors.
@_transparent
public func _debugPrecondition(
@autoclosure condition: () -> Bool, _ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
// Only check in debug mode.
if _isDebugAssertConfiguration() {
if !_branchHint(condition(), true) {
_fatalErrorMessage("fatal error", message, file, line)
}
}
}
@_transparent @noreturn
public func _debugPreconditionFailure(
message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line) {
if _isDebugAssertConfiguration() {
_precondition(false, message, file: file, line: line)
}
_conditionallyUnreachable()
}
/// Internal checks.
///
/// Internal checks are to be used for checking correctness conditions in the
/// standard library. They are only enable when the standard library is built
/// with the build configuration INTERNAL_CHECKS_ENABLED enabled. Otherwise, the
/// call to this function is a noop.
@_transparent
public func _sanityCheck(
@autoclosure condition: () -> Bool, _ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
#if INTERNAL_CHECKS_ENABLED
if !_branchHint(condition(), true) {
_fatalErrorMessage("fatal error", message, file, line)
}
#endif
}
@_transparent @noreturn
public func _sanityCheckFailure(
message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
_sanityCheck(false, message, file: file, line: line)
_conditionallyUnreachable()
}
| 34.980469 | 80 | 0.698381 |
907a358899091f52a8b988d4ed17c0d5e8b6c96a | 8,743 | // Sources/protoc-gen-swift/FileGenerator.swift - File-level generation logic
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This provides the logic for each file that is stored in the plugin request.
/// In particular, generateOutputFile() actually builds a Swift source file
/// to represent a single .proto input. Note that requests typically contain
/// a number of proto files that are not to be generated.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
import SwiftProtobuf
class FileGenerator {
private let fileDescriptor: FileDescriptor
private let generatorOptions: GeneratorOptions
private let namer: SwiftProtobufNamer
var outputFilename: String {
let ext = ".pb.swift"
let pathParts = splitPath(pathname: fileDescriptor.name)
switch generatorOptions.outputNaming {
case .FullPath:
return pathParts.dir + pathParts.base + ext
case .PathToUnderscores:
let dirWithUnderscores =
pathParts.dir.replacingOccurrences(of: "/", with: "_")
return dirWithUnderscores + pathParts.base + ext
case .DropPath:
return pathParts.base + ext
}
}
init(fileDescriptor: FileDescriptor,
generatorOptions: GeneratorOptions) {
self.fileDescriptor = fileDescriptor
self.generatorOptions = generatorOptions
namer = SwiftProtobufNamer(currentFile: fileDescriptor,
protoFileToModuleMappings: generatorOptions.protoToModuleMappings)
}
/// Generate, if `errorString` gets filled in, then report error instead of using
/// what written into `printer`.
func generateOutputFile(printer p: inout CodePrinter, errorString: inout String?) {
guard fileDescriptor.fileOptions.swiftPrefix.isEmpty ||
isValidSwiftIdentifier(fileDescriptor.fileOptions.swiftPrefix,
allowQuoted: false) else {
errorString = "\(fileDescriptor.name) has an 'swift_prefix' that isn't a valid Swift identifier (\(fileDescriptor.fileOptions.swiftPrefix))."
return
}
p.print(
"// DO NOT EDIT.\n",
"// swift-format-ignore-file\n",
"//\n",
"// Generated by the Swift generator plugin for the protocol buffer compiler.\n",
"// Source: \(fileDescriptor.name)\n",
"//\n",
"// For information on using the generated types, please see the documentation:\n",
"// https://github.com/apple/swift-protobuf/\n",
"\n")
// Attempt to bring over the comments at the top of the .proto file as
// they likely contain copyrights/preamble/etc.
//
// The C++ FileDescriptor::GetSourceLocation(), says the location for
// the file is an empty path. That never seems to have comments on it.
// https://github.com/protocolbuffers/protobuf/issues/2249 opened to
// figure out the right way to do this since the syntax entry is
// optional.
let syntaxPath = IndexPath(index: Google_Protobuf_FileDescriptorProto.FieldNumbers.syntax)
if let syntaxLocation = fileDescriptor.sourceCodeInfoLocation(path: syntaxPath) {
let comments = syntaxLocation.asSourceComment(commentPrefix: "///",
leadingDetachedPrefix: "//")
if !comments.isEmpty {
p.print(comments)
// If the was a leading or tailing comment it won't have a blank
// line, after it, so ensure there is one.
if !comments.hasSuffix("\n\n") {
p.print("\n")
}
}
}
p.print("import Foundation\n")
if !fileDescriptor.isBundledProto {
// The well known types ship with the runtime, everything else needs
// to import the runtime.
p.print("import \(namer.swiftProtobufModuleName)\n")
}
if let neededImports = generatorOptions.protoToModuleMappings.neededModules(forFile: fileDescriptor) {
p.print("\n")
for i in neededImports {
p.print("import \(i)\n")
}
}
p.print("\n")
generateVersionCheck(printer: &p)
let extensionSet =
ExtensionSetGenerator(fileDescriptor: fileDescriptor,
generatorOptions: generatorOptions,
namer: namer)
extensionSet.add(extensionFields: fileDescriptor.extensions)
let enums = fileDescriptor.enums.map {
return EnumGenerator(descriptor: $0, generatorOptions: generatorOptions, namer: namer)
}
let messages = fileDescriptor.messages.map {
return MessageGenerator(descriptor: $0,
generatorOptions: generatorOptions,
namer: namer,
extensionSet: extensionSet)
}
for e in enums {
e.generateMainEnum(printer: &p)
e.generateCaseIterable(printer: &p)
}
for m in messages {
m.generateMainStruct(printer: &p, parent: nil, errorString: &errorString)
var caseIterablePrinter = CodePrinter()
m.generateEnumCaseIterable(printer: &caseIterablePrinter)
if !caseIterablePrinter.isEmpty && !generatorOptions.removeBoilerplateCode {
p.print("\n#if swift(>=4.2)\n")
p.print(caseIterablePrinter.content)
p.print("\n#endif // swift(>=4.2)\n")
}
}
if !extensionSet.isEmpty {
let pathParts = splitPath(pathname: fileDescriptor.name)
let filename = pathParts.base + pathParts.suffix
p.print(
"\n",
"// MARK: - Extension support defined in \(filename).\n")
// Generate the Swift Extensions on the Messages that provide the api
// for using the protobuf extension.
extensionSet.generateMessageSwiftExtensions(printer: &p)
// Generate a registry for the file.
extensionSet.generateFileProtobufExtensionRegistry(printer: &p)
// Generate the Extension's declarations (used by the two above things).
//
// This is done after the other two as the only time developers will need
// these symbols is if they are manually building their own ExtensionMap;
// so the others are assumed more interesting.
extensionSet.generateProtobufExtensionDeclarations(printer: &p)
}
let protoPackage = fileDescriptor.package
let needsProtoPackage: Bool = !protoPackage.isEmpty && !messages.isEmpty
if needsProtoPackage || !enums.isEmpty || !messages.isEmpty {
p.print(
"\n",
"// MARK: - Code below here is support for the SwiftProtobuf runtime.\n")
if needsProtoPackage {
p.print(
"\n",
"fileprivate let _protobuf_package = \"\(protoPackage)\"\n")
}
for e in enums {
e.generateRuntimeSupport(printer: &p)
}
for m in messages {
m.generateRuntimeSupport(printer: &p, file: self, parent: nil)
}
}
}
private func generateVersionCheck(printer p: inout CodePrinter) {
let v = Version.compatibilityVersion
p.print(
"// If the compiler emits an error on this type, it is because this file\n",
"// was generated by a version of the `protoc` Swift plug-in that is\n",
"// incompatible with the version of SwiftProtobuf to which you are linking.\n",
"// Please ensure that you are building against the same version of the API\n",
"// that was used to generate this file.\n",
"fileprivate struct _GeneratedWithProtocGenSwiftVersion: \(namer.swiftProtobufModuleName).ProtobufAPIVersionCheck {\n")
p.indent()
p.print(
"struct _\(v): \(namer.swiftProtobufModuleName).ProtobufAPIVersion_\(v) {}\n",
"typealias Version = _\(v)\n")
p.outdent()
p.print("}\n")
}
}
| 43.282178 | 151 | 0.590987 |
f4226ca9014bc2fdc7160fd9b42e602e423b9c0d | 1,975 | import UIKit
var str = ["1","2","three","four","5"]
//print(str.sorted())
//let result = str.sorted { (x, y) -> Bool in
// return x > y
//}
//print(result)
//let mapResult = str.map { (x) -> Int? in
// return Int(x)
//}
//print(mapResult)
//let filterResult = str.filter { $0 > 5}
//
//print(filterResult)
//let reduceResult = str.reduce(0) { (result, x) -> Int in
// return result + x
//}
//
//print(reduceResult)
//let compactMapResult = str.compactMap { Int($0) }
//print(compactMapResult)
//
//func lenth(value1: String, value2: String) -> Bool {
// return value1.count < value2.count
//}
//
//str.sort(by: lenth)
//print(str)
//let result = str.filter {$0.count > 1}.map {$0.uppercased()}
//print(result)
//let result = str.contains {$0.first == "t"}
//print(result)
extension Array {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercased() }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
public func customMap<T>(_ transform: (Element) -> T) -> [T] {
var result = [T]()
for item in self {
result.append(transform(item))
}
return result
}
}
let result = str.customMap { (item) -> String in
item.uppercased()
}
print(result)
| 25.986842 | 78 | 0.592405 |
647f9ef47d1069c8d350008e90301d0f1442ccdf | 1,356 | import Foundation
struct Atbash {
private static func stripWhiteSpaceAndPunctuations(_ input: String) -> String {
var returnString = ""
input.characters.forEach {
if !" ,.".contains(String($0)) {
returnString.append($0)
}
}
return returnString
}
static let cipherDictApply: [Character : Character] = ["a": "z", "b": "y", "c": "x", "d": "w", "e": "v", "f": "u", "g": "t", "h": "s", "i": "r", "j": "q", "k": "p", "l": "o", "m": "n", "n": "m", "o": "l", "p": "k", "q": "j", "r": "i", "s": "h", "t": "g", "u": "f", "v": "e", "w": "d", "x": "c", "y": "b", "z": "a"]
static func encode( _ valueIn: String) -> String {
let value = stripWhiteSpaceAndPunctuations(valueIn.lowercased() )
var text2return = ""
for each in value.characters {
text2return.append(cipherDictApply[each] ?? each )
}
return insertSpace5th(text2return)
}
static func insertSpace5th(_ value: String) -> String {
var tempCounter = 0
var tempString: String = ""
for each in value.characters {
if tempCounter % 5 == 0 && tempCounter != 0 {
tempString += " \(each)"
} else { tempString += "\(each)" }
tempCounter += 1
}
return tempString
}
}
| 32.285714 | 318 | 0.490413 |
09a156e0457b7312fc9f51650741afe734d8b9a5 | 541 | //
// factorialTrailingZeroes.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/factorial-trailing-zeroes/
// Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code
//
// Why on earth is this tagged "easy" on leetCode!?
class Solution {
func trailingZeroes(_ num: Int) -> Int {
var result = 0, n = num
while n >= 5 {
n /= 5
result += n
}
return result
}
}
| 25.761905 | 117 | 0.652495 |
dd713d25a993312a7016c291959219a1c21ed634 | 3,052 | //
// AuthServiceSpec.swift
// Eber
//
// Created by myung gi son on 21/09/2019.
//
import RxSwift
import KeychainAccess
import Quick
import Nimble
import Stubber
import Moya
import RxBlocking
@testable import Eber
final class AuthServiceSpec: QuickSpec {
override func spec() {
func createAuthService(
networking: NetworkingStub = .init(),
accessTokenStore: AccessTokenStoreStub = .init()
) -> AuthService {
return AuthService(networking: networking, accessTokenStore: accessTokenStore)
}
var accessTokenStoreStub: AccessTokenStoreStub!
var networkingStub: NetworkingStub!
var authService: AuthService!
beforeEach {
accessTokenStoreStub = AccessTokenStoreStub()
networkingStub = NetworkingStub()
authService = createAuthService(
networking: networkingStub,
accessTokenStore: accessTokenStoreStub
)
}
context("while initializing") {
it("loads access token from AccessTokenStore") {
Stubber.register(accessTokenStoreStub.loadAccessToken) { _ in nil }
authService = createAuthService(accessTokenStore: accessTokenStoreStub)
expect(Stubber.executions(accessTokenStoreStub.loadAccessToken).count) == 1
}
}
context("when succeeds to authorize") {
beforeEach {
Stubber.register(accessTokenStoreStub.saveAccessToken) { _ in }
Stubber.register(networkingStub.request) { _ in
let json: [String: Any?] = [
"data": [
"token": AccessTokenFixture.accessToken.accessToken,
]
]
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])
return .just(Response(statusCode: 200, data: jsonData))
}
}
context("when access token should be preserved") {
it("saves access token to AccessTokenStore") {
_ = authService.authorize(auth: AuthFixture.auth, shouldPreserveAccessToken: true).toBlocking().materialize()
expect(authService.currentAccessToken?.accessToken) == AccessTokenFixture.accessToken.accessToken
expect(Stubber.executions(accessTokenStoreStub.saveAccessToken).count) == 1
}
}
context("when access token should not be preserved") {
it("doesn`t save access token to AccessTokenStore") {
_ = authService.authorize(auth: AuthFixture.auth, shouldPreserveAccessToken: false).toBlocking().materialize()
expect(authService.currentAccessToken?.accessToken) == AccessTokenFixture.accessToken.accessToken
expect(Stubber.executions(accessTokenStoreStub.saveAccessToken).count) == 0
}
}
}
context("when sign out") {
it("remove access token from AccessTokenStore") {
Stubber.register(accessTokenStoreStub.deleteAccessToken) { _ in }
authService.signOut()
expect(authService.currentAccessToken).to(beNil())
expect(Stubber.executions(accessTokenStoreStub.deleteAccessToken).count) == 1
}
}
}
}
| 34.292135 | 120 | 0.679227 |
1841ad372d7ae5027b12b07f2bef656e01dbcec9 | 6,846 | //
// WireframeInterfaceImagePickerEx.swift
// ArrvisCore
//
// Created by Yutaka Izumaru on 2019/08/02.
// Copyright © 2019 Arrvis Co., Ltd. All rights reserved.
//
import MobileCoreServices
import Photos
import RxSwift
private var imagePickerDelegateKey = 0
private var disposeBagKey = 1
/// ImagePicker
extension WireframeInterface {
private var imagePickerDelegate: ImagePickerDelegate? {
get {
return objc_getAssociatedObject(self, &imagePickerDelegateKey) as? ImagePickerDelegate ?? nil
}
set {
objc_setAssociatedObject(self, &imagePickerDelegateKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
fileprivate var disposeBag: DisposeBag {
get {
guard let object = objc_getAssociatedObject(self, &disposeBagKey) as? DisposeBag else {
self.disposeBag = DisposeBag()
return self.disposeBag
}
return object
}
set {
objc_setAssociatedObject(self, &disposeBagKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
/// メディア選択アクションシート表示
public func showMediaPickerSelectActionSheetScreen(
_ cameraRollEventHandler: CameraRollEventHandler,
_ mediaTypes: [CFString] = [kUTTypeImage, kUTTypeMovie]) {
var actions = [
photoLibraryButtonTitle(): (UIAlertAction.Style.default, { [unowned self] in
self.showLibraryScreen(cameraRollEventHandler, mediaTypes)
})
]
if UIImagePickerController.isSourceTypeAvailable(.camera) {
actions[cameraButtonTitle()] = (.default, { [unowned self] in
self.showCameraScreen(cameraRollEventHandler, mediaTypes)
})
}
showActionSheet(title: sheetTitle(),
message: sheetMessage(),
actions: actions,
cancel: cancelButtonTitle()) { [unowned self] in
self.onCancel()
}
}
/// ライブラリスクリーン表示
public func showLibraryScreen(_ handler: CameraRollEventHandler,
_ mediaTypes: [CFString] = [kUTTypeImage, kUTTypeMovie]) {
requestAccessToPhotoLibrary().observeOn(MainScheduler.instance).subscribe(onNext: { [unowned self] status in
if status == .authorized {
self.imagePickerDelegate = ImagePickerDelegate(handler)
self.navigator.navigate(
screen: SystemScreens.imagePicker,
payload: (
self.imagePickerDelegate,
UIImagePickerController.SourceType.photoLibrary,
mediaTypes
)
)
} else {
handler.onFailAccessPhotoLibrary()
}
}).disposed(by: disposeBag)
}
/// カメラスクリーン表示
public func showCameraScreen(_ handler: CameraRollEventHandler,
_ mediaTypes: [CFString] = [kUTTypeImage, kUTTypeMovie]) {
requestAccessToTakeMovie().observeOn(MainScheduler.instance).subscribe(onNext: { [unowned self] ret in
if ret {
self.imagePickerDelegate = ImagePickerDelegate(handler)
self.navigator.navigate(
screen: SystemScreens.imagePicker,
payload: (
self.imagePickerDelegate,
UIImagePickerController.SourceType.camera,
mediaTypes
)
)
} else {
handler.onFailAccessCamera()
}
}).disposed(by: disposeBag)
}
/// フォトライブラリへのアクセスリクエスト
public func requestAccessToPhotoLibrary() -> Observable<PHAuthorizationStatus> {
return Observable.create({ observer in
PHPhotoLibrary.requestAuthorization { status in
observer.onNext(status)
observer.onCompleted()
}
return Disposables.create()
})
}
/// 動画撮影アクセスリクエスト
public func requestAccessToTakeMovie() -> Observable<Bool> {
return Observable.create({ observer in
AVCaptureDevice.requestAccess(for: .video) { authorized in
observer.onNext(authorized)
observer.onCompleted()
}
return Disposables.create()
})
}
}
private class ImagePickerDelegate: NSObject, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
var cameraRollEventHandler: CameraRollEventHandler
init(_ cameraRollEventHandler: CameraRollEventHandler) {
self.cameraRollEventHandler = cameraRollEventHandler
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
picker.dismiss(animated: true) { [unowned self] in
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
if let image = info[convertFromUIImagePickerControllerInfoKey(.originalImage)] as? UIImage {
self.cameraRollEventHandler.onImageSelected(image)
} else if let url = info[convertFromUIImagePickerControllerInfoKey(.mediaURL)] as? URL {
self.cameraRollEventHandler.onMediaSelected(url)
} else if let asset = self.assetFromInfoKey(info) {
asset.getURL(completionHandler: { [unowned self] responseUrl in
if let url = responseUrl {
self.cameraRollEventHandler.onMediaSelected(url)
}
})
}
}
}
private func assetFromInfoKey(_ info: [String: Any]) -> PHAsset? {
if #available(iOS 11.0, *) {
return info[UIImagePickerController.InfoKey.phAsset.rawValue] as? PHAsset
} else {
guard let url = info[UIImagePickerController.InfoKey.referenceURL.rawValue] as? URL else { return nil }
return PHAsset.fetchAssets(withALAssetURLs: [url], options: nil).firstObject
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true) { [unowned self] in
self.cameraRollEventHandler.onCanceled()
}
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromUIImagePickerControllerInfoKeyDictionary(
_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
| 38.24581 | 116 | 0.615396 |
79c53e52a00aa4f45bf20516af2d4ba80e525780 | 7,445 | //
// ViewController.swift
// ADSuyiSDKDemo-iOS-Swift
//
// Created by 陈坤 on 2020/5/27.
// Copyright © 2020 陈坤. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
private var mainTable:UITableView!
private var dataArray: Array<String> = ["开屏广告","开屏V+广告","原生信息流广告","Banner横幅广告","激励视频","插屏广告","Draw视频","全屏视频","内容组件","组合广告 GroupAd", "快手内容"]
private let tableViewCellID = "SimpleTableIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
// [NSString stringWithFormat:@"ADSuyiSDK-Demo-v%@",[ADSuyiSDK getSDKVersion]]
self.title = NSString.init(format: "ADmobile 广告聚合SDK Demo") as String
self.view.backgroundColor = UIColor.white
let setBtn = UIButton.init()
// setBtn.setTitle("设置", for: .normal)
setBtn.setTitleColor(UIColor.white, for: .normal)
setBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
setBtn.setImage(UIImage.init(named: "set"), for: .normal)
setBtn.frame = CGRect.init(x: 0, y: 0, width: 20, height: 20)
setBtn.addTarget(self, action: #selector(setBtnClick), for: .touchUpInside)
let rightItem = UIBarButtonItem.init(customView: setBtn)
self.navigationItem.rightBarButtonItem = rightItem;
initTableView()
// Do any additional setup after loading the view.
}
@objc func setBtnClick() {
self.navigationController?.pushViewController(SetTableViewController(), animated: true)
}
private func initTableView() {
mainTable = UITableView.init(frame: self.view.bounds)
mainTable.frame.origin.y = CGFloat(tabBarHeight)
mainTable.backgroundColor = UIColor.init(red: 225/255.0, green: 233/255.0, blue: 239/255.0, alpha: 1)
self.view.addSubview(mainTable)
mainTable.translatesAutoresizingMaskIntoConstraints = false
let viewConstraints:[NSLayoutConstraint] = [
NSLayoutConstraint.init(item: mainTable!, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint.init(item: mainTable!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint.init(item: mainTable!, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0),
NSLayoutConstraint.init(item: mainTable!, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0)]
self.view.addConstraints(viewConstraints)
mainTable.delegate = self
mainTable.dataSource = self
mainTable.separatorStyle = .none;
mainTable.reloadData()
}
// mark - UITableViewDelegate/UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 48
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let label = UILabel.init()
label.textAlignment = .center
label.text = ADSuyiSDK.getVersion()
label.textColor = UIColor.init(red: 36/255.0, green: 132/255.0, blue: 207/255.0, alpha: 1);
return label
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 45
}
//
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: tableViewCellID)
let title = dataArray[indexPath.row]
cell.contentView.backgroundColor = UIColor.init(red: 225/255.0, green: 233/255.0, blue: 239/255.0, alpha: 1)
cell.backgroundColor = UIColor.init(red: 225/255.0, green: 233/255.0, blue: 239/255.0, alpha: 1)
cell.layer.cornerRadius = 6
cell.contentView.layer.cornerRadius = 6
cell.clipsToBounds = true
cell.contentView.clipsToBounds = true
let view = cell.contentView.viewWithTag(999)
if view != nil {
view?.removeFromSuperview()
}
let labTitle = UILabel.init()
labTitle.font = UIFont.adsy_PingFangRegularFont(14)
labTitle.backgroundColor = UIColor.white
labTitle.textAlignment = NSTextAlignment.center
labTitle.tag = 999
labTitle.textColor = UIColor.adsy_color(withHexString: "#666666")
labTitle.text = title
labTitle.clipsToBounds = true
cell.contentView.addSubview(labTitle)
labTitle.frame = CGRect.init(x: 16, y: 8, width: SCREEN_WIDTH - 32, height: 32)
labTitle.layer.cornerRadius = 4
labTitle.layer.borderWidth = 1
labTitle.layer.borderColor = UIColor.adsy_color(withHexString: "#E5E5EA")?.cgColor
labTitle.layer.shadowColor = UIColor.adsy_color(withHexString: "#000000", alphaComponent: 0.1)?.cgColor
labTitle.layer.shadowOffset = CGSize.init(width: 0, height: 1)
labTitle.layer.shadowOpacity = 1
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
self.navigationController?.pushViewController(ADSuyiSplashViewController.init(), animated: true)
break
case 1:
self.navigationController?.pushViewController(ADSuyiSplashVPlusViewController.init(), animated: true)
break
case 2:
let nativeVC = AdSuyiNativeViewController.init()
nativeVC.posid = "177a790a315eeb7053"
self.navigationController?.pushViewController(nativeVC, animated: true)
break
case 3:
self.navigationController?.pushViewController(ADSuyiBannerViewController.init(), animated: true)
break
case 4:
self.navigationController?.pushViewController(AdSuyiRewardViewController.init(), animated: true)
break
case 5:
self.navigationController?.pushViewController(AdSuyiInterstitialViewController.init(), animated: true)
break
case 6:
self.navigationController?.pushViewController(AdSuyiDrawVodViewController.init(), animated: true)
break
case 7:
self.navigationController?.pushViewController(AdSuyiFullScreenVodViewController.init(), animated: true)
break
case 8:
self.navigationController?.pushViewController(AdSuyiContainViewController.init(), animated: true)
break
case 9:
let vc = ADSuyiGroupAdViewController()
vc.nativePosid = "e9eaffb6b9d97cd813"
vc.rewardPosid = "47d196ffaaa92ae93c"
self.navigationController?.pushViewController(vc, animated: true)
break
case 10:
let vc = AdSuyiContentViewController()
self.navigationController?.pushViewController(vc, animated: true)
break
default:
break
}
}
}
| 43.034682 | 166 | 0.655205 |
f9a049240b4574e6dbf1e9cfcc41489ea41e94bb | 971 | //
// RemindersTests.swift
// RemindersTests
//
// Created by Joachim Kret on 18.01.2018.
// Copyright © 2018 JK. All rights reserved.
//
import XCTest
@testable import Reminders
class RemindersTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.243243 | 111 | 0.633368 |
096fa6b4b96e3e8ebf4176693c678b131b419457 | 3,163 | // Copyright 2016-2020 Fitbit, Inc
// SPDX-License-Identifier: Apache-2.0
import XCTest
@testable import FbSmo
class MiscTests: XCTestCase {
private let expected = Misc(
tinyInt: 12,
smallInt: 200,
mediumInt: 80000,
largeInt: 80000000000,
array: [1, 2, 3, "1", "2", "3"],
true: true,
false: false,
null: nil,
tinyString: "tinyString",
mediumString: "mediumString1 mediumString1 mediumString1 mediumString1 mediumString1",
float: 1.2345,
object: ["a": 1, "b": 2]
)
/// Decode using JSONDecoder to check that Codable behaves as expected
func testJsonReference() throws {
let fixture = loadFixture("misc.json")
let decoded = try JSONDecoder().decode(Misc.self, from: fixture)
XCTAssertEqual(decoded, expected)
}
func testJson() throws {
let fixture = loadFixture("misc.json")
let decoded = try FbSmoDecoder().decode(Misc.self, from: fixture, using: .json)
XCTAssertEqual(decoded, expected)
}
func testCbor() throws {
let fixture = loadFixture("misc.cbor")
let decoded = try FbSmoDecoder().decode(Misc.self, from: fixture, using: .cbor)
XCTAssertEqual(decoded, expected)
}
func testEncodeDecode() {
encodeDecodeTest(expected)
}
}
private struct Misc: Codable, Equatable {
let tinyInt: Int
let smallInt: Int
let mediumInt: Int
let largeInt: Int64
let array: [NumberOrString]
let `true`: Bool
let `false`: Bool
let null: Bool?
let tinyString: String
let mediumString: String
let float: Double
let object: [String: Int]
}
private enum NumberOrString: Equatable, Codable, ExpressibleByStringLiteral, ExpressibleByIntegerLiteral {
case number(Int)
case string(String)
public init(extendedGraphemeClusterLiteral value: String) { self = .string(value) }
public init(unicodeScalarLiteral value: String) { self = .string(value) }
public init(stringLiteral value: String) { self = .string(value) }
public init(integerLiteral value: Int) { self = .number(value) }
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
guard let number = try? container.decode(Int.self) else {
self = .string(try container.decode(String.self))
return
}
self = .number(number)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .number(let number):
try container.encode(number)
case .string(let string):
try container.encode(string)
}
}
static func == (lhs: NumberOrString, rhs: NumberOrString) -> Bool {
switch (lhs, rhs) {
case let (.number(lhsNumber), .number(rhsNumber)):
return lhsNumber == rhsNumber
case (.number, _):
return false
case let (.string(lhsString), .string(rhsString)):
return lhsString == rhsString
case (.string, _):
return false
}
}
}
| 29.839623 | 106 | 0.62251 |
6a5ed829f61a14a41aa0ad25dabd0e7102276e68 | 519 | //
// StripeBundleLocator.swift
// StripeiOS
//
// Created by Mel Ludowise on 7/6/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
final class StripeBundleLocator: BundleLocatorProtocol {
static let internalClass: AnyClass = StripeBundleLocator.self
static let bundleName = "Stripe"
#if SWIFT_PACKAGE
static let spmResourcesBundle = Bundle.module
#endif
static let resourcesBundle = StripeBundleLocator.computeResourcesBundle()
}
| 25.95 | 77 | 0.749518 |
ddb596d9271e21beff7376a0b949008eaef7589b | 7,343 | //
// Highlight.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
@objc(ChartHighlight)
open class Highlight: NSObject
{
/// the x-value of the highlighted value
fileprivate var _x = Double.nan
/// the y-value of the highlighted value
fileprivate var _y = Double.nan
/// the x-pixel of the highlight
fileprivate var _xPx = CGFloat.nan
/// the y-pixel of the highlight
fileprivate var _yPx = CGFloat.nan
/// the index of the data object - in case it refers to more than one
open var dataIndex = Int(-1)
/// the index of the dataset the highlighted value is in
fileprivate var _dataSetIndex = Int(0)
/// index which value of a stacked bar entry is highlighted
///
/// **default**: -1
fileprivate var _stackIndex = Int(-1)
/// the axis the highlighted value belongs to
fileprivate var _axis: YAxis.AxisDependency = YAxis.AxisDependency.left
/// the x-position (pixels) on which this highlight object was last drawn
open var drawX: CGFloat = 0.0
/// the y-position (pixels) on which this highlight object was last drawn
open var drawY: CGFloat = 0.0
public override init()
{
super.init()
}
/// - parameter x: the x-value of the highlighted value
/// - parameter y: the y-value of the highlighted value
/// - parameter xPx: the x-pixel of the highlighted value
/// - parameter yPx: the y-pixel of the highlighted value
/// - parameter dataIndex: the index of the Data the highlighted value belongs to
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataIndex: Int,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency)
{
super.init()
_x = x
_y = y
_xPx = xPx
_yPx = yPx
self.dataIndex = dataIndex
_dataSetIndex = dataSetIndex
_stackIndex = stackIndex
_axis = axis
}
/// - parameter x: the x-value of the highlighted value
/// - parameter y: the y-value of the highlighted value
/// - parameter xPx: the x-pixel of the highlighted value
/// - parameter yPx: the y-pixel of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter axis: the axis the highlighted value belongs to
public convenience init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency)
{
self.init(x: x, y: y, xPx: xPx, yPx: yPx,
dataIndex: 0,
dataSetIndex: dataSetIndex,
stackIndex: stackIndex,
axis: axis)
}
/// - parameter x: the x-value of the highlighted value
/// - parameter y: the y-value of the highlighted value
/// - parameter xPx: the x-pixel of the highlighted value
/// - parameter yPx: the y-pixel of the highlighted value
/// - parameter dataIndex: the index of the Data the highlighted value belongs to
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
axis: YAxis.AxisDependency)
{
super.init()
_x = x
_y = y
_xPx = xPx
_yPx = yPx
_dataSetIndex = dataSetIndex
_axis = axis
}
/// - parameter x: the x-value of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
public init(x: Double, dataSetIndex: Int)
{
_x = x
_dataSetIndex = dataSetIndex
}
/// - parameter x: the x-value of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
public convenience init(x: Double, dataSetIndex: Int, stackIndex: Int)
{
self.init(x: x, dataSetIndex: dataSetIndex)
_stackIndex = stackIndex
}
open var x: Double { return _x }
open var y: Double { return _y }
open var xPx: CGFloat { return _xPx }
open var yPx: CGFloat { return _yPx }
open var dataSetIndex: Int { return _dataSetIndex }
open var stackIndex: Int { return _stackIndex }
open var axis: YAxis.AxisDependency { return _axis }
open var isStacked: Bool { return _stackIndex >= 0 }
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(x: CGFloat, y: CGFloat)
{
self.drawX = x
self.drawY = y
}
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(pt: CGPoint)
{
self.drawX = pt.x
self.drawY = pt.y
}
// MARK: NSObject
open override var description: String
{
return "Highlight, x: \(_x), y: \(_y), dataIndex (combined charts): \(dataIndex), dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex)"
}
open override func isEqual(_ object: Any?) -> Bool
{
if object == nil
{
return false
}
if !(object! as AnyObject).isKind(of: type(of: self))
{
return false
}
if (object! as AnyObject).x != _x
{
return false
}
if (object! as AnyObject).y != _y
{
return false
}
if (object! as AnyObject).dataIndex != dataIndex
{
return false
}
if (object! as AnyObject).dataSetIndex != _dataSetIndex
{
return false
}
if (object! as AnyObject).stackIndex != _stackIndex
{
return false
}
return true
}
}
func ==(lhs: Highlight, rhs: Highlight) -> Bool
{
if lhs === rhs
{
return true
}
if !lhs.isKind(of: type(of: rhs))
{
return false
}
if lhs._x != rhs._x
{
return false
}
if lhs._y != rhs._y
{
return false
}
if lhs.dataIndex != rhs.dataIndex
{
return false
}
if lhs._dataSetIndex != rhs._dataSetIndex
{
return false
}
if lhs._stackIndex != rhs._stackIndex
{
return false
}
return true
}
| 28.796078 | 173 | 0.591992 |
87e2ee29818b354dba84fb82cc1407fae26e02e1 | 7,429 | //
// Photorater.swift
// StyleTransfer
//
// Created by hugo on 2020/9/5.
// Copyright © 2020 TensorFlow Authors. All rights reserved.
//
import TensorFlowLite
import UIKit
class PhotoRater {
private var predictInterpreter: Interpreter
private let tfLiteQueue: DispatchQueue
/// Create a Style Transferer instance with a quantized Int8 model that runs inference on the CPU.
static func newCPUStyleTransferer(
completion: @escaping ((Result<PhotoRater>) -> Void)
) -> () {
return PhotoRater.newInstance(
useMetalDelegate: false,
completion: completion)
}
static func newGPUStyleTransferer(
completion: @escaping ((Result<PhotoRater>) -> Void)
) -> () {
return PhotoRater.newInstance(
useMetalDelegate: true,
completion: completion)
}
static func newInstance(
useMetalDelegate: Bool,
completion: @escaping ((Result<PhotoRater>) -> Void)) {
// Create a dispatch queue to ensure all operations on the Intepreter will run serially.
let tfLiteQueue = DispatchQueue(label: "photorater")
// Run initialization in background thread to avoid UI freeze.
tfLiteQueue.async {
// Construct the path to the model file.
guard
let predictModelPath = Bundle.main.path(
forResource: Constants.Float16.predictModel,
ofType: Constants.modelFileExtension
)
else {
completion(.error(InitializationError.invalidModel(
"model could not be loaded"
)))
return
}
// Specify the delegate for the TF Lite `Interpreter`.
let createDelegates: () -> [Delegate]? = {
if useMetalDelegate {
return [MetalDelegate()]
}
return nil
}
let createOptions: () -> Interpreter.Options? = {
if useMetalDelegate {
return nil
}
var options = Interpreter.Options()
options.threadCount = ProcessInfo.processInfo.processorCount >= 2 ? 2 : 1
return options
}
do {
// Create the `Interpreter`s.
let predictInterpreter = try Interpreter(
modelPath: predictModelPath,
options: createOptions(),
delegates: createDelegates()
)
// Allocate memory for the model's input `Tensor`s.
try predictInterpreter.allocateTensors()
// Create an StyleTransferer instance and return.
let photorater = PhotoRater(
tfLiteQueue: tfLiteQueue,
predictInterpreter: predictInterpreter
)
DispatchQueue.main.async {
completion(.success(photorater))
}
} catch let error {
print("Failed to create the interpreter with error: \(error.localizedDescription)")
DispatchQueue.main.async {
completion(.error(InitializationError.internalError(error)))
}
return
}
}
}
/// Initialize Style Transferer instance.
fileprivate init(
tfLiteQueue: DispatchQueue,
predictInterpreter: Interpreter
) {
// Store TF Lite intepreter
self.predictInterpreter = predictInterpreter
// Store the dedicated DispatchQueue for TFLite.
self.tfLiteQueue = tfLiteQueue
}
func runStyleTransfer(
photo image: UIImage,
completion: @escaping ((Result<PhotoRaterResult>) -> Void)) {
tfLiteQueue.async {
let outputTensor: Tensor
// let startTime: Date = Date()
// var preprocessingTime: TimeInterval = 0
// var stylePredictTime: TimeInterval = 0
// var styleTransferTime: TimeInterval = 0
// var postprocessingTime: TimeInterval = 0
// func timeSinceStart() -> TimeInterval {
// return abs(startTime.timeIntervalSinceNow)
// }
do {
guard
let inputRGBData = image.scaledData(
with: CGSize(width: 224, height: 224),
isQuantized: false
)
else {
DispatchQueue.main.async {
completion(.error(StyleTransferError.invalidImage))
}
print("Failed to convert the input image buffer to RGB data.")
return
}
// preprocessingTime = timeSinceStart()
// Copy the RGB data to the input `Tensor`.
try self.predictInterpreter.copy(inputRGBData, toInputAt: 0)
// Run inference by invoking the `Interpreter`.
try self.predictInterpreter.invoke()
// Get the output `Tensor` to process the inference results.
outputTensor = try self.predictInterpreter.output(at: 0)
// Grab bottleneck data from output tensor.
// stylePredictTime = timeSinceStart() - preprocessingTime
// Copy the RGB and bottleneck data to the input `Tensor`.
// try self.transferInterpreter.copy(inputRGBData, toInputAt: 0)
// try self.transferInterpreter.copy(bottleneck, toInputAt: 1)
// Run inference by invoking the `Interpreter`.
// try self.transferInterpreter.invoke()
// Get the result tensor
// outputTensor = try self.transferInterpreter.output(at: 0)
// styleTransferTime = timeSinceStart() - stylePredictTime - preprocessingTime
} catch let error {
print("Failed to invoke the interpreter with error: \(error.localizedDescription)")
DispatchQueue.main.async {
completion(.error(StyleTransferError.internalError(error)))
}
return
}
let result: Float
result = outputTensor.data.toArray(type: Float32.self)[0]
print(result)
// Construct image from output tensor data
// guard let cgImage = self.postprocessImageData(data: outputTensor.data) else {
// DispatchQueue.main.async {
// completion(.error(StyleTransferError.resultVisualizationError))
// }
// return
// }
//
// let outputImage = UIImage(cgImage: cgImage)
// postprocessingTime =
// timeSinceStart() - stylePredictTime - styleTransferTime - preprocessingTime
// Return the result.
DispatchQueue.main.async {
completion(
.success(
PhotoRaterResult(
result: result
)
)
)
}
}
}
}
/// Convenient enum to return result with a callback
enum Result<T> {
case success(T)
case error(Error)
}
/// Define errors that could happen in the initialization of this class
enum InitializationError: Error {
// Invalid TF Lite model
case invalidModel(String)
// Invalid label list
case invalidLabelList(String)
// TF Lite Internal Error when initializing
case internalError(Error)
}
/// Define errors that could happen when running style transfer
enum StyleTransferError: Error {
// Invalid input image
case invalidImage
// TF Lite Internal Error when initializing
case internalError(Error)
// Invalid input image
case resultVisualizationError
}
struct PhotoRaterResult {
let result: Float
}
private enum Constants {
// Namespace for Float16 models, optimized for GPU inference.
enum Float16 {
static let predictModel = "predict"
}
static let modelFileExtension = "tflite"
static let styleImageSize = CGSize(width: 224, height: 224)
static let inputImageSize = CGSize(width: 224, height: 224)
}
| 28.573077 | 102 | 0.632925 |
67f021c4f854eb84dfa17a847777364042ff3190 | 656 | /*:
## Exercise - Variables
Declare a variable `schooling` and set it to the number of years of school that you have completed. Print `schooling` to the console.
*/
var schooling = 17
print(schooling)
/*:
Now imagine you just completed an additional year of school, and update the `schooling` variable accordingly. Print `schooling` to the console.
*/
schooling = schooling + 1
print(schooling)
/*:
Does the above code compile? Why is this different than trying to update a constant? Print your explanation to the console using the `print` function.
*/
//: [Previous](@previous) | page 3 of 10 | [Next: App Exercise - Step Count](@next)
| 28.521739 | 151 | 0.721037 |
dd15330a5ab3c81bddc1f96e8970aa0d9e0824fb | 693 | //
// String+Regex.swift
// TelephoneDirectory
//
// Created by Daniele Salvioni on 12/11/2019.
// Copyright © 2019 Daniele Salvioni. All rights reserved.
//
import Foundation
extension String
{
public func match(pattern: String) -> Bool
{
return self.range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil
}
public func applyTemplate(pattern: String, templateMask: String, controlPattern: String) -> String?
{
let templated = self.replacingOccurrences(of: pattern, with: templateMask, options: [.regularExpression], range: nil)
return templated.matches(pattern: controlPattern) == true ? templated : nil
}
}
| 28.875 | 125 | 0.686869 |
9caea1df72f7a4c58e560aec2b003b3f0c76a4b0 | 6,820 | //
// DownLoadFiles.swift
// spdbapp
//
// Created by GBTouchG3 on 15/5/19.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
import Alamofire
class DownloadFile: NSObject {
var filebar: Float = 0
var fileid: String = ""
var filename: String = ""
}
var downloadlist:[DownloadFile] = []
class DownLoadManager: NSObject {
//判断当前文件夹是否存在jsondata数据,如果不存在,则继续进入下面的步骤
//如果存在该数据,则判断当前json与本地jsonlocal是否一致,如果一致,则打印 json数据信息已经存在,return
class func isSameJSONData(jsondata: NSData) -> Bool {
var localJSONPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/jsondata.txt")
var filemanager = NSFileManager.defaultManager()
if filemanager.fileExistsAtPath(localJSONPath){
let jsonLocal = filemanager.contentsAtPath(localJSONPath)
if jsonLocal == jsondata {
println("json数据信息已经存在")
return true
}
return false
}
return false
}
class func isSamePDFFile(fileid: String) -> Bool {
var filePath = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(fileid).pdf")
var filemanager = NSFileManager.defaultManager()
if filemanager.fileExistsAtPath(filePath){
for var i = 0; i < downloadlist.count; ++i {
if fileid == downloadlist[i].fileid {
downloadlist[i].filebar = 1
}
}
return true
}
return false
}
class func isFileDownload(id: String) -> Bool{
var filepath = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(id).pdf")
var manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath(filepath){
return true
}else{
return false
}
}
class func isStart(bool: Bool){
if bool == true{
downloadTest()
downLoadJSON()
}
}
class func downloadTest(){
var meeting = appManager.current
var meetingid = meeting.id
var sourcesInfo = meeting.sources
println("sourcesInfo.count = \(sourcesInfo.count)")
for var i = 0 ; i < sourcesInfo.count ; i++ {
var fileid = sourcesInfo[i].id
var filename = String()
//根据source的id去寻找对应的name
// if let sources = json["source"].array{
// for var k = 0 ; k < sources.count ; k++ {
// if fileid == sources[k]["id"].stringValue{
// filename = sources[k]["name"].stringValue
// }
// }
// }
var isfind:Bool = false
var downloadCurrentFile = DownloadFile()
downloadCurrentFile.filebar = 0
downloadCurrentFile.fileid = fileid
if downloadlist.count==0{
downloadlist.append(downloadCurrentFile)
}
else {
for var i = 0; i < downloadlist.count ; ++i {
if fileid == downloadlist[i].fileid {
isfind = true
}
}
if !isfind {
downloadlist.append(downloadCurrentFile)
}
}
//http://192.168.2.101:10086/gbtouch/meetings/e9f63596-ddac-4d19-996b-cd592d1b77af/570de66d-e17c-40e9-9daa-60e3e3b56894.pdf
var filepath = server.downloadFileUrl + "gbtouch/meetings/\(meetingid)/\(fileid).pdf"
var getPDFURL = NSURL(string: filepath)
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
println("filepath = \(filepath)")
//判断../Documents是否存在当前filename为名的文件,如果存在,则返回;如不存在,则下载文件
var b = self.isSamePDFFile(fileid)
if b == false{
Alamofire.download(.GET, getPDFURL!, destination).progress {
(_, totalBytesRead, totalBytesExpectedToRead) in
dispatch_async(dispatch_get_main_queue()) {
var processbar: Float = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
downloadCurrentFile.fileid = fileid
downloadCurrentFile.filebar = processbar
for var i = 0; i < downloadlist.count ; ++i {
if fileid == downloadlist[i].fileid {
if processbar > downloadlist[i].filebar {
downloadlist[i].filebar = processbar
// println("processbar\(i) = \(processbar)")
}
}
}
if totalBytesRead == totalBytesExpectedToRead {
println("\(fileid) 下载成功")
}
}
}
}
else if b == true{
println("\(fileid)文件已存在")
}
}
}
//下载json数据到本地并保存
class func downLoadJSON(){
Alamofire.request(.GET, server.meetingServiceUrl).responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, data, err) -> Void in
var jsonFilePath = NSHomeDirectory().stringByAppendingPathComponent("Documents/jsondata.txt")
println("\(data)")
if(err != nil){
println("下载当前json出错,error ===== \(err)")
return
}
var jsondata = NSJSONSerialization.dataWithJSONObject(data!, options: NSJSONWritingOptions.allZeros, error: nil)
//如果当前json和服务器上的json数据不一样,则保存。保存成功提示:当前json保存成功,否则提示:当前json保存失败。
var bool = self.isSameJSONData(jsondata!)
if !bool{
var b = jsondata?.writeToFile(jsonFilePath, atomically: true)
if (b! == true) {
NSLog("当前json保存成功")
}
else{
NSLog("当前json保存失败")
}
}
var manager = NSFileManager.defaultManager()
if !manager.fileExistsAtPath(jsonFilePath){
var b = manager.createFileAtPath(jsonFilePath, contents: nil, attributes: nil)
if b{
println("创建json成功")
}
}
}
}
}
| 33.930348 | 150 | 0.501906 |
e40ba944e30ba36ddf46eea3eea9023ca81869e6 | 1,600 | //
// Copyright (c) 2021 Related Code - https://relatedcode.com
//
// 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 Walkthrough5Cell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
@IBOutlet var labelFeature1: UILabel!
@IBOutlet var labelDescription1: UILabel!
@IBOutlet var labelFeature2: UILabel!
@IBOutlet var labelDescription2: UILabel!
//-------------------------------------------------------------------------------------------------------------------------------------------
func bindData(index: Int, data: [String: String]) {
guard let feature1 = data["feature1"] else { return }
guard let description1 = data["description1"] else { return }
guard let feature2 = data["feature2"] else { return }
guard let description2 = data["description2"] else { return }
imageView.sample("Social", "Couples", index + 5)
labelFeature1.text = feature1
labelDescription1.text = description1
labelFeature2.text = feature2
labelDescription2.text = description2
}
}
| 42.105263 | 145 | 0.615625 |
72639e0d633a525bf8c1d44f3fa04d11bcc20973 | 6,194 | //
// Created by Andrew Podkovyrin
// Copyright © 2019 Dash Core Group. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// 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
final class LocaleItem: NSObject, SearchSelectorItem {
private(set) var attributedTitle: NSAttributedString
/** These properties need @objc to make them key value compliant when filtering using NSPredicate,
and so they are accessible and usable in Objective-C to interact with other frameworks.
*/
@objc let code: String
@objc let localizedCode: String
init(code: String, localizedCode: String) {
self.code = code
self.localizedCode = localizedCode
attributedTitle = LocaleItem.attributedString(code: code,
localizedCode: localizedCode,
searchQuery: "")
}
func updateAttributedTitle(with searchQuery: String) {
attributedTitle = LocaleItem.attributedString(code: code,
localizedCode: localizedCode,
searchQuery: searchQuery)
}
}
private extension LocaleItem {
static func attributedString(code: String, localizedCode: String, searchQuery: String) -> NSAttributedString {
let font = UIFont.preferredFont(forTextStyle: .body)
let textColor = Styles.Colors.textColor
let string = [code, localizedCode].joined(separator: " - ")
if searchQuery.isEmpty {
let attributes = [NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: textColor]
return NSAttributedString(string: string, attributes: attributes)
}
else {
return NSAttributedString.attributedText(string,
font: font,
textColor: textColor,
highlightedText: searchQuery,
highlightedTextColor: Styles.Colors.tintColor)
}
}
}
final class LocaleSelectorModel: SearchSelectorModel {
var items: [LocaleItem] {
if searchQuery.isEmpty {
return allItems
}
else {
return filteredItems
}
}
private(set) var selectedItems: Set<LocaleItem>
let allowsMultiSelection: Bool
private var allItems: [LocaleItem]
private var searchQuery = ""
private var filteredItems = [LocaleItem]()
init(codes: [String],
localizeCode: (String) -> (String),
selectedCodes: Set<String>,
allowsMultiSelection: Bool = false) {
var items = [LocaleItem]()
var selectedItems = Set<LocaleItem>()
for code in codes {
let localizedCode = localizeCode(code)
let localeItem = LocaleItem(code: code, localizedCode: localizedCode)
items.append(localeItem)
if selectedCodes.contains(code) {
selectedItems.insert(localeItem)
}
}
allItems = items
self.selectedItems = selectedItems
self.allowsMultiSelection = allowsMultiSelection
}
func filterItems(searchQuery: String) {
self.searchQuery = searchQuery
let predicate = searchPredicate(for: searchQuery)
filteredItems = allItems.filter { predicate.evaluate(with: $0) }
allItems.forEach { $0.updateAttributedTitle(with: searchQuery) }
}
func toggleSelection(for item: LocaleItem) {
if !allowsMultiSelection {
selectedItems.removeAll()
}
if selectedItems.contains(item) {
selectedItems.remove(item)
}
else {
selectedItems.insert(item)
}
}
func toggleAllSelection() {
assert(allowsMultiSelection)
if selectedItems.isEmpty {
selectedItems = Set(allItems)
}
else {
selectedItems = Set()
}
}
// MARK: Private
private func searchPredicate(for query: String) -> NSPredicate {
let searchItems = query.components(separatedBy: " ") as [String]
let andMatchPredicates: [NSPredicate] = searchItems.map { searchString in
findMatches(searchString: searchString)
}
let finalCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: andMatchPredicates)
return finalCompoundPredicate
}
private func findMatches(searchString: String) -> NSCompoundPredicate {
enum ExpressionKeys: String {
case code
case localizedCode
}
var searchItemsPredicate = [NSPredicate]()
let searchKeyPaths = [ExpressionKeys.code.rawValue, ExpressionKeys.localizedCode.rawValue]
for keyPath in searchKeyPaths {
let leftExpression = NSExpression(forKeyPath: keyPath)
let rightExpression = NSExpression(forConstantValue: searchString)
let comparisonPredicate =
NSComparisonPredicate(leftExpression: leftExpression,
rightExpression: rightExpression,
modifier: .direct,
type: .contains,
options: [.caseInsensitive, .diacriticInsensitive])
searchItemsPredicate.append(comparisonPredicate)
}
let orMatchPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: searchItemsPredicate)
return orMatchPredicate
}
}
| 34.797753 | 114 | 0.60494 |
894bdb551ba3c1825e3ce44dfdf01256ad6cff78 | 1,575 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class ListViewController: UITableViewController {
var list = [String]()
private var selectAction: ((Int) -> Void)?
func setSelectAction(_ action: @escaping (Int) -> Void) {
selectAction = action
}
// MARK: tableview data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
// MARK: tableview delegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell", for: indexPath)
cell.textLabel?.text = list[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectAction?(indexPath.row)
}
}
| 32.142857 | 109 | 0.686349 |
0a78dde90e0881ab3612df49cf83cf6165a03f63 | 556 | //
// Edges.swift
// TestPr
//
// Created by crypto_user on 09/09/2019.
// Copyright © 2019 crypto_user. All rights reserved.
//
import UIKit
import VDKit
extension Edges.Set {
var attributes: [NSLayoutConstraint.Attribute] {
var result: [NSLayoutConstraint.Attribute] = []
if contains(.top) { result.append(.top) }
if contains(.bottom) { result.append(.bottom) }
if contains(.trailing) { result.append(.trailing) }
if contains(.leading) { result.append(.leading) }
return result
}
}
| 23.166667 | 59 | 0.629496 |
16ab6bdd2a9c170f789d3220cf84301c0e2a806e | 6,557 | //
// CardsCollectionViewLayout.swift
// CardsExample
//
// Created by Filipp Fediakov on 18.08.17.
// Copyright © 2017 filletofish. All rights reserved.
//
import UIKit
open class CardsCollectionViewLayout: UICollectionViewLayout {
// MARK: - Layout configuration
public var itemSize: CGSize = CGSize(width: 200, height: 300) {
didSet{
invalidateLayout()
}
}
public var spacing: CGFloat = 10.0 {
didSet{
invalidateLayout()
}
}
public var maximumVisibleItems: Int = 4 {
didSet{
invalidateLayout()
}
}
// MARK: UICollectionViewLayout
override open var collectionView: UICollectionView {
return super.collectionView!
}
override open var collectionViewContentSize: CGSize {
let itemsCount = CGFloat(collectionView.numberOfItems(inSection: 0))
return CGSize(width: collectionView.bounds.width * itemsCount,
height: collectionView.bounds.height)
}
override open func prepare() {
super.prepare()
assert(collectionView.numberOfSections == 1, "Multiple sections aren't supported!")
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let totalItemsCount = collectionView.numberOfItems(inSection: 0)
let minVisibleIndex = max(Int(collectionView.contentOffset.x) / Int(collectionView.bounds.width), 0)
let maxVisibleIndex = min(minVisibleIndex + maximumVisibleItems, totalItemsCount)
let contentCenterX = collectionView.contentOffset.x + (collectionView.bounds.width / 2.0)
let deltaOffset = Int(collectionView.contentOffset.x) % Int(collectionView.bounds.width)
let percentageDeltaOffset = CGFloat(deltaOffset) / collectionView.bounds.width
let visibleIndices = stride(from: minVisibleIndex, to: maxVisibleIndex, by: 1)
let attributes: [UICollectionViewLayoutAttributes] = visibleIndices.map { index in
let indexPath = IndexPath(item: index, section: 0)
return computeLayoutAttributesForItem(indexPath: indexPath,
minVisibleIndex: minVisibleIndex,
contentCenterX: contentCenterX,
deltaOffset: CGFloat(deltaOffset),
percentageDeltaOffset: percentageDeltaOffset)
}
return attributes
}
public func getVisiblesIndicates() -> [IndexPath] {
let totalItemsCount = collectionView.numberOfItems(inSection: 0)
let minVisibleIndex = max(Int(collectionView.contentOffset.x) / Int(collectionView.bounds.width), 0)
let maxVisibleIndex = min(minVisibleIndex + maximumVisibleItems, totalItemsCount)
return stride(from: minVisibleIndex, to: maxVisibleIndex, by: 1).map { IndexPath(item: $0, section: 0) }
}
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let contentCenterX = collectionView.contentOffset.x + (collectionView.bounds.width / 2.0)
let minVisibleIndex = Int(collectionView.contentOffset.x) / Int(collectionView.bounds.width)
let deltaOffset = Int(collectionView.contentOffset.x) % Int(collectionView.bounds.width)
let percentageDeltaOffset = CGFloat(deltaOffset) / collectionView.bounds.width
return computeLayoutAttributesForItem(indexPath: indexPath,
minVisibleIndex: minVisibleIndex,
contentCenterX: contentCenterX,
deltaOffset: CGFloat(deltaOffset),
percentageDeltaOffset: percentageDeltaOffset)
}
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
// MARK: - Layout computations
fileprivate extension CardsCollectionViewLayout {
private func scale(at index: Int) -> CGFloat {
let translatedCoefficient = CGFloat(index) - CGFloat(self.maximumVisibleItems) / 2
return CGFloat(pow(0.95, translatedCoefficient))
}
private func transform(atCurrentVisibleIndex visibleIndex: Int, percentageOffset: CGFloat) -> CGAffineTransform {
var rawScale = visibleIndex < maximumVisibleItems ? scale(at: visibleIndex) : 1.0
if visibleIndex != 0 {
let previousScale = scale(at: visibleIndex - 1)
let delta = (previousScale - rawScale) * percentageOffset
rawScale += delta
}
return CGAffineTransform(scaleX: rawScale, y: rawScale)
}
fileprivate func computeLayoutAttributesForItem(indexPath: IndexPath,
minVisibleIndex: Int,
contentCenterX: CGFloat,
deltaOffset: CGFloat,
percentageDeltaOffset: CGFloat) -> UICollectionViewLayoutAttributes {
let attributes = UICollectionViewLayoutAttributes(forCellWith:indexPath)
let visibleIndex = indexPath.row - minVisibleIndex
attributes.size = itemSize
let midY = self.collectionView.bounds.midY
attributes.center = CGPoint(x: contentCenterX + spacing * CGFloat(visibleIndex),
y: midY + spacing * CGFloat(visibleIndex))
attributes.zIndex = maximumVisibleItems - visibleIndex
attributes.transform = transform(atCurrentVisibleIndex: visibleIndex,
percentageOffset: percentageDeltaOffset)
switch visibleIndex {
case 0:
attributes.center.x -= deltaOffset
break
case 1..<maximumVisibleItems:
attributes.center.x -= spacing * percentageDeltaOffset
attributes.center.y -= spacing * percentageDeltaOffset
if visibleIndex == maximumVisibleItems - 1 {
attributes.alpha = percentageDeltaOffset
}
break
default:
attributes.alpha = 0
break
}
return attributes
}
}
| 41.5 | 121 | 0.608815 |
620ad7415be06c5be421de25c98448b4cbc8a343 | 973 | // RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s
// XFAIL: *
@_fixed_layout
public struct Vector<T> : VectorNumeric {
public var x: T
public var y: T
public typealias ScalarElement = T
public init(_ scalar: T) {
self.x = scalar
self.y = scalar
}
}
// This exists to minimize generated SIL.
@inline(never) func abort() -> Never { fatalError() }
@differentiable(adjoint: fakeAdj)
public func + <T>(lhs: Vector<T>, rhs: Vector<T>) -> Vector<T> {
abort()
}
@differentiable(adjoint: fakeAdj)
public func - <T>(lhs: Vector<T>, rhs: Vector<T>) -> Vector<T> {
abort()
}
@differentiable(adjoint: fakeAdj)
public func * <T>(lhs: Vector<T>, rhs: Vector<T>) -> Vector<T> {
abort()
}
public func fakeAdj<T>(seed: Vector<T>, y: Vector<T>, lhs: Vector<T>, rhs: Vector<T>) -> (Vector<T>, Vector<T>) {
abort()
}
public func test1() {
func foo(_ x: Vector<Float>) -> Vector<Float> {
return x + x
}
_ = gradient(at: Vector(0), in: foo)
}
| 22.627907 | 113 | 0.631038 |
e46078477efab2b5e181ae103d3e08932745dafe | 2,211 | //
// AppDelegate.swift
// PassDataWithDelegationInSwift
//
// Created by Carlos Santiago Cruz on 03/11/18.
// Copyright © 2018 Carlos Santiago Cruz. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47.042553 | 285 | 0.75848 |
e069869ce81630ff2a8960fc1910d78804551d04 | 3,084 | // This source file is part of the https://github.com/ColdGrub1384/Pisth open source project
//
// Copyright (c) 2017 - 2018 Adrian Labbé
// Licensed under Apache License v2.0
//
// See https://raw.githubusercontent.com/ColdGrub1384/Pisth/master/LICENSE for license information
import UIKit
/// Git branches table view controller to display Git remote branches at `repoPath`.
class GitRemotesTableViewController: GitBranchesTableViewController {
override func viewDidLoad() {
tableView.backgroundView = UIActivityIndicatorView(style: .gray)
(tableView.backgroundView as? UIActivityIndicatorView)?.startAnimating()
tableView.tableFooterView = UIView()
navigationItem.setRightBarButtonItems(nil, animated: false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
ConnectionManager.shared.runTask {
_ = ConnectionManager.shared.filesSession!.channel.execute("git -C '\(self.repoPath!)' remote update --prune", error: nil)
var error: NSError?
let result = ConnectionManager.shared.filesSession!.channel.execute("git -C '\(self.repoPath!)' branch -r", error: &error)
if error == nil {
for branch in result.components(separatedBy: "\n") {
if !branch.contains("/HEAD ") && branch.replacingOccurrences(of: " ", with: "") != "" {
self.branches.append(branch.replacingOccurrences(of: " ", with: ""))
}
}
}
DispatchQueue.main.async {
self.tableView.backgroundView = nil
self.tableView.reloadData()
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "branch", for: indexPath)
guard let title = cell.viewWithTag(1) as? UILabel else { return cell }
guard let isCurrent = cell.viewWithTag(2) as? UILabel else { return cell }
title.text = branches[indexPath.row]
isCurrent.isHidden = (current != branches[indexPath.row])
return cell
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let handler = selectionHandler {
handler(self, indexPath)
return
}
launch(command: "git -C '\(repoPath!)' log --graph \(branches[indexPath.row])", withTitle: "Commits for \(branches[indexPath.row])")
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - Storyboard
override class func makeViewController() -> GitRemotesTableViewController {
return UIStoryboard(name: "Git", bundle: nil).instantiateViewController(withIdentifier: "remoteBranches") as! GitRemotesTableViewController
}
}
| 40.051948 | 147 | 0.629377 |
e00dd510cf73815c074599eb0d4c20f4461a1784 | 1,695 | //
// ViewController.swift
// CustomControl
//
// Created by Hoang Anh on 9/27/17.
// Copyright © 2017 anh. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var emailTextField: EmailTextField!
@IBOutlet weak var passwordTextField: PasswordTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.isNavigationBarHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.emailTextField.text = "[email protected]"
self.passwordTextField.text = "123456"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Action
@IBAction func loginButtonAction(_ sender: Any) {
do {
try self.emailTextField.checkValidInput()
try self.passwordTextField.checkValidInput()
self.didLogin(email: self.emailTextField.text, password: self.passwordTextField.text)
} catch let error {
print(error)
}
}
func didLogin(email: String, password: String) {
if email == "[email protected]" && password == "123456" {
print("Login success")
let ratingViewController = RatingViewController(nibName: "RatingViewController", bundle: nil)
self.navigationController?.pushViewController(ratingViewController, animated: true)
} else {
print("Email or password is wrong")
}
}
}
| 29.736842 | 105 | 0.646018 |
e804753c4c0d50f6b2de19aa2ceeb0edce05a601 | 3,337 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
private final class ChatHandler: ChannelInboundHandler {
public typealias InboundIn = ByteBuffer
public typealias OutboundOut = ByteBuffer
private func printByte(_ byte: UInt8) {
#if os(Android)
print(Character(UnicodeScalar(byte)), terminator:"")
#else
fputc(Int32(byte), stdout)
#endif
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
var buffer = self.unwrapInboundIn(data)
while let byte: UInt8 = buffer.readInteger() {
printByte(byte)
}
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
print("error: ", error)
// As we are not really interested getting notified on success or failure we just pass nil as promise to
// reduce allocations.
context.close(promise: nil)
}
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let bootstrap = ClientBootstrap(group: group)
// Enable SO_REUSEADDR.
.channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.channelInitializer { channel in
channel.pipeline.addHandler(ChatHandler())
}
defer {
try! group.syncShutdownGracefully()
}
// First argument is the program path
let arguments = CommandLine.arguments
let arg1 = arguments.dropFirst().first
let arg2 = arguments.dropFirst(2).first
let defaultHost = "127.0.0.1"
let defaultPort = 9999
enum ConnectTo {
case ip(host: String, port: Int)
case unixDomainSocket(path: String)
}
let connectTarget: ConnectTo
switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) {
case (.some(let h), _ , .some(let p)):
/* we got two arguments, let's interpret that as host and port */
connectTarget = .ip(host: h, port: p)
case (.some(let portString), .none, _):
/* couldn't parse as number, expecting unix domain socket path */
connectTarget = .unixDomainSocket(path: portString)
case (_, .some(let p), _):
/* only one argument --> port */
connectTarget = .ip(host: defaultHost, port: p)
default:
connectTarget = .ip(host: defaultHost, port: defaultPort)
}
let channel = try { () -> Channel in
switch connectTarget {
case .ip(let host, let port):
return try bootstrap.connect(host: host, port: port).wait()
case .unixDomainSocket(let path):
return try bootstrap.connect(unixDomainSocketPath: path).wait()
}
}()
print("ChatClient connected to ChatServer: \(channel.remoteAddress!), happy chatting\n. Press ^D to exit.")
while let line = readLine(strippingNewline: false) {
var buffer = channel.allocator.buffer(capacity: line.utf8.count)
buffer.writeString(line)
try! channel.writeAndFlush(buffer).wait()
}
// EOF, close connect
try! channel.close().wait()
print("ChatClient closed")
| 32.086538 | 112 | 0.659574 |
649af7a8c274df1f37d461388e0958c9e09d31ca | 853 | //
// FullScreenDisclaimerInteractorTest.swift
// AptoSDK
//
// Created by Takeichi Kanzaki on 08/06/2018.
//
//
import XCTest
import AptoSDK
@testable import AptoUISDK
class FullScreenDisclaimerInteractorTest: XCTestCase {
private var sut: FullScreenDisclaimerInteractor!
// Collaborators
private let serviceLocator = ServiceLocatorFake()
private let disclaimer: Content = .plainText("Disclaimer")
override func setUp() {
super.setUp()
sut = FullScreenDisclaimerInteractor(disclaimer: disclaimer)
}
func testProvideDisclaimerSetDisclaimerToDataReceiver() {
// Given
var returnedDisclaimer: Content?
// When
sut.provideDisclaimer { disc in
returnedDisclaimer = disc
}
// Then
XCTAssertEqual(disclaimer, returnedDisclaimer!) // swiftlint:disable:this implicitly_unwrapped_optional
}
}
| 21.871795 | 107 | 0.742087 |
21a962d7d475907fe1eb24364775cbef77bfecbc | 23,345 | //
// LocationMaster.swift
// Bladey
//
// Created by Marco Filetti on 13/05/2017.
// Copyright © 2017 Marco Filetti. All rights reserved.
//
import Foundation
import CoreLocation
import os.log
/// The location master delegate is notified of the distance and angle
/// from the last location received
@objc protocol LocationMasterDelegate: class {
/// Gives update on how distant we are from a given point and how to get there. Gets called only if we are not standing still.
@objc optional func locationMaster(provideIndication: Indication)
/// Retrieves the last received location
@objc optional func locationMaster(didReceiveLocation: CLLocation)
/// Tells that the GPS signal has been missing for some time.
/// May be sent repeatedly if old signals are received.
@objc optional func locationMasterSignalLost()
/// Tells that we are standing still (if not using magnetometer).
/// Will be sent repeatedly until we start moving.
@objc optional func locationMasterStandingStill()
/// Acknowledges that the location master stopped itself
/// (e.g. when the nearby notification was triggered and we are configured to
/// stop once that happens)
@objc optional func locationMasterDidStop()
/// Updates the heading
@objc optional func locationMaster(headingUpdated: Double)
}
/// The location master is the heart of both phone and watch apps.
/// It is responsible for retrieving locations, and telling us distance
/// from the given location.
class LocationMaster: NSObject, CLLocationManagerDelegate {
/// The great location master itself
static let shared = LocationMaster()
/// Returns true if we are standing still (indication updates should
/// not be sent in this case)
private(set) var standingStill = false { didSet {
if standingStill, !useMagnetometer {
masterDelegate?.locationMasterStandingStill?()
}
} }
/// True if signal was lost
private(set) var signalLost = false { didSet {
if signalLost {
masterDelegate?.locationMasterSignalLost?()
}
} }
/// True if we want to use magnetometer and the device has it
var useMagnetometer: Bool {
CLLocationManager.headingAvailable() && LocationMaster.shared.magnetometerPref
}
/// Magnetometer preference set by user.
/// Can change this value to enable / disable magnetometer
var magnetometerPref = UserDefaults.standard.bool(forKey: Constants.Defs.useMagnetometer) { didSet {
if isRunning {
if CLLocationManager.headingAvailable() {
startHeading()
} else {
stopHeading()
}
}
} }
/// Device orientation (for magnetometer).
/// Change this to propagate changes
static var orientation: DeviceOrientation = .portrait { didSet {
if shared.useMagnetometer {
switch orientation {
case .portrait:
LocationMaster.shared.locManager.headingOrientation = .portrait
#if !WatchApp
case .landscapeLeft:
LocationMaster.shared.locManager.headingOrientation = .landscapeLeft
case .landscapeRight:
LocationMaster.shared.locManager.headingOrientation = .landscapeRight
case .portraitUpsideDown:
// portrait upside down is perceived as upside up, since when upside down it actually appears as normal portrait
LocationMaster.shared.locManager.headingOrientation = .portrait
#endif
}
}
}}
// MARK: - Navigation variables
/// Destination that we give directions to.
/// If nil, gives directions towards north (compass mode).
var destination: Destination? { didSet {
if destination != nil {
referenceLocation = CLLocation(latitude: destination!.latitude, longitude: destination!.longitude)
} else {
referenceLocation = nil
}
} }
/// This gets set to true if we attempt to start
/// without proper authorization
var shouldAskForAuth = false
/// True if we started
var isRunning: Bool = false
/// True if we force closed the app
var forceClosed: Bool = false
/// Speed buffer
var speedBuffer = RunningBuffer(size: Constants.etaBufferSize)
/// Location buffer for standing detection
let locBuffer = LocationBuffer(maxLocationDuration: Constants.standingStillTime)
/// Angle buffer for angle smoothing
var angleBuffer = RunningBuffer(size: Constants.angleBufferSize)
// MARK: - Stable properties
/// To be notified of new information
/// set to nil to stop communication, or set to a new delegate.
weak var masterDelegate: LocationMasterDelegate?
/// Core location informing us about new locations
let locManager: CLLocationManager
/// Geocoder to reverse location info
let geocoder = CLGeocoder()
/// Wheter we should use km or miles
static var usesMetric: Bool { get {
switch Options.Measurements.saved {
case .automatic:
if Locale.current.usesMetricSystem && Locale.current.identifier != "en_GB" {
return true
} else {
return false
}
case .metricWithComma, .metricWithDot:
return true
case .imperial:
return false
}
} }
// MARK: - Private variables
/// Number of location updates collected so far (start() resets this)
private(set) var nOfLocationUpdates: UInt = 0
/// Last time an indication with good FuzzyAccuracy was sent to delegate
private(set) var lastGoodIndicationDate = Date.distantPast
/// Last indication sent
private(set) var lastIndication: Indication?
/// Last location received from CLLocationManager
private(set) var lastLocation: CLLocation?
/// Reference location (updated when destination changes).
/// If nil, gives indications towards north (compass mode).
private var referenceLocation: CLLocation?
/// Gets set to the current date when we ask for relaxation. If
/// enough time passed (relaxEnableTime), reduce GPS accuracy
private(set) var relaxedModeEngaged: Date? = nil
/// Become true once we are actively reducing GPS accuracy.
private(set) var relaxedMode: Bool = false
/// Time for signal lost (should be nil when not running)
private var signalLostTimer: Timer?
// MARK: - Initialization
/// Creates a new instance.
/// Only itself can create itself, therefore make use of shared.
private override init() {
locManager = CLLocationManager()
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(nearbyNotificationTriggeredStop(_:)), name: Constants.Notifications.nearDistanceNotificationStopTracking, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(runInBackgroundToggled(_:)), name: Constants.Notifications.changedRunInBackgroundPreference, object: nil)
locManager.delegate = self
}
// MARK: - Notification callbacks
@objc private func nearbyNotificationTriggeredStop(_ notification: Notification) {
// if we are asked to stop ourselves, do so
if isRunning {
stop()
masterDelegate?.locationMasterDidStop?()
}
}
@objc private func runInBackgroundToggled(_ notification: Notification) {
#if WatchApp
if #available(watchOSApplicationExtension 4.0, *) {
let runInBackground = UserDefaults.standard.object(forKey: Constants.Defs.runInBackground) as! Bool
locManager.allowsBackgroundLocationUpdates = runInBackground
}
#else
let runInBackground = UserDefaults.standard.object(forKey: Constants.Defs.runInBackground) as! Bool
locManager.allowsBackgroundLocationUpdates = runInBackground
#endif
}
// MARK: - Timer callbacks
@objc private func signalLostCheck(_ timer: Timer) {
guard isRunning, let lastLoc = lastLocation, !signalLost else { return }
if lastLoc.timestamp.addingTimeInterval(Constants.signalLostTime) < Date() {
signalLost = true
}
}
// MARK: - Internal Methods
/// Starts location updates and initiates location data collection.
/// Must make sure that we have proper location authorizations beforehand.
/// Can throw a `StartFailure`
func start() throws {
guard !forceClosed else {
return
}
nOfLocationUpdates = 0
speedBuffer = RunningBuffer(size: Constants.etaBufferSize)
angleBuffer = RunningBuffer(size: Constants.angleBufferSize)
shouldAskForAuth = false
lastGoodIndicationDate = Date.distantPast
lastIndication = nil
lastLocation = nil
relaxedMode = false
locBuffer.reset()
standingStill = false
relaxedModeEngaged = nil
NotificationHelper.sentNearDistanceNotification = false
NotificationHelper.sentETANotification = false
let locAuthStatus = CLLocationManager.authorizationStatus()
guard locAuthStatus == .authorizedWhenInUse || locAuthStatus == .authorizedAlways else {
shouldAskForAuth = true
throw StartFailure.locationAuthorization
}
guard !isRunning else {
throw StartFailure.alreadyStarted
}
self.isRunning = true
signalLostTimer = Timer(timeInterval: 2.5, target: self, selector: #selector(signalLostCheck), userInfo: nil, repeats: true)
RunLoop.current.add(signalLostTimer!, forMode: .common)
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.distanceFilter = kCLDistanceFilterNone
#if WatchApp
if #available(watchOSApplicationExtension 4.0, *) {
locManager.activityType = .other
locManager.allowsBackgroundLocationUpdates = UserDefaults.standard.object(forKey: Constants.Defs.runInBackground) as! Bool
}
#else
locManager.allowsBackgroundLocationUpdates = UserDefaults.standard.object(forKey: Constants.Defs.runInBackground) as! Bool
locManager.pausesLocationUpdatesAutomatically = false
locManager.activityType = .other
#endif
locManager.startUpdatingLocation()
startHeading()
}
/// Stops location data collection.
func stop(final: Bool = false) {
guard final || self.isRunning else {
return
}
self.isRunning = false
if final {
forceClosed = true
self.masterDelegate = nil
locManager.delegate = nil
}
signalLostTimer?.invalidate()
signalLostTimer = nil
locManager.stopUpdatingLocation()
stopHeading()
#if WatchApp
if #available(watchOSApplicationExtension 4.0, *) {
locManager.allowsBackgroundLocationUpdates = false
}
#else
locManager.allowsBackgroundLocationUpdates = false
#endif
}
func startHeading() {
if useMagnetometer {
locManager.startUpdatingHeading()
}
}
func stopHeading() {
if CLLocationManager.headingAvailable() {
locManager.stopUpdatingHeading()
if lastIndication == nil {
masterDelegate?.locationMasterSignalLost?()
}
}
}
/// Sets to top accuracy (e.g. when entering foreground)
func increaseAccuracy() {
relaxedModeEngaged = nil
relaxedMode = false
if locManager.desiredAccuracy != kCLLocationAccuracyBest {
locManager.desiredAccuracy = kCLLocationAccuracyBest
}
}
/// Relaxes accuracy depending on the distance to the target and
/// notification geofence
func relaxAccuracy() {
guard UserDefaults.standard.object(forKey: Constants.Defs.batterySaving) as! Bool else {
return
}
if isRunning {
relaxedModeEngaged = Date()
assessAccuracy()
}
}
/// Returns true if we don't have authorization
func notAuthorized() -> Bool {
if CLLocationManager.authorizationStatus() == .notDetermined {
return false
}
if CLLocationManager.authorizationStatus() == .authorizedAlways {
return false
}
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
return false
}
return true
}
/// Check if authorization is not determined, and if so requests
/// to authorize
func verifyAuthorization() {
if CLLocationManager.authorizationStatus() == .notDetermined {
requestLocationAuthorization()
}
}
/// Gets a convenience last location (if any)
func getConvenienceLocation() -> CLLocation? {
let locAuthStatus = CLLocationManager.authorizationStatus()
guard locAuthStatus == .authorizedWhenInUse || locAuthStatus == .authorizedAlways else {
return nil
}
guard let locManagerLoc = locManager.location else {
return nil
}
// return own location if it exists and is recent, otherwise locManager's
if let ownLoc = lastLocation, ownLoc.horizontalAccuracy > 0, ownLoc.timestamp > locManagerLoc.timestamp {
return ownLoc
} else if locManagerLoc.horizontalAccuracy > 0 {
return locManagerLoc
} else {
return nil
}
}
/// Reverse geocoder info to get a title
func getInfo(forLocation: CLLocation, callback: @escaping (String?) -> Void) {
geocoder.reverseGeocodeLocation(forLocation) {
placemarks, error in
if let error = error {
os_log("Error while reversing geocoding info: %@", type: .error, error.localizedDescription)
callback(nil)
}
if let pl = placemarks?.first, let tf = pl.thoroughfare {
callback(tf)
} else {
callback(nil)
}
}
}
/// Gets an accurate location asynchronously.
/// Will call locationMaster(didReceiveLocation: CLLocation) later.
func fetchLocation() throws {
let locAuthStatus = CLLocationManager.authorizationStatus()
guard locAuthStatus == .authorizedWhenInUse || locAuthStatus == .authorizedAlways else {
throw StartFailure.locationAuthorization
}
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.requestLocation()
}
// MARK: - Private methods
/// Check if we need to increase / decrease GPS accuracy, based
/// on whether notifications are on, which distance we are interested in
/// and how far we are from destination.
/// For relaxed mode.
private func assessAccuracy() {
guard let relaxDate = relaxedModeEngaged else {
return
}
// fist check how long ago relaxAccuracy was called.
// if not so long ago (e.g. 2 minutes ago) do nothing
// enable relaxed mode after some time that it was requested
if !relaxedMode && relaxDate.addingTimeInterval(Constants.relaxEnableTime) < Date() {
relaxedMode = true
}
guard relaxedMode else {
return
}
guard let lastIndication = self.lastIndication, lastIndication.distance > 0 else {
return
}
let adjustedAccuracy: CLLocationAccuracy
// convert numeric accuracy to a kCLAccuracy value
if lastIndication.minimumDistance > 9000 {
adjustedAccuracy = kCLLocationAccuracyThreeKilometers
} else if lastIndication.minimumDistance > 3000 {
adjustedAccuracy = kCLLocationAccuracyKilometer
} else if lastIndication.minimumDistance > 1000 {
adjustedAccuracy = kCLLocationAccuracyHundredMeters
} else if lastIndication.minimumDistance > 200 {
adjustedAccuracy = kCLLocationAccuracyNearestTenMeters
} else {
adjustedAccuracy = kCLLocationAccuracyBest
}
// before enacting change, check again that we should do that
guard self.relaxedModeEngaged != nil && self.relaxedMode else {
return
}
// if needed kCLAccuracy is different from current, set new value
if adjustedAccuracy != locManager.desiredAccuracy {
locManager.desiredAccuracy = adjustedAccuracy
}
}
/// Return an ETA using the previous indication and the current indication.
/// Manipulates the speedBuffer. If nil, no reliable value could be calculated.
private func calculateETA(_ indication: Indication, lastIndication: Indication) -> TimeInterval? {
// Fail if either distance is negative (invalid)
guard indication.distance >= 0 && lastIndication.distance >= 0 else {
return nil
}
// We proceed only if both accuracies are not bad, or if relaxed mode is on
// only if the two accuracies are within a given proportion of each other
let etaProceed: Bool
if relaxedMode {
// when in relaxed mode, both values' accuracies must be within a given proportion of each other
etaProceed = withinProportion(indication.accuracy, lastIndication.accuracy, p: Constants.maxEtaAccuracyPropDiffRelaxed)
} else {
// when not in relaxed mode, indications accuracies must be similar
etaProceed = lastIndication.similarAccuracy(indication)
}
guard etaProceed else {
return nil
}
// to calculate eta, calculate difference in relative distance between this location and the last one
let distDiff = lastIndication.relativeDistance - indication.relativeDistance
// calculate time passed during move, get speed it and add to buffer
let timeDiff = indication.location.timestamp.timeIntervalSince(lastIndication.location.timestamp)
let relativeSpeed = distDiff / timeDiff
speedBuffer.addSample(relativeSpeed)
// weighted speed weights recent values more than old ones
guard let wSpeed = speedBuffer.weightedMean(), wSpeed > 0 else {
return nil
}
let estimate = indication.relativeDistance / wSpeed
// less than 24 hours
guard estimate >= 0, estimate < 24 * 60 * 60 else {
return nil
}
return estimate
}
/// Request authorizations to use location (assuming
/// authorization was not determined).
private func requestLocationAuthorization() {
guard CLLocationManager.authorizationStatus() == .notDetermined else {
os_log("Authorization was already set, pointless to call this", type: .error)
return
}
locManager.requestWhenInUseAuthorization()
}
// MARK: - CLLocation delegate adoption
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
lastLocation = location
guard let masterDelegate = masterDelegate else { return }
guard location.horizontalAccuracy >= 0 else {
os_log("Received invalid location", type: .fault)
return
}
masterDelegate.locationMaster?(didReceiveLocation: location)
guard isRunning else {
return
}
nOfLocationUpdates += 1
guard nOfLocationUpdates >= Constants.minNoOfLocations else {
return
}
signalLost = location.timestamp.addingTimeInterval(Constants.signalLostTime) < Date()
if signalLost {
return
}
locBuffer.addLocation(newLocation: location)
standingStill = locBuffer.standing()
guard !standingStill || useMagnetometer else {
return
}
let maybeIndication: Indication?
// Create location using a reference or in compass mode
if let refLoc = referenceLocation {
maybeIndication = Indication(currentLocation: location, referenceLocation: refLoc, previousIndication: lastIndication, previousBuffer: angleBuffer)
} else {
maybeIndication = Indication(towardsNorthFromLocation: location, previousIndication: lastIndication, previousBuffer: angleBuffer)
}
guard let indication = maybeIndication else {
os_log("Invalid indication created (should never happen)", type: .error)
return
}
// add angle to buffer, if any
if let angle = indication.angle {
angleBuffer.addSample(angle)
}
// calculate eta
if let lastIndication = self.lastIndication,
nOfLocationUpdates >= Constants.minNoOfLocations * 2 {
indication.eta = calculateETA(indication, lastIndication: lastIndication)
}
// send indication.
// if we are in relaxed more, last indication was good,
// or if last good indication was sent too long ago
if relaxedMode ||
indication.fuzzyAccuracy == .good ||
lastGoodIndicationDate.addingTimeInterval(Constants.goodAccuracyDuration) < location.timestamp {
masterDelegate.locationMaster?(provideIndication: indication)
lastIndication = indication
// send notification if that's appropriate
NotificationHelper.sendNotificationsIfNeeded(indication, self.destination)
}
if indication.fuzzyAccuracy == .good {
lastGoodIndicationDate = location.timestamp
}
// if we have been asked to enter relaxed mode, check if accuracy needs to be changed
if relaxedModeEngaged != nil {
assessAccuracy()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
os_log("Failed to retrieve location: %@", type: .error, error.localizedDescription)
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
guard isRunning, !signalLost, newHeading.trueHeading >= 0, let masterDelegate = self.masterDelegate else {
return
}
masterDelegate.locationMaster?(headingUpdated: newHeading.trueHeading)
}
}
| 36.590909 | 191 | 0.632469 |
0823466b42bac30e086b44d9bc080d1237cb14f6 | 5,965 | //
// ValueMappingForSetField.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-09.
// Copyright © 2015–2017 Károly Lőrentey.
//
extension ObservableValueType {
public func map<Field: ObservableSetType>(_ key: @escaping (Value) -> Field) -> AnyObservableSet<Field.Element> {
return ValueMappingForSetField<Self, Field>(parent: self, key: key).anyObservableSet
}
public func map<Field: UpdatableSetType>(_ key: @escaping (Value) -> Field) -> AnyUpdatableSet<Field.Element> {
return ValueMappingForUpdatableSetField<Self, Field>(parent: self, key: key).anyUpdatableSet
}
}
private final class UpdateSourceForSetField<Parent: ObservableValueType, Field: ObservableSetType>: TransactionalSource<SetChange<Field.Element>> {
typealias Element = Field.Element
typealias Change = SetChange<Element>
typealias Value = Update<Change>
private struct ParentSink: OwnedSink {
typealias Owner = UpdateSourceForSetField
unowned let owner: Owner
let identifier = 1
func receive(_ update: ValueUpdate<Parent.Value>) {
owner.applyParentUpdate(update)
}
}
private struct FieldSink: OwnedSink {
typealias Owner = UpdateSourceForSetField
unowned let owner: Owner
let identifier = 2
func receive(_ update: SetUpdate<Field.Element>) {
owner.applyFieldUpdate(update)
}
}
let parent: Parent
let key: (Parent.Value) -> Field
private var _field: Field? = nil
init(parent: Parent, key: @escaping (Parent.Value) -> Field) {
self.parent = parent
self.key = key
}
fileprivate var field: Field {
if let field = self._field { return field }
return key(parent.value)
}
override func activate() {
let field = key(parent.value)
field.add(FieldSink(owner: self))
parent.add(ParentSink(owner: self))
_field = field
}
override func deactivate() {
parent.remove(ParentSink(owner: self))
_field!.remove(FieldSink(owner: self))
_field = nil
}
private func subscribe(to field: Field) {
_field!.remove(FieldSink(owner: self))
_field = field
field.add(FieldSink(owner: self))
}
func applyParentUpdate(_ update: ValueUpdate<Parent.Value>) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
let oldValue = self._field!.value
let field = self.key(change.new)
self.subscribe(to: field)
sendChange(SetChange(removed: oldValue, inserted: field.value))
case .endTransaction:
endTransaction()
}
}
func applyFieldUpdate(_ update: SetUpdate<Field.Element>) {
send(update)
}
}
private final class ValueMappingForSetField<Parent: ObservableValueType, Field: ObservableSetType>: _AbstractObservableSet<Field.Element> {
typealias Element = Field.Element
private let updateSource: UpdateSourceForSetField<Parent, Field>
init(parent: Parent, key: @escaping (Parent.Value) -> Field) {
self.updateSource = .init(parent: parent, key: key)
}
var field: Field { return updateSource.field }
override var isBuffered: Bool { return field.isBuffered }
override var count: Int { return field.count }
override var value: Set<Element> { return field.value }
override func contains(_ member: Element) -> Bool { return field.contains(member) }
override func isSubset(of other: Set<Element>) -> Bool { return field.isSubset(of: other) }
override func isSuperset(of other: Set<Element>) -> Bool { return field.isSuperset(of: other) }
override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> {
updateSource.add(sink)
}
@discardableResult
override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> {
return updateSource.remove(sink)
}
}
private final class ValueMappingForUpdatableSetField<Parent: ObservableValueType, Field: UpdatableSetType>: _AbstractUpdatableSet<Field.Element> {
typealias Element = Field.Element
private let updateSource: UpdateSourceForSetField<Parent, Field>
init(parent: Parent, key: @escaping (Parent.Value) -> Field) {
self.updateSource = .init(parent: parent, key: key)
}
var field: Field { return updateSource.field }
override var isBuffered: Bool { return field.isBuffered }
override var count: Int { return field.count }
override var value: Set<Element> {
get { return field.value }
set { field.value = newValue }
}
override func contains(_ member: Element) -> Bool { return field.contains(member) }
override func isSubset(of other: Set<Element>) -> Bool { return field.isSubset(of: other) }
override func isSuperset(of other: Set<Element>) -> Bool { return field.isSuperset(of: other) }
override func apply(_ update: SetUpdate<Element>) { field.apply(update) }
override func remove(_ member: Element) { field.remove(member) }
override func insert(_ member: Element) { field.insert(member) }
override func removeAll() { field.removeAll() }
override func formUnion(_ other: Set<Field.Element>) { field.formUnion(other) }
override func formIntersection(_ other: Set<Field.Element>) { field.formIntersection(other) }
override func formSymmetricDifference(_ other: Set<Field.Element>) { field.formSymmetricDifference(other) }
override func subtract(_ other: Set<Field.Element>) { field.subtract(other) }
final override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> {
updateSource.add(sink)
}
@discardableResult
final override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> {
return updateSource.remove(sink)
}
}
| 35.505952 | 147 | 0.674267 |
de91d83fbdb30265cfbc27d00db077af64d98565 | 899 | //
// drizzleTests.swift
// drizzleTests
//
// Created by Xcode Nerd on 9/23/14.
// Copyright (c) 2014 Dulio Denis. All rights reserved.
//
import UIKit
import XCTest
class drizzleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
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.
}
}
}
| 24.297297 | 111 | 0.612903 |
9b963a88a1a212441fc8dde4e21d5473c46c5981 | 808 | //
// CreateMock.swift
// Cuckoo
//
// Created by Tadeas Kriz on 7/6/18.
//
import Foundation
public func createMock<MOCKED: Mocked>(for mockedType: MOCKED.Type, configuration: (MockBuilder, MOCKED.MockType.Stubbing) -> MOCKED.MockType) -> MOCKED.MockType {
return createMock(MOCKED.MockType.self, configuration: configuration)
}
public func createMock<MOCK: Mock>(_ mockType: MOCK.Type, configuration: (MockBuilder, MOCK.Stubbing) -> MOCK) -> MOCK {
let manager = MockManager(hasParent: MOCK.cuckoo_hasSuperclass)
MockManager.preconfiguredManagerThreadLocal.value = manager
defer { MockManager.preconfiguredManagerThreadLocal.delete() }
let builder = MockBuilder(manager: manager)
let stubbing = MOCK.Stubbing(manager: manager)
return configuration(builder, stubbing)
}
| 32.32 | 163 | 0.751238 |
f494a076c587a915d07370d89a3d8960cfab45a7 | 510 | //
// LevelThreeViewController.swift
// Debugging
//
// Created by Akhil Agrawal on 3/9/17.
// Copyright © 2017 Akhil Agrawal. All rights reserved.
//
import UIKit
// View that doesn't respond to taps
class LevelThreeViewController: GameLevelViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent;
}
}
| 22.173913 | 61 | 0.703922 |
899de43cba8bc6495679b64c84502bdd8c975088 | 7,297 | //
// BarChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// Chart that draws bars.
open class BarChartView: BarLineChartViewBase, BarChartDataProvider
{
/// if set to true, all values are drawn above their bars, instead of below their top
private var _drawValueAboveBarEnabled = true
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
private var _drawBarShadowEnabled = false
/// if set to true, a rounded rectangle with the corners is drawn on each bar
private var _drawRoundedBarEnabled = false
internal override func initialize()
{
super.initialize()
renderer = BarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
self.highlighter = BarHighlighter(chart: self)
self.xAxis.spaceMin = 0.5
self.xAxis.spaceMax = 0.5
}
internal override func calcMinMax()
{
guard let data = self.data as? BarChartData
else { return }
if fitBars
{
_xAxis.calculate(
min: data.xMin - data.barWidth / 2.0,
max: data.xMax + data.barWidth / 2.0)
}
else
{
_xAxis.calculate(min: data.xMin, max: data.xMax)
}
// calculate axis range (min / max) according to provided data
leftAxis.calculate(
min: data.getYMin(axis: .left),
max: data.getYMax(axis: .left))
rightAxis.calculate(
min: data.getYMin(axis: .right),
max: data.getYMax(axis: .right))
}
/// - Returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart.
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight?
{
if _data === nil
{
Swift.print("Can't select by touch. No data set.")
return nil
}
guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y)
else { return nil }
if !isHighlightFullBarEnabled { return h }
// For isHighlightFullBarEnabled, remove stackIndex
return Highlight(
x: h.x, y: h.y,
xPx: h.xPx, yPx: h.yPx,
dataIndex: h.dataIndex,
dataSetIndex: h.dataSetIndex,
stackIndex: -1,
axis: h.axis)
}
/// - Returns: The bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data.
@objc open func getBarBounds(entry e: BarChartDataEntry) -> CGRect
{
guard let
data = _data as? BarChartData,
let set = data.getDataSetForEntry(e) as? IBarChartDataSet
else { return CGRect.null }
let y = e.y
let x = e.x
let barWidth = data.barWidth
let left = x - barWidth / 2.0
let right = x + barWidth / 2.0
let top = y >= 0.0 ? y : 0.0
let bottom = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(forAxis: set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
/// Groups all BarDataSet objects this data object holds together by modifying the x-value of their entries.
/// Previously set x-values of entries will be overwritten. Leaves space between bars and groups as specified by the parameters.
/// Calls `notifyDataSetChanged()` afterwards.
///
/// - Parameters:
/// - fromX: the starting point on the x-axis where the grouping should begin
/// - groupSpace: the space between groups of bars in values (not pixels) e.g. 0.8f for bar width 1f
/// - barSpace: the space between individual bars in values (not pixels) e.g. 0.1f for bar width 1f
@objc open func groupBars(fromX: Double, groupSpace: Double, barSpace: Double)
{
guard let barData = self.barData
else
{
Swift.print("You need to set data for the chart before grouping bars.", terminator: "\n")
return
}
barData.groupBars(fromX: fromX, groupSpace: groupSpace, barSpace: barSpace)
notifyDataSetChanged()
}
/// Highlights the value at the given x-value in the given DataSet. Provide -1 as the dataSetIndex to undo all highlighting.
///
/// - Parameters:
/// - x:
/// - dataSetIndex:
/// - stackIndex: the index inside the stack - only relevant for stacked entries
@objc open func highlightValue(x: Double, dataSetIndex: Int, stackIndex: Int)
{
highlightValue(Highlight(x: x, dataSetIndex: dataSetIndex, stackIndex: stackIndex))
}
// MARK: Accessors
/// if set to true, all values are drawn above their bars, instead of below their top
@objc open var drawValueAboveBarEnabled: Bool
{
get { return _drawValueAboveBarEnabled }
set
{
_drawValueAboveBarEnabled = newValue
setNeedsDisplay()
}
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
@objc open var drawBarShadowEnabled: Bool
{
get { return _drawBarShadowEnabled }
set
{
_drawBarShadowEnabled = newValue
setNeedsDisplay()
}
}
/// if set to true, a rounded rectangle is drawn on each bar
open var drawRoundedBarEnabled: Bool {
get { return _drawRoundedBarEnabled }
set {
_drawRoundedBarEnabled = newValue
setNeedsDisplay()
}
}
/// Adds half of the bar width to each side of the x-axis range in order to allow the bars of the barchart to be fully displayed.
/// **default**: false
@objc open var fitBars = false
/// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values (relevant only for stacked).
/// If enabled, highlighting operations will highlight the whole bar, even if only a single stack entry was tapped.
@objc open var highlightFullBarEnabled: Bool = false
/// `true` the highlight is be full-bar oriented, `false` ifsingle-value
open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled }
// MARK: - BarChartDataProvider
open var barData: BarChartData? { return _data as? BarChartData }
/// `true` if drawing values above bars is enabled, `false` ifnot
open var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled }
/// `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot
open var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled }
/// - returns: `true` if drawing rounded bars is enabled, `false` if not
open var isDrawRoundedBarEnabled: Bool { return drawRoundedBarEnabled }
}
| 36.123762 | 149 | 0.619707 |
614a14e020744ea901b04a1676cd0ee445ffca15 | 543 | //
// AQLabel.swift
// TestingGitLink
//
// Created by Akash Yashavanthrao Shindhe on 17/01/21.
//
import SwiftUI
struct AQLabel: View {
var body: some View {
Form {
SectionView(title: "Label", description: "A standard label for user interface items, consisting of an icon with a title.") {
VStack {
Label(text: "Label")
}
}
}
}
}
struct AQLabel_Previews: PreviewProvider {
static var previews: some View {
AQLabel()
}
}
| 20.111111 | 136 | 0.554328 |
f46c8952e13e4eb39f0f7ea7d6bf5b00357c651f | 887 | //
// TypeHolderExample.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct TypeHolderExample: Codable {
public var stringItem: String
public var numberItem: Double
public var integerItem: Int
public var boolItem: Bool
public var arrayItem: [Int]
public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) {
self.stringItem = stringItem
self.numberItem = numberItem
self.integerItem = integerItem
self.boolItem = boolItem
self.arrayItem = arrayItem
}
public enum CodingKeys: String, CodingKey {
case stringItem = "string_item"
case numberItem = "number_item"
case integerItem = "integer_item"
case boolItem = "bool_item"
case arrayItem = "array_item"
}
}
| 22.74359 | 109 | 0.668546 |
2247b5082ed3f94b23000e3db51086605a623639 | 1,748 |
import UIKit
import WebKit
import SwiftUI
import SnapKit
class HttpInterceptWebMenuViewController: UIViewController {
var arrData = [("B站","https://www.bilibili.com/"),("网易","https://www.163.com"),("sohu","https://www.sohu.com/"),("the verge","https://www.theverge.com/"),("鱼塘","https://mo.fish/?class_id=%E5%85%A8%E9%83%A8&hot_id=2")]
var tbMenu = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
tbMenu.dataSource = self
tbMenu.delegate = self
tbMenu.dataSource = self
tbMenu.delegate = self
tbMenu.tableFooterView = UIView()
view.addSubview(tbMenu)
tbMenu.snp.makeConstraints { (m) in
m.edges.equalTo(0)
}
}
}
extension HttpInterceptWebMenuViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil{
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell?.textLabel?.text = arrData[indexPath.row].0
cell?.detailTextLabel?.text = arrData[indexPath.row].1
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let vc = CacheWebViewController(urlString: arrData[indexPath.row].1)
navigationController?.pushViewController(vc, animated: true)
}
}
| 36.416667 | 221 | 0.662471 |
dbce0ec9dab66aa08a192bfcad179cf0fc3221f0 | 1,633 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/comments.framework/Modules/comments.swiftmodule)
// RUN: %empty-directory(%t/comments.framework/Modules/comments.swiftmodule/Project)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.framework/Modules/comments.swiftmodule/%target-swiftmodule-name -emit-module-doc-path %t/comments.framework/Modules/comments.swiftmodule/%target-swiftdoc-name -emit-module-source-info-path %t/comments.framework/Modules/comments.swiftmodule/Project/%target-swiftsourceinfo-name %s
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -F %t | %FileCheck %s
// RUN: cp -r %t/comments.framework/Modules/comments.swiftmodule %t/comments.swiftmodule
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t | %FileCheck %s
/// first_decl_class_1 Aaa.
public class first_decl_class_1 {
/// decl_func_1 Aaa.
public func decl_func_1() {}
/**
* decl_func_3 Aaa.
*/
public func decl_func_2() {}
/// decl_func_3 Aaa.
/** Bbb. */
public func decl_func_3() {}
}
// CHECK: comments-framework.swift:12:14: Class/first_decl_class_1 RawComment=[/// first_decl_class_1 Aaa.\n]
// CHECK: comments-framework.swift:15:15: Func/first_decl_class_1.decl_func_1 RawComment=[/// decl_func_1 Aaa.\n]
// CHECK: comments-framework.swift:20:15: Func/first_decl_class_1.decl_func_2 RawComment=[/**\n * decl_func_3 Aaa.\n */]
// CHECK: comments-framework.swift:24:15: Func/first_decl_class_1.decl_func_3 RawComment=[/// decl_func_3 Aaa.\n/** Bbb. */]
| 51.03125 | 375 | 0.745254 |
08f422a10ed7b8deb86c69fc9f21b096a52c41e3 | 315 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A {
let a : b: P {
return """[1]]
protocol c : b> {
return "[1)
var b = c
let a {
}
if true {
func b: B<T where T : d {
}
}
func b<T : b :
| 17.5 | 87 | 0.647619 |
56370755c27c942addbd71cf9bf0810232421533 | 1,094 | //
// BundleExtension.swift
// Codename Shout
//
// Created by Marquis Kurt on 7/3/22.
//
// This file is part of Codename Shout.
//
// Codename Shout is non-violent software: you can use, redistribute, and/or modify it under the terms of the CNPLv7+
// as found in the LICENSE file in the source code root directory or at <https://git.pixie.town/thufie/npl-builder>.
//
// Codename Shout comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. See the CNPL for
// details.
import Foundation
extension Bundle {
/// Returns the version and build number of the app in the format "Version (Build)".
/// - Note: If `CFBundleShortVersionString` and/or `CFBundloeVersion` are not found, their values will be replaced
/// with `0`.
func getAppVersion() -> String {
guard let info = infoDictionary else {
return "0 (0.0)"
}
let appVersion = info["CFBundleShortVersionString"] as? String ?? "0.0"
let appBuild = info["CFBundleVersion"] as? String ?? "0"
return "\(appVersion) (\(appBuild))"
}
}
| 36.466667 | 118 | 0.666362 |
c123e0a64bd11b025c50db9f22e58f35e40f41b5 | 1,828 | import Foundation
import Utilities
let data = try readLines(forDay: 3).map { Array($0).map { Int(String($0))! } }
let bitCount = data[0].count
func findMostCommonBit(in data: [[Int]], at idx: Int) -> Int {
var zeroCount = 0
var oneCount = 0
for line in data {
switch line[idx] {
case 0:
zeroCount += 1
case 1:
oneCount += 1
default:
fatalError("Invalid bit: \(line[idx])")
}
}
return zeroCount > oneCount ? 0 : 1
}
func findLeastCommonBit(in data: [[Int]], at idx: Int) -> Int {
findMostCommonBit(in: data, at: idx) == 0 ? 1 : 0
}
func bitsToInt(_ bits: [Int]) -> Int {
bits.enumerated().map { idx, bit in
bit * Int(pow(2, Double(bitCount - 1 - idx)))
}.reduce(0, +)
}
let gammaBits = (0..<bitCount).map { findMostCommonBit(in: data, at: $0) }
let epsilonBits = (0..<bitCount).map { findLeastCommonBit(in: data, at: $0) }
let gammaValue = bitsToInt(gammaBits)
let epsilonValue = bitsToInt(epsilonBits)
let part1 = gammaValue * epsilonValue
print("Part 1: \(part1)")
var oxygenCandidates = data
var oxygenGeneratorRating: Int!
for i in 0..<bitCount {
let mostCommonBit = findMostCommonBit(in: oxygenCandidates, at: i)
oxygenCandidates = oxygenCandidates.filter { $0[i] == mostCommonBit }
if oxygenCandidates.count == 1 {
oxygenGeneratorRating = bitsToInt(oxygenCandidates[0])
break
}
}
var co2Candidates = data
var co2Rating: Int!
for i in 0..<bitCount {
let leastCommonBit = findLeastCommonBit(in: co2Candidates, at: i)
co2Candidates = co2Candidates.filter { $0[i] == leastCommonBit }
if co2Candidates.count == 1 {
co2Rating = bitsToInt(co2Candidates[0])
break
}
}
let part2 = oxygenGeneratorRating * co2Rating
print("Part 2: \(part2)")
| 27.283582 | 78 | 0.63512 |
6ae87e2b39fa864c5b5f6eef645602a4d0b1130c | 566 | import UIKit
extension UIButton {
func setIcon(_ image: UIImage?, color: UIColor) {
self.setImage(image?.template(), for: .normal)
self.imageView?.contentMode = .scaleAspectFit
self.imageView?.tintColor = color
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 0)
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 4)
}
func configureAccessibilityLabel(label: String, hint: String? = nil) {
accessibilityLabel = label
accessibilityHint = hint
}
}
| 33.294118 | 81 | 0.650177 |
1d2b4608a850d38b7a54a4a3ec519a349562e0f0 | 541 | //
// AccountInfoEndpoint.swift
// settlepay-ios-sdk
//
// Created by Yelyzaveta Kartseva on 28.04.2021.
//
import Alamofire
import Marshal
class AccountInfoEndpoint: BaseEndpoint, APIEndpoint {
typealias ResponseType = AccountInfoResponse
var path: String {
return APIPath.accountInfo
}
}
struct AccountInfoResponse: Unmarshaling {
let result: AccountInfoResponseData
init(object: MarshaledObject) throws {
result = try AccountInfoResponseData(object: object)
}
}
| 18.033333 | 60 | 0.687616 |
dd7a5df138f6bbe53a1f0428bdfce5001649dbe9 | 1,150 |
import Foundation
extension String {
public var asJamulusUrl: URL? {
var components = URLComponents()
let vals = self.components(separatedBy: ":")
guard vals.count > 0, !vals[0].isEmpty else {
return nil
}
components.host = vals[0]
if vals.count > 1,
let port = UInt(vals[1]) {
components.port = Int(port)
} else {
components.port = Int(ApiConsts.defaultPort)
}
return components.url
}
/// Attempts to parse a date from a jamulus chat message
public var chatDate: Date? {
if let found = dateFormatter.date(from: self) {
let bits = Calendar.current
.dateComponents([.hour, .minute,.second], from: found)
return Calendar.current.date(
bySettingHour: bits.hour!, minute: bits.minute!, second: bits.second!,
of: Date(),
matchingPolicy: .strict,repeatedTimePolicy: .first, direction: .forward
)
}
return nil
}
}
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "(hh:mm:ss aa)"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}
| 25 | 79 | 0.635652 |
5be5ba9f06f803a9dfec4302ac8a1cdbc652ff2f | 1,525 | //
// PopoverPresentationController.swift
// SwiftWeiBo
//
// Created by Imanol on 2/24/16.
// Copyright © 2016 imanol. All rights reserved.
//
import UIKit
@available(iOS 8.0, *)
class PopoverPresentationController: UIPresentationController {
var presentFrame = CGRectZero
override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
}
//即将转场时调用
override func containerViewWillLayoutSubviews() {
//1 修改被展示的视图
// containerView; // 容器视图
// presentedView() // 被展现的视图
if presentFrame == CGRectZero{
presentedView()?.frame = CGRect(x: 100, y: 56, width: 200, height: 200)
}else
{
presentedView()?.frame = presentFrame
}
//在容器下面添加一个蒙版
containerView?.insertSubview(coverView, atIndex: 0)
}
//MARK: - LAZY LOADING
private lazy var coverView:UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.0, alpha: 0.2)
view.frame = UIScreen.mainScreen().bounds
//添加监听事件
let tap = UITapGestureRecognizer(target: self, action: "close")
view.addGestureRecognizer(tap)
return view
}()
func close(){
presentedViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| 28.240741 | 120 | 0.628852 |
87b9e5f08e7af0128ef4260953b79c272b486a57 | 1,019 | //
// IntersectionOfTwoArraysIITests.swift
// CodingChallengesTests
//
// Created by William Boles on 20/11/2021.
// Copyright © 2021 Boles. All rights reserved.
//
import XCTest
@testable import LeetCode
class IntersectionOfTwoArraysIITests: XCTestCase {
// MARK: - Tests
func test_A() {
let nums1 = [1, 2, 2, 1]
let nums2 = [2, 2]
let intersectingValues = IntersectionOfTwoArraysII.intersect(nums1, nums2)
XCTAssertEqual(intersectingValues, [2,2])
}
func test_B() {
let nums1 = [4, 9, 5]
let nums2 = [9, 4, 9, 8, 4]
let intersectingValues = IntersectionOfTwoArraysII.intersect(nums1, nums2)
XCTAssertEqual(intersectingValues, [4, 9])
}
func test_C() {
let nums1 = [1, 2, 2, 1]
let nums2 = [2]
let intersectingValues = IntersectionOfTwoArraysII.intersect(nums1, nums2)
XCTAssertEqual(intersectingValues, [2])
}
}
| 23.159091 | 82 | 0.591757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.