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
|
---|---|---|---|---|---|
fb6243e477b07ff71490435da8ff889ed5165648 | 1,379 | //
// AutocompleteParser.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Core
class AutocompleteParser {
func convert(fromJsonData data: Data) throws -> [Suggestion] {
guard let json = try? JSONSerialization.jsonObject(with: data) else {
throw JsonError.invalidJson
}
guard let jsonArray = json as? [[String: String]] else {
throw JsonError.typeMismatch
}
var suggestions = [Suggestion]()
for element in jsonArray {
if let type = element.keys.first, let suggestion = element[type] {
suggestions.append(Suggestion(type: type, suggestion: suggestion))
}
}
return suggestions
}
}
| 29.978261 | 82 | 0.649021 |
6739dce665d136a8f64260b5360483c5838f3b2b | 2,498 | //
// ChargeAlertViewController.swift
// PeasNovel
//
// Created by lieon on 2019/5/10.
// Copyright © 2019 NotBroken. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class ChargeAlertViewController: BaseViewController {
@IBOutlet weak var adBtn: UIButton!
@IBOutlet weak var coverBtn: UIButton!
@IBOutlet weak var vipBtn: UIButton!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var closeBtn: UIButton!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
convenience init(_ viewModel: ChargeAlertViewModel) {
self.init()
self.rx
.viewDidLoad
.subscribe(onNext: { [weak self] in
self?.config(viewModel)
})
.disposed(by: bag)
self.rx
.viewDidLoad
.bind(to: viewModel.viewDidLoad)
.disposed(by: bag)
}
private func config(_ viewModel: ChargeAlertViewModel) {
vipBtn.setTitle(CommomData.share.switcherConfig.value?.buy_vip ?? false ? "0元免广告阅读": "购买VIP会员免广告" , for: .normal)
vipBtn.rx.tap.map { ChargeViewModel()}
.subscribe(onNext: {[weak self] in
self?.navigationController?.pushViewController(ChargeViewController($0), animated: true)
})
.disposed(by: bag )
coverBtn.rx.tap.mapToVoid()
.subscribe(onNext: {[weak self] in
self?.dismiss(animated: true, completion: nil)
})
.disposed(by: bag )
closeBtn.rx.tap.mapToVoid()
.subscribe(onNext: {[weak self] in
self?.dismiss(animated: true, completion: nil)
})
.disposed(by: bag )
adBtn.rx.tap.map { AdvertiseService.advertiseConfig(.readerRewardVideoAd)}
.unwrap()
.filter { !$0.is_close }
.mapToVoid()
.subscribe(onNext: { [weak self] in
self?.dismiss(animated: false, completion: {
NotificationCenter.default.post(name: NSNotification.Name.Event.dismissAdChapter, object: nil)
NotificationCenter.default.post(name: NSNotification.Name.Advertise.presentRewardVideoAd, object: nil)
})
})
.disposed(by:self.bag )
}
}
| 32.025641 | 122 | 0.582866 |
ede9144f5c7daa12702815fc481a119a22895c24 | 89 | //
// TSTag.swift
// Pods
//
// Created by 斉藤 祐輔 on 2019/03/20.
//
import Foundation
| 9.888889 | 35 | 0.595506 |
1413bcb6bd5dd3ed4e3698290b7bd867edabb8d8 | 901 | //
// PlayingCardDeck.swift
// PlayingCard
//
// Created by Nick on 2019/6/7.
// Copyright © 2019 Nick. All rights reserved.
//
import Foundation
struct PlayingCardDeck {
private (set) var cards = [PlayingCard]()
init() {
for suit in PlayingCard.Suit.all {
for rank in PlayingCard.Rank.allRank {
cards.append(PlayingCard(suit: suit, rank: rank))
}
}
}
mutating func draw() -> PlayingCard? {
if cards.count > 0 {
return cards.remove(at: cards.count.arc4rancom)
} else {
return nil
}
}
}
extension Int {
var arc4rancom: Int {
if self > 0 {
return Int(arc4random_uniform(UInt32(self)))
} else if self < 0 {
return -Int(arc4random_uniform(UInt32(self)))
} else {
return 0
}
}
}
| 20.477273 | 65 | 0.527192 |
76ea4bf45eaf5e77471da10738ea10678a12f1c7 | 14,723 | //
// Formatter.swift
// SwiftFormat
//
// Version 0.35.5
//
// Created by Nick Lockwood on 12/08/2016.
// Copyright 2016 Nick Lockwood
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/nicklockwood/SwiftFormat
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// This is a utility class used for manipulating a tokenized source file.
/// It doesn't actually contain any logic for formatting, but provides
/// utility methods for enumerating and adding/removing/replacing tokens.
/// The primary advantage it provides over operating on the token array
/// directly is that it allows mutation during enumeration, and
/// transparently handles changes that affect the current token index.
public class Formatter: NSObject {
private var enumerationIndex = -1
private var disabledCount = 0
private var disabledNext = 0
private var wasNextDirective = false
// Current rule, used for handling comment directives
var currentRule: String? {
didSet {
disabledCount = 0
disabledNext = 0
}
}
// Is current rule enabled
var isEnabled: Bool { return disabledCount + disabledNext <= 0 }
// Process a comment token (which may contain directives)
func processCommentBody(_ comment: String) {
let prefix = "swiftformat:"
guard let rule = currentRule, comment.hasPrefix(prefix),
let directive = ["disable", "enable"].first(where: { comment.hasPrefix("\(prefix)\($0)") }),
comment.range(of: "\\b(\(rule)|all)\\b", options: .regularExpression) != nil else {
return
}
wasNextDirective = comment.hasPrefix("\(prefix)\(directive):next")
switch directive {
case "disable":
if wasNextDirective {
disabledNext = 1
} else {
disabledCount += 1
}
case "enable":
if wasNextDirective {
disabledNext = -1
} else {
disabledCount -= 1
}
default:
preconditionFailure()
}
}
/// Process a linebreak (used to cancel disable/enable:next directive)
func processLinebreak() {
if wasNextDirective {
wasNextDirective = false
} else if disabledNext != 0 {
disabledNext = 0
}
}
/// The options that the formatter was initialized with
public let options: FormatOptions
/// The token array managed by the formatter (read-only)
public private(set) var tokens: [Token]
/// Create a new formatter instance from a token array
public init(_ tokens: [Token], options: FormatOptions = FormatOptions()) {
self.tokens = tokens
self.options = options
}
// MARK: access and mutation
/// Returns the token at the specified index, or nil if index is invalid
public func token(at index: Int) -> Token? {
guard index >= 0 && index < tokens.count else { return nil }
return tokens[index]
}
/// Replaces the token at the specified index with one or more new tokens
public func replaceToken(at index: Int, with tokens: Token...) {
if tokens.count == 0 {
removeToken(at: index)
} else {
self.tokens[index] = tokens[0]
for (i, token) in tokens.dropFirst().enumerated() {
insertToken(token, at: index + i + 1)
}
}
}
/// Replaces the tokens in the specified range with new tokens
public func replaceTokens(inRange range: Range<Int>, with tokens: [Token]) {
let max = min(range.count, tokens.count)
for i in 0 ..< max {
self.tokens[range.lowerBound + i] = tokens[i]
}
if range.count > max {
for _ in max ..< range.count {
removeToken(at: range.lowerBound + max)
}
} else {
for i in max ..< tokens.count {
insertToken(tokens[i], at: range.lowerBound + i)
}
}
}
/// Replaces the tokens in the specified closed range with new tokens
public func replaceTokens(inRange range: ClosedRange<Int>, with tokens: [Token]) {
replaceTokens(inRange: range.lowerBound ..< range.upperBound + 1, with: tokens)
}
/// Removes the token at the specified index
public func removeToken(at index: Int) {
tokens.remove(at: index)
if enumerationIndex >= index {
enumerationIndex -= 1
}
}
/// Removes the tokens in the specified range
public func removeTokens(inRange range: Range<Int>) {
replaceTokens(inRange: range, with: [])
}
/// Removes the tokens in the specified closed range
public func removeTokens(inRange range: ClosedRange<Int>) {
replaceTokens(inRange: range, with: [])
}
/// Removes the last token
public func removeLastToken() {
tokens.removeLast()
}
/// Inserts an array of tokens at the specified index
public func insertTokens(_ tokens: [Token], at index: Int) {
for token in tokens.reversed() {
self.tokens.insert(token, at: index)
}
if enumerationIndex >= index {
enumerationIndex += tokens.count
}
}
/// Inserts a single token at the specified index
public func insertToken(_ token: Token, at index: Int) {
insertTokens([token], at: index)
}
// MARK: enumeration
/// Loops through each token in the array. It is safe to mutate the token
/// array inside the body block, but note that the index and token arguments
/// may not reflect the current token any more after a mutation
public func forEachToken(_ body: (Int, Token) -> Void) {
assert(enumerationIndex == -1, "forEachToken does not support re-entrancy")
enumerationIndex = 0
while enumerationIndex < tokens.count {
let token = tokens[enumerationIndex]
switch token {
case let .commentBody(comment):
processCommentBody(comment)
case .linebreak:
processLinebreak()
default:
break
}
if isEnabled {
body(enumerationIndex, token) // May mutate enumerationIndex
}
enumerationIndex += 1
}
enumerationIndex = -1
}
/// As above, but only loops through tokens that match the specified filter block
public func forEachToken(where matching: (Token) -> Bool, _ body: (Int, Token) -> Void) {
forEachToken { index, token in
if matching(token) {
body(index, token)
}
}
}
/// As above, but only loops through tokens with the specified type and string
public func forEach(_ token: Token, _ body: (Int, Token) -> Void) {
forEachToken(where: { $0 == token }, body)
}
/// As above, but only loops through tokens with the specified type and string
public func forEach(_ type: TokenType, _ body: (Int, Token) -> Void) {
forEachToken(where: { $0.is(type) }, body)
}
// MARK: utilities
/// Returns the index of the next token at the current scope that matches the block
public func index(after index: Int, where matches: (Token) -> Bool) -> Int? {
guard index < tokens.count else { return nil }
var scopeStack: [Token] = []
for i in index + 1 ..< tokens.count {
let token = tokens[i]
if let scope = scopeStack.last, token.isEndOfScope(scope) {
scopeStack.removeLast()
if case .linebreak = token, scopeStack.count == 0, matches(token) {
return i
}
} else if scopeStack.count == 0 && matches(token) {
return i
} else if token.isEndOfScope {
return nil
} else if case .startOfScope = token {
scopeStack.append(token)
}
}
return nil
}
/// Returns the index of the next matching token at the current scope
public func index(of token: Token, after index: Int) -> Int? {
return self.index(after: index, where: { $0 == token })
}
/// Returns the index of the next token at the current scope of the specified type
public func index(of type: TokenType, after index: Int, if matches: (Token) -> Bool = { _ in true }) -> Int? {
return self.index(after: index, where: { $0.is(type) }).flatMap { matches(tokens[$0]) ? $0 : nil }
}
/// Returns the next token at the current scope that matches the block
public func nextToken(after index: Int, where matches: (Token) -> Bool = { _ in true }) -> Token? {
return self.index(after: index, where: matches).map { tokens[$0] }
}
/// Returns the next token at the current scope of the specified type
public func next(_ type: TokenType, after index: Int, if matches: (Token) -> Bool = { _ in true }) -> Token? {
return self.index(of: type, after: index, if: matches).map { tokens[$0] }
}
/// Returns the index of the previous token at the current scope that matches the block
public func index(before index: Int, where matches: (Token) -> Bool) -> Int? {
guard index > 0 else { return nil }
var linebreakEncountered = false
var scopeStack: [Token] = []
for i in (0 ..< index).reversed() {
let token = tokens[i]
if case .startOfScope = token {
if let scope = scopeStack.last, scope.isEndOfScope(token) {
scopeStack.removeLast()
} else if token.string == "//", linebreakEncountered {
linebreakEncountered = false
} else if matches(token) {
return i
} else if token.string == "//", self.token(at: index)?.isLinebreak == true {
continue
} else {
return nil
}
} else if scopeStack.count == 0 && matches(token) {
return i
} else if case .linebreak = token {
linebreakEncountered = true
} else if case .endOfScope = token {
scopeStack.append(token)
}
}
return nil
}
/// Returns the index of the previous matching token at the current scope
public func index(of token: Token, before index: Int) -> Int? {
return self.index(before: index, where: { $0 == token })
}
/// Returns the index of the previous token at the current scope of the specified type
public func index(of type: TokenType, before index: Int, if matches: (Token) -> Bool = { _ in true }) -> Int? {
return self.index(before: index, where: { $0.is(type) }).flatMap { matches(tokens[$0]) ? $0 : nil }
}
/// Returns the previous token at the current scope that matches the block
public func lastToken(before index: Int, where matches: (Token) -> Bool) -> Token? {
return self.index(before: index, where: matches).map { tokens[$0] }
}
/// Returns the previous token at the current scope of the specified type
public func last(_ type: TokenType, before index: Int, if matches: (Token) -> Bool = { _ in true }) -> Token? {
return self.index(of: type, before: index, if: matches).map { tokens[$0] }
}
/// Returns the starting token for the containing scope at the specified index
public func currentScope(at index: Int) -> Token? {
return last(.startOfScope, before: index)
}
/// Returns the index of the ending token for the current scope
public func endOfScope(at index: Int) -> Int? {
let startIndex: Int
guard var startToken = token(at: index) else { return nil }
if case .startOfScope = startToken {
startIndex = index
} else if let index = self.index(of: .startOfScope, before: index) {
startToken = tokens[index]
startIndex = index
} else {
return nil
}
return self.index(after: startIndex) {
$0.isEndOfScope(startToken)
}
}
/// Returns the index of the first token of the line containing the specified index
public func startOfLine(at index: Int) -> Int {
var index = index
while let token = token(at: index - 1) {
if case .linebreak = token {
break
}
index -= 1
}
return index
}
/// Returns the space at the start of the line containing the specified index
public func indentForLine(at index: Int) -> String {
if let token = token(at: startOfLine(at: index)), case let .space(string) = token {
return string
}
return ""
}
/// Either modifies or removes the existing space token at the specified
/// index, or inserts a new one if there is not already a space token present.
/// Returns the number of tokens inserted or removed
@discardableResult func insertSpace(_ space: String, at index: Int) -> Int {
if token(at: index)?.isSpace == true {
if space.isEmpty {
removeToken(at: index)
return -1 // Removed 1 token
}
replaceToken(at: index, with: .space(space))
} else if !space.isEmpty {
insertToken(.space(space), at: index)
return 1 // Inserted 1 token
}
return 0 // Inserted 0 tokens
}
}
| 38.241558 | 115 | 0.599266 |
0153e5b540332f5a2d06ef092766f42e5c9cfb83 | 1,151 | // Copyright © 2021 Yurii Lysytsia. All rights reserved.
#if canImport(Foundation)
import class Foundation.FileManager
import struct Foundation.URL
// MARK: - Extensions | Contents
public extension FileManager {
/// Returns `true` if a file or directory exists at a specified url path.
func fileExists(at url: URL) -> Bool { fileExists(atPath: url.path) }
/// Performs a shallow search of the specified directory and returns URLs for the contained items.
func contentsOfDirectory(at url: URL) throws -> (directories: [URL], files: [URL]) {
let contents = try contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
let dividedContents = contents.divided(by: { $0.hasDirectoryPath })
return (dividedContents.matched, dividedContents.nonMatched)
}
/// Performs a shallow search of the specified directory and returns URLs for the contained files with given extension only.
func contentsOfDirectory(at url: URL, withExtension ext: String) throws -> [URL] {
try contentsOfDirectory(at: url).files.filter { $0.pathExtension == ext }
}
}
#endif
| 44.269231 | 128 | 0.719374 |
2feb995c2cbe0fde81ee7136837e16efcb191a40 | 1,478 | import Foundation
public protocol TextStoringMonitor {
func willApplyMutation(_ mutation: TextMutation, to storage: TextStoring)
func didApplyMutation(_ mutation: TextMutation, to storage: TextStoring)
func willCompleteChangeProcessing(of mutation: TextMutation?, in storage: TextStoring)
func didCompleteChangeProcessing(of mutation: TextMutation?, in storage: TextStoring)
}
public extension TextStoringMonitor {
/// Invoke all the monitoring methods in order
func processMutation(_ mutation: TextMutation, in storage: TextStoring) {
willApplyMutation(mutation, to: storage)
didApplyMutation(mutation, to: storage)
willCompleteChangeProcessing(of: mutation, in: storage)
didCompleteChangeProcessing(of: mutation, in: storage)
}
/// Apply the mutation to storage, and invoke all monitoring methods
func applyMutation(_ mutation: TextMutation, to storage: TextStoring) {
willApplyMutation(mutation, to: storage)
storage.applyMutation(mutation)
didApplyMutation(mutation, to: storage)
willCompleteChangeProcessing(of: mutation, in: storage)
didCompleteChangeProcessing(of: mutation, in: storage)
}
/// Apply an array of mutations to storage, and invoke all monitoring methods
func applyMutations(_ mutations: [TextMutation], to storage: TextStoring) {
for mutation in mutations {
applyMutation(mutation, to: storage)
}
}
}
| 42.228571 | 90 | 0.730717 |
23b2a8da0f4d0cec3cb6ddfdc1c4d969a6c97e27 | 8,336 | /*
Enablement.swift
Crypt
Copyright 2015 The Crypt Project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import Security
import CoreFoundation
class Enablement: NSObject {
// Define a pointer to the MechanismRecord. This will be used to get and set
// all the inter-mechanism data. It is also used to allow or deny the login.
private var mechanism:UnsafePointer<MechanismRecord>
// This NSString will be used as the domain for the inter-mechanism context data
private let contextCryptDomain : NSString = "com.grahamgilbert.crypt"
// init the class with a MechanismRecord
init(mechanism:UnsafePointer<MechanismRecord>) {
NSLog("Crypt:MechanismInvoke:Enablement:[+] initWithMechanismRecord");
self.mechanism = mechanism
}
// This is the only public function. It will be called from the
// ObjC AuthorizationPlugin class
func run() {
guard let username = getUsername()
else { allowLogin(); return }
guard let password = getPassword()
else { allowLogin(); return }
let the_settings = NSDictionary.init(dictionary: ["Username" : username, "Password" : password])
if getBoolHintValue() {
NSLog("Attempting to Enable FileVault 2")
do {
let outputPlist = try enableFileVault(the_settings)
outputPlist.writeToFile("/private/var/root/crypt_output.plist", atomically: true)
restartMac()
}
catch let error as NSError {
NSLog("%@", error)
allowLogin()
}
} else {
NSLog("Hint value wasn't set")
// Allow to login. End of mechanism
NSLog("Crypt:MechanismInvoke:Enablement:run:[+] allowLogin");
allowLogin()
}
}
// Restart
private func restartMac() -> Bool {
// Wait a couple of seconds for everything to finish
sleep(3)
let task = NSTask();
NSLog("%@", "Restarting after enabling encryption")
task.launchPath = "/sbin/reboot"
task.launch()
return true
}
// fdesetup Errors
enum FileVaultError: ErrorType {
case FDESetupFailed(retCode: Int32)
case OutputPlistNull
case OutputPlistMalformed
}
// fdesetup wrapper
func enableFileVault(theSettings : NSDictionary) throws -> NSDictionary {
let inputPlist = try NSPropertyListSerialization.dataWithPropertyList(theSettings,
format: NSPropertyListFormat.XMLFormat_v1_0, options: 0)
let inPipe = NSPipe.init()
let outPipe = NSPipe.init()
let task = NSTask.init()
task.launchPath = "/usr/bin/fdesetup"
task.arguments = ["enable", "-outputplist", "-inputplist"]
task.standardInput = inPipe
task.standardOutput = outPipe
task.launch()
inPipe.fileHandleForWriting.writeData(inputPlist)
inPipe.fileHandleForWriting.closeFile()
task.waitUntilExit()
if task.terminationStatus != 0 {
throw FileVaultError.FDESetupFailed(retCode: task.terminationStatus)
}
let outputData = outPipe.fileHandleForReading.readDataToEndOfFile()
outPipe.fileHandleForReading.closeFile()
if outputData.length == 0 {
throw FileVaultError.OutputPlistNull
}
var format : NSPropertyListFormat = NSPropertyListFormat.XMLFormat_v1_0
let outputPlist = try NSPropertyListSerialization.propertyListWithData(outputData,
options: NSPropertyListReadOptions.Immutable, format: &format)
if (format == NSPropertyListFormat.XMLFormat_v1_0) {
return outputPlist as! NSDictionary
} else {
throw FileVaultError.OutputPlistMalformed
}
}
// This is how we get the inter-mechanism context data
private func getBoolHintValue() -> Bool {
var value : UnsafePointer<AuthorizationValue> = nil
var err: OSStatus = noErr
err = self.mechanism.memory.fPlugin.memory.fCallbacks.memory.GetHintValue(mechanism.memory.fEngine, contextCryptDomain.UTF8String, &value)
if err != errSecSuccess {
NSLog("%@","couldn't retrieve hint value")
return false
}
let outputdata = NSData.init(bytes: value.memory.data, length: value.memory.length)
guard let boolHint = NSKeyedUnarchiver.unarchiveObjectWithData(outputdata)
else {
NSLog("couldn't unpack hint value")
return false
}
return boolHint.boolValue
}
// This is how we set the inter-mechanism context data
private func setHintValue(encryptionToBeEnabled : Bool) -> Bool {
var inputdata : String
if encryptionToBeEnabled {
inputdata = "true"
} else {
inputdata = "false"
}
// Try and unwrap the optional NSData returned from archivedDataWithRootObject
// This can be decoded on the other side with unarchiveObjectWithData
guard let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(inputdata)
else {
NSLog("Crypt:MechanismInvoke:Enablement:setHintValue [+] Failed to unwrap archivedDataWithRootObject");
return false
}
// Fill the AuthorizationValue struct with our data
var value = AuthorizationValue(length: data.length,
data: UnsafeMutablePointer<Void>(data.bytes))
// Use the MechanismRecord SetHintValue callback to set the
// inter-mechanism context data
let err : OSStatus = self.mechanism.memory.fPlugin.memory.fCallbacks.memory.SetHintValue(
mechanism.memory.fEngine, contextCryptDomain.UTF8String, &value)
return (err == errSecSuccess) ? true : false
}
// Get the kAuthorizationEnvironmentPassword
private func getPassword() -> NSString? {
var value : UnsafePointer<AuthorizationValue> = nil
var flags = AuthorizationContextFlags()
var err: OSStatus = noErr
err = self.mechanism.memory.fPlugin.memory.fCallbacks.memory.GetContextValue(mechanism.memory.fEngine, kAuthorizationEnvironmentPassword, &flags, &value)
if err != errSecSuccess {
return nil
}
guard let pass = NSString.init(bytes: value.memory.data, length: value.memory.length, encoding: NSUTF8StringEncoding)
else { return nil }
return pass.stringByReplacingOccurrencesOfString("\0", withString: "")
}
// Get the AuthorizationEnvironmentUsername
private func getUsername() -> NSString? {
var value : UnsafePointer<AuthorizationValue> = nil
var flags = AuthorizationContextFlags()
var err: OSStatus = noErr
err = self.mechanism.memory.fPlugin.memory.fCallbacks.memory.GetContextValue(mechanism.memory.fEngine, kAuthorizationEnvironmentUsername, &flags, &value)
if err != errSecSuccess {
return nil
}
guard let username = NSString.init(bytes: value.memory.data, length: value.memory.length, encoding: NSUTF8StringEncoding)
else { return nil }
return username.stringByReplacingOccurrencesOfString("\0", withString: "")
}
// Allow the login. End of the mechanism
private func allowLogin() -> OSStatus {
NSLog("VerifyAuth:MechanismInvoke:MachinePIN:[+] Done. Thanks and have a lovely day.");
var err: OSStatus = noErr
err = self.mechanism
.memory.fPlugin
.memory.fCallbacks
.memory.SetResult(mechanism.memory.fEngine, AuthorizationResult.Allow)
NSLog("VerifyAuth:MechanismInvoke:MachinePIN:[+] [%d]", Int(err));
return err
}
}
| 38.063927 | 161 | 0.65511 |
2f944262fee2c99bc67190ba032fab82cadccdb8 | 321 | //
// CurrencyServiceEndpoints.swift
// iCurrency
//
// Created by Armands Baurovskis on 27/04/2019.
// Copyright © 2019 iOSCoder. All rights reserved.
//
import Foundation
import RxSwift
protocol CurrencyServiceEndpoints {
func fetchCurrencies(baseCurrency: String) -> Observable<Result<[Currency], ApiError>>
}
| 21.4 | 88 | 0.753894 |
1af6cf365c09aed1621f3fcdce0a29eb7106c940 | 5,466 | //
// UIColor+BridgeKeyNames.swift
// BridgeAppSDK
//
// Copyright © 2017 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
extension UIColor {
// MARK: App background - default colors
open class var appBackgroundLight: UIColor {
return UIColor.white
}
open class var appBackgroundDark: UIColor {
return UIColor.primaryTintColor ?? UIColor.magenta
}
open class var appBackgroundGreen: UIColor {
return UIColor.greenTintColor
}
open class var appCrosshatchLight: UIColor {
return UIColor.appBackgroundLight.withAlphaComponent(0.3)
}
open class var appCrosshatchDark: UIColor {
return UIColor.appBackgroundDark.withAlphaComponent(0.3)
}
open class var appCrosshatchGreen: UIColor {
return UIColor.appBackgroundGreen.withAlphaComponent(0.3)
}
// MARK: App text - default colors
open class var appTextLight: UIColor {
return UIColor.white
}
open class var appTextDark: UIColor {
return UIColor(red: 65.0 / 255.0, green: 72.0 / 255.0, blue: 89.0 / 255.0, alpha: 1.0)
}
open class var appTextGreen: UIColor {
return UIColor.white
}
// MARK: Underlined button - default colors
open class var underlinedButtonTextLight: UIColor {
return UIColor.white
}
open class var underlinedButtonTextDark: UIColor {
return UIColor(red: 73.0 / 255.0, green: 91.0 / 255.0, blue: 122.0 / 255.0, alpha: 1.0)
}
// MARK: Rounded button - default colors
open class var roundedButtonBackgroundDark: UIColor {
return UIColor(red: 1.0, green: 136.0 / 255.0, blue: 117.0 / 255.0, alpha: 1.0)
}
open class var roundedButtonShadowDark: UIColor {
return UIColor(red: 242.0 / 255.0, green: 128.0 / 255.0, blue: 111.0 / 255.0, alpha: 1.0)
}
open class var roundedButtonTextLight: UIColor {
return UIColor.white
}
open class var roundedButtonBackgroundLight: UIColor {
return UIColor.white
}
open class var roundedButtonShadowLight: UIColor {
return UIColor(white: 245.0 / 255.0, alpha: 1.0)
}
open class var roundedButtonTextDark: UIColor {
return UIColor.appBackgroundDark
}
// MARK: Generic step view controller - header view
open class var headerViewHeaderLabel: UIColor {
return UIColor.darkGray
}
open class var headerViewDetailsLabel: UIColor {
return UIColor.gray
}
open class var headerViewPromptLabel: UIColor {
return UIColor.lightGray
}
open class var headerViewProgressBar: UIColor {
return UIColor(red: 103.0 / 255.0, green: 191.0 / 255.0, blue: 95.0 / 255.0, alpha: 1.0)
}
open class var headerViewProgressBackground: UIColor {
return UIColor.darkGray
}
open class var headerViewStepCountLabel: UIColor {
return UIColor.darkGray
}
// MARK: Generic step view controller - choice cell
open class var choiceCellBackground: UIColor {
return UIColor.white
}
open class var choiceCellBackgroundHighlighted: UIColor {
return UIColor.lightGray
}
open class var choiceCellLabel: UIColor {
return UIColor.darkGray
}
open class var choiceCellLabelHighlighted: UIColor {
return UIColor.darkGray
}
// MARK: Generic step view controller - text field cell
open class var textFieldCellText: UIColor {
return UIColor.darkGray
}
open class var textFieldCellBorder: UIColor {
return UIColor.darkGray
}
open class var textFieldCellLabel: UIColor {
return UIColor.lightGray
}
}
| 30.707865 | 97 | 0.678375 |
872b92ec0ea451fc680a047058f5600ede0c752d | 431 | public typealias GraphQLInputValue = JSONEncodable
public typealias GraphQLMap = [String: GraphQLInputValue]
public protocol GraphQLMapConvertible: JSONEncodable {
var graphQLMap: GraphQLMap { get }
}
extension GraphQLMapConvertible {
public var jsonValue: JSONValue {
return graphQLMap.jsonValue
}
}
public typealias GraphQLID = String
public protocol GraphQLMappable {
init(reader: GraphQLResultReader) throws
}
| 21.55 | 57 | 0.795824 |
8faada3a98123df233fb0abe781e2fe9c8de5c16 | 2,176 | //
// AppDelegate.swift
// MysteryNumber
//
// Created by Marc Schneider on 04/09/2018.
// Copyright © 2018 Hippo. 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:.
}
}
| 46.297872 | 285 | 0.755974 |
dbae238fbea9daf7ec84582c35b7ebdafee1401f | 233 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func e<T{
enum e{
class A:A
var b{
let a=b<{
}
}class A:A
func b | 19.416667 | 87 | 0.729614 |
5d50abe39dc5695481ba1dfe73caa40468dd5911 | 882 | //
// FBCurveLocation.swift
// Swift VectorBoolean for iOS
//
// Based on FBCurveLocation - Created by Andrew Finnell on 6/18/13.
// Copyright (c) 2013 Fortunate Bear, LLC. All rights reserved.
//
// Created by Leslie Titze on 2015-07-06.
// Copyright (c) 2015 Leslie Titze. All rights reserved.
//
import UIKit
class FBCurveLocation {
var graph : FBBezierGraph?
var contour : FBBezierContour?
fileprivate var _edge : FBBezierCurve
fileprivate var _parameter : Double
fileprivate var _distance : Double
init(edge: FBBezierCurve, parameter: Double, distance: Double) {
_edge = edge
_parameter = parameter
_distance = distance
}
var edge : FBBezierCurve {
return _edge
}
var parameter : Double {
return _parameter
}
var distance : Double {
return _distance
}
}
| 23.210526 | 68 | 0.650794 |
9b97fe25d06ded36956cfdd2e5be23ed02d43240 | 926 | import Foundation
import Nimble
import Quick
@testable import Bedrock
class OptionalSpec: QuickSpec {
override func spec() {
describe("isEmpty/isNotEmpty") {
it("returns true/false for none") {
expect(String?.none.lacksElements).to(beTrue())
expect(String?.none.hasElements).to(beFalse())
}
it("returns true/false for an empty collection") {
expect(String?.some("").lacksElements).to(beTrue())
expect(String?.some("").hasElements).to(beFalse())
}
it("returns false/true for an occupied collection") {
expect(String?.some("I-IT'S NOT LIKE I LIKE YOU OR ANYTHING, B-BAKA (//∇//)\\").lacksElements).to(beFalse())
expect(String?.some("I-IT'S NOT LIKE I LIKE YOU OR ANYTHING, B-BAKA (//∇//)\\").hasElements).to(beTrue())
}
}
}
}
| 28.060606 | 124 | 0.559395 |
5ba01e46e9e6159f234ff77a30afa9345dde78b2 | 605 | import Foundation
struct UserRetrieve: Codable {
let id: Int?
let fullname: String?
let last_name: String?
let email: String?
let avatar: MediaFile?
let about: String?
let username: String?
let is_subscribed: Bool?
let followings_count: Int?
let followers_count: Int?
let feed_elements_count: Int?
}
extension UserRetrieve: Hashable, Equatable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: UserRetrieve, rhs: UserRetrieve) -> Bool {
lhs.hashValue == rhs.hashValue
}
}
| 20.166667 | 67 | 0.636364 |
f7eb0c04a13507f0afc6d1edd349e273c4e9c579 | 11,001 | //
// BasePresentationController.swift
// SideMenu
//
// Created by Jon Kent on 10/20/18.
//
import UIKit
internal protocol PresentationModel {
/// Draws `presentStyle.backgroundColor` behind the status bar. Default is 1.
var statusBarEndAlpha: CGFloat { get }
/// Enable or disable interaction with the presenting view controller while the menu is displayed. Enabling may make it difficult to dismiss the menu or cause exceptions if the user tries to present and already presented menu. `presentingViewControllerUseSnapshot` must also set to false. Default is false.
var presentingViewControllerUserInteractionEnabled: Bool { get }
/// Use a snapshot for the presenting vierw controller while the menu is displayed. Useful when layout changes occur during transitions. Not recommended for apps that support rotation. Default is false.
var presentingViewControllerUseSnapshot: Bool { get }
/// The presentation style of the menu.
var presentationStyle: SideMenuPresentationStyle { get }
/// Width of the menu when presented on screen, showing the existing view controller in the remaining space. Default is zero.
var menuWidth: CGFloat { get }
}
internal protocol SideMenuPresentationControllerDelegate: class {
func sideMenuPresentationControllerDidTap(_ presentationController: SideMenuPresentationController)
func sideMenuPresentationController(_ presentationController: SideMenuPresentationController, didPanWith gesture: UIPanGestureRecognizer)
}
internal final class SideMenuPresentationController {
private let config: PresentationModel
private unowned var containerView: UIView
private var interactivePopGestureRecognizerEnabled: Bool?
private let leftSide: Bool
private weak var originalSuperview: UIView?
private unowned var presentedViewController: UIViewController
private unowned var presentingViewController: UIViewController
private lazy var snapshotView: UIView? = {
guard config.presentingViewControllerUseSnapshot,
let view = presentingViewController.view.snapshotView(afterScreenUpdates: true) else {
return nil
}
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
return view
}()
private lazy var statusBarView: UIView? = {
guard config.statusBarEndAlpha != 0 else { return nil }
return UIView {
$0.backgroundColor = config.presentationStyle.backgroundColor
$0.autoresizingMask = [.flexibleHeight, .flexibleWidth]
$0.isUserInteractionEnabled = false
}
}()
required init(config: PresentationModel, leftSide: Bool, presentedViewController: UIViewController, presentingViewController: UIViewController, containerView: UIView) {
self.config = config
self.containerView = containerView
self.leftSide = leftSide
self.presentedViewController = presentedViewController
self.presentingViewController = presentingViewController
}
deinit {
guard !presentedViewController.isHidden else { return }
// Presentations must be reversed to preserve user experience
dismissalTransitionWillBegin()
dismissalTransition()
dismissalTransitionDidEnd(true)
}
var frameOfPresentedViewInContainerView: CGRect {
var rect = containerView.frame
rect.origin.x = leftSide ? 0 : rect.width - config.menuWidth
rect.size.width = config.menuWidth
return rect
}
func containerViewWillLayoutSubviews() {
presentedViewController.view.untransform {
presentedViewController.view.frame = frameOfPresentedViewInContainerView
}
presentingViewController.view.untransform {
presentingViewController.view.frame = containerView.frame
snapshotView?.frame = containerView.frame
}
guard let statusBarView = statusBarView else { return }
let statusBarOffset = containerView.frame.size.height - presentedViewController.view.bounds.height
var statusBarFrame = UIApplication.shared.statusBarFrame
// For in-call status bar, height is normally 40, which overlaps view. Instead, calculate height difference
// of view and set height to fill in remaining space.
if statusBarOffset >= CGFloat.ulpOfOne {
statusBarFrame.size.height = statusBarOffset
}
statusBarView.frame = statusBarFrame
}
func presentationTransitionWillBegin() {
if let snapshotView = snapshotView {
presentingViewController.view.addSubview(snapshotView)
}
presentingViewController.view.isUserInteractionEnabled = config.presentingViewControllerUserInteractionEnabled
containerView.backgroundColor = config.presentationStyle.backgroundColor
originalSuperview = presentingViewController.view.superview
containerView.addSubview(presentingViewController.view)
containerView.addSubview(presentedViewController.view)
layerViews()
if let statusBarView = statusBarView {
containerView.addSubview(statusBarView)
}
dismissalTransition()
config.presentationStyle.presentationTransitionWillBegin(to: presentedViewController, from: presentingViewController)
}
func presentationTransition() {
transition(
to: presentedViewController,
from: presentingViewController,
alpha: config.presentationStyle.presentingEndAlpha,
statusBarAlpha: config.statusBarEndAlpha,
scale: config.presentationStyle.presentingScaleFactor,
translate: config.presentationStyle.presentingTranslateFactor
)
config.presentationStyle.presentationTransition(to: presentedViewController, from: presentingViewController)
}
func presentationTransitionDidEnd(_ completed: Bool) {
guard completed else {
snapshotView?.removeFromSuperview()
dismissalTransitionDidEnd(!completed)
return
}
addParallax(to: presentingViewController.view)
if let topNavigationController = presentingViewController as? UINavigationController {
interactivePopGestureRecognizerEnabled = topNavigationController.interactivePopGestureRecognizer?.isEnabled
topNavigationController.interactivePopGestureRecognizer?.isEnabled = false
}
containerViewWillLayoutSubviews()
config.presentationStyle.presentationTransitionDidEnd(to: presentedViewController, from: presentingViewController, completed)
}
func dismissalTransitionWillBegin() {
snapshotView?.removeFromSuperview()
presentationTransition()
config.presentationStyle.dismissalTransitionWillBegin(to: presentedViewController, from: presentingViewController)
}
func dismissalTransition() {
transition(
to: presentingViewController,
from: presentedViewController,
alpha: config.presentationStyle.menuStartAlpha,
statusBarAlpha: 0,
scale: config.presentationStyle.menuScaleFactor,
translate: config.presentationStyle.menuTranslateFactor
)
config.presentationStyle.dismissalTransition(to: presentedViewController, from: presentingViewController)
}
func dismissalTransitionDidEnd(_ completed: Bool) {
guard completed else {
if let snapshotView = snapshotView {
presentingViewController.view.addSubview(snapshotView)
}
presentationTransitionDidEnd(!completed)
return
}
statusBarView?.removeFromSuperview()
presentedViewController.view.removeFromSuperview()
presentingViewController.view.motionEffects.removeAll()
presentingViewController.view.layer.shadowOpacity = 0
presentedViewController.view.layer.shadowOpacity = 0
if let interactivePopGestureRecognizerEnabled = interactivePopGestureRecognizerEnabled,
let topNavigationController = presentingViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer?.isEnabled = interactivePopGestureRecognizerEnabled
}
originalSuperview?.addSubview(presentingViewController.view)
presentingViewController.view.isUserInteractionEnabled = true
config.presentationStyle.dismissalTransitionDidEnd(to: presentedViewController, from: presentingViewController, completed)
}
}
private extension SideMenuPresentationController {
func transition(to: UIViewController, from: UIViewController, alpha: CGFloat, statusBarAlpha: CGFloat, scale: CGFloat, translate: CGFloat) {
containerViewWillLayoutSubviews()
to.view.transform = .identity
to.view.alpha = 1
let x = (leftSide ? 1 : -1) * config.menuWidth * translate
from.view.alpha = alpha
from.view.transform = CGAffineTransform
.identity
.translatedBy(x: x, y: 0)
.scaledBy(x: scale, y: scale)
statusBarView?.alpha = statusBarAlpha
}
func layerViews() {
statusBarView?.layer.zPosition = 2
if config.presentationStyle.menuOnTop {
addShadow(to: presentedViewController.view)
presentedViewController.view.layer.zPosition = 1
} else {
addShadow(to: presentingViewController.view)
presentedViewController.view.layer.zPosition = -1
}
}
func addShadow(to view: UIView) {
view.layer.shadowColor = config.presentationStyle.onTopShadowColor.cgColor
view.layer.shadowRadius = config.presentationStyle.onTopShadowRadius
view.layer.shadowOpacity = config.presentationStyle.onTopShadowOpacity
view.layer.shadowOffset = config.presentationStyle.onTopShadowOffset
}
func addParallax(to view: UIView) {
var effects: [UIInterpolatingMotionEffect] = []
let x = config.presentationStyle.presentingParallaxStrength.width
if x > 0 {
let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
horizontal.minimumRelativeValue = -x
horizontal.maximumRelativeValue = x
effects.append(horizontal)
}
let y = config.presentationStyle.presentingParallaxStrength.height
if y > 0 {
let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
vertical.minimumRelativeValue = -y
vertical.maximumRelativeValue = y
effects.append(vertical)
}
if effects.count > 0 {
let group = UIMotionEffectGroup()
group.motionEffects = effects
view.motionEffects.removeAll()
view.addMotionEffect(group)
}
}
}
| 41.202247 | 310 | 0.709026 |
018576c7ee78aa050ba423e3e1864f7f830543c1 | 5,163 | //
// PublishJobDestination.swift
// VimeoNetworking
//
// Copyright © 2019 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/// The status of the upload or post for the given platform.
/// - error: There was an error trying to upload the video or create the post.
/// - finished: The post was successfully published.
/// - inProgress: The post creation process is currently underway.
@objc public enum PublishStatus: Int {
case error
case finished
case inProgress
}
extension PublishStatus: CustomStringConvertible {
public var description: String {
switch self {
case .error:
return .error
case .finished:
return .finished
case .inProgress:
return .inProgress
}
}
}
@objcMembers
public class PublishDestination: VIMModelObject {
internal private(set) var statusString: String?
/// The status of the post for a given platform.
@nonobjc public var status: PublishStatus? {
switch self.statusString {
case String.error:
return .error
case String.finished:
return .finished
case String.inProgress:
return .inProgress
default:
return nil
}
}
/// The URL of the post on a given platform.
public private(set) var thirdPartyPostURL: String?
/// The ID of the post on a given platform.
public private(set) var thirdPartyPostID: String?
/// The number of views this post has, as reported by the third party platform.
public private(set) var thirdPartyViewCount: NSNumber?
/// The number of likes (or equivalent) this post has, as reported by the third party platform.
public private(set) var thirdPartyLikeCount: NSNumber?
/// The number of comments this post has, as reported by the third party platform.
public private(set) var thirdPartyCommentCount: NSNumber?
// MARK: - Overrides
public override func getObjectMapping() -> Any? {
return [
Constants.thirdPartyPostURL.0: Constants.thirdPartyPostURL.1,
Constants.thirdPartyPostID.0: Constants.thirdPartyPostID.1,
Constants.thirdPartyViewCount.0: Constants.thirdPartyViewCount.1,
Constants.thirdPartyLikeCount.0: Constants.thirdPartyLikeCount.1,
Constants.thirdPartyCommentCount.0: Constants.thirdPartyCommentCount.1,
Constants.status.0: Constants.status.1
]
}
}
/// Encapsulates data related to all supported platform destinations.
@objcMembers
public class PublishDestinations: VIMModelObject {
/// Information about a post on Facebook.
public private(set) var facebook: PublishDestination?
/// Information about a post on YouTube.
public private(set) var youtube: PublishDestination?
/// Information about a post on LinkedIn.
public private(set) var linkedin: PublishDestination?
/// Information about a post on Twitter.
public private(set) var twitter: PublishDestination?
public override func getClassForObjectKey(_ key: String?) -> AnyClass? {
switch key {
case String.facebook,
String.linkedin,
String.twitter,
String.youtube:
return PublishDestination.self
default:
return nil
}
}
}
private extension String {
static let error = "error"
static let finished = "finished"
static let inProgress = "in_progress"
}
private struct Constants {
static let status = (key: "status", value: "statusString")
static let thirdPartyPostURL = (key: "third_party_post_url", value: "thirdPartyPostURL")
static let thirdPartyPostID = (key: "third_party_post_id", value: "thirdPartyPostID")
static let thirdPartyViewCount = (key: "third_party_view_count", value: "thirdPartyViewCount")
static let thirdPartyLikeCount = (key: "third_party_like_count", value: "thirdPartyLikeCount")
static let thirdPartyCommentCount = (key: "third_party_comment_count", value: "thirdPartyCommentCount")
}
| 37.413043 | 107 | 0.693783 |
5dbe6def58792e6d5d5acca7137e2325900c280c | 15,588 | import SQLKit
/// Postgres-specific column types.
public struct PostgresColumnType: SQLExpression, Equatable {
public static var blob: PostgresColumnType {
return .varbit
}
/// See `Equatable`.
public static func == (lhs: PostgresColumnType, rhs: PostgresColumnType) -> Bool {
return lhs.primitive == rhs.primitive && lhs.isArray == rhs.isArray
}
/// signed eight-byte integer
public static var int8: PostgresColumnType {
return .bigint
}
/// signed eight-byte integer
public static var bigint: PostgresColumnType {
return .init(.bigint)
}
/// autoincrementing eight-byte integer
public static var serial8: PostgresColumnType {
return .bigserial
}
/// autoincrementing eight-byte integer
public static var bigserial: PostgresColumnType {
return .init(.bigserial)
}
/// fixed-length bit string
public static var bit: PostgresColumnType {
return .init(.bit(nil))
}
/// fixed-length bit string
public static func bit(_ n: Int) -> PostgresColumnType {
return .init(.bit(n))
}
/// variable-length bit string
public static var varbit: PostgresColumnType {
return .init(.varbit(nil))
}
/// variable-length bit string
public static func varbit(_ n: Int) -> PostgresColumnType {
return .init(.varbit(n))
}
/// logical Boolean (true/false)
public static var bool: PostgresColumnType {
return .boolean
}
/// logical Boolean (true/false)
public static var boolean: PostgresColumnType {
return .init(.boolean)
}
/// rectangular box on a plane
public static var box: PostgresColumnType {
return .init(.box)
}
/// binary data (“byte array”)
public static var bytea: PostgresColumnType {
return .init(.bytea)
}
/// fixed-length character string
public static var char: PostgresColumnType {
return .init(.char(nil))
}
/// fixed-length character string
public static func char(_ n: Int) -> PostgresColumnType {
return .init(.char(n))
}
/// variable-length character string
public static var varchar: PostgresColumnType {
return .init(.varchar(nil))
}
/// variable-length character string
public static func varchar(_ n: Int) -> PostgresColumnType {
return .init(.varchar(n))
}
/// IPv4 or IPv6 network address
public static var cidr: PostgresColumnType {
return .init(.cidr)
}
/// circle on a plane
public static var circle: PostgresColumnType {
return .init(.circle)
}
/// calendar date (year, month, day)
public static var date: PostgresColumnType {
return .init(.date)
}
/// floating-point number (8 bytes)
public static var float8: PostgresColumnType {
return .doublePrecision
}
/// floating-point number (8 bytes)
public static var doublePrecision: PostgresColumnType {
return .init(.doublePrecision)
}
/// IPv4 or IPv6 host address
public static var inet: PostgresColumnType {
return .init(.inet)
}
/// signed four-byte integer
public static var int: PostgresColumnType {
return .integer
}
/// signed four-byte integer
public static var int4: PostgresColumnType {
return .integer
}
/// signed four-byte integer
public static var integer: PostgresColumnType {
return .init(.integer)
}
/// time span
public static var interval: PostgresColumnType {
return .init(.interval)
}
/// textual JSON data
public static var json: PostgresColumnType {
return .init(.json)
}
/// binary JSON data, decomposed
public static var jsonb: PostgresColumnType {
return .init(.jsonb)
}
/// infinite line on a plane
public static var line: PostgresColumnType {
return .init(.line)
}
/// line segment on a plane
public static var lseg: PostgresColumnType {
return .init(.lseg)
}
/// MAC (Media Access Control) address
public static var macaddr: PostgresColumnType {
return .init(.macaddr)
}
/// MAC (Media Access Control) address (EUI-64 format)
public static var macaddr8: PostgresColumnType {
return .init(.macaddr8)
}
/// currency amount
public static var money: PostgresColumnType {
return .init(.money)
}
/// exact numeric of selectable precision
public static var decimal: PostgresColumnType {
return .init(.numeric(nil, nil))
}
/// exact numeric of selectable precision
public static func decimal(_ p: Int, _ s: Int) -> PostgresColumnType {
return .init(.numeric(p, s))
}
/// exact numeric of selectable precision
public static func numeric(_ p: Int, _ s: Int) -> PostgresColumnType {
return .init(.numeric(p, s))
}
/// exact numeric of selectable precision
public static var numeric: PostgresColumnType {
return .init(.numeric(nil, nil))
}
/// geometric path on a plane
public static var path: PostgresColumnType {
return .init(.path)
}
/// PostgreSQL Log Sequence Number
public static var pgLSN: PostgresColumnType {
return .init(.pgLSN)
}
/// geometric point on a plane
public static var point: PostgresColumnType {
return .init(.point)
}
/// closed geometric path on a plane
public static var polygon: PostgresColumnType {
return .init(.polygon)
}
/// single precision floating-point number (4 bytes)
public static var float4: PostgresColumnType {
return .real
}
/// single precision floating-point number (4 bytes)
public static var real: PostgresColumnType {
return .init(.real)
}
/// signed two-byte integer
public static var int2: PostgresColumnType {
return .smallint
}
/// signed two-byte integer
public static var smallint: PostgresColumnType {
return .init(.smallint) }
/// autoincrementing two-byte integer
public static var serial2: PostgresColumnType {
return .smallserial
}
/// autoincrementing two-byte integer
public static var smallserial: PostgresColumnType {
return .init(.smallserial)
}
/// autoincrementing four-byte integer
public static var serial4: PostgresColumnType {
return .serial
}
/// autoincrementing four-byte integer
public static var serial: PostgresColumnType {
return .init(.serial)
}
/// variable-length character string
public static var text: PostgresColumnType {
return .init(.text)
}
/// time of day (no time zone)
public static var time: PostgresColumnType {
return .init(.time(nil))
}
/// time of day (no time zone)
public static func time(_ n: Int) -> PostgresColumnType {
return .init(.time(n))
}
/// time of day, including time zone
public static var timetz: PostgresColumnType {
return .init(.timetz(nil))
}
/// time of day, including time zone
public static func timetz(_ n: Int) -> PostgresColumnType {
return .init(.timetz(n))
}
/// date and time (no time zone)
public static var timestamp: PostgresColumnType {
return .init(.timestamp(nil))
}
/// date and time (no time zone)
public static func timestamp(_ n: Int) -> PostgresColumnType {
return .init(.timestamp(n))
}
/// date and time, including time zone
public static var timestamptz: PostgresColumnType {
return .init(.timestamptz(nil))
}
/// date and time, including time zone
public static func timestamptz(_ n: Int) -> PostgresColumnType {
return .init(.timestamptz(n))
}
/// text search query
public static var tsquery: PostgresColumnType {
return .init(.tsquery)
}
/// text search document
public static var tsvector: PostgresColumnType {
return .init(.tsvector)
}
/// user-level transaction ID snapshot
public static var txidSnapshot: PostgresColumnType {
return .init(.txidSnapshot)
}
/// universally unique identifier
public static var uuid: PostgresColumnType {
return .init(.uuid)
}
/// XML data
public static var xml: PostgresColumnType {
return .init(.xml)
}
/// User-defined type
public static func custom(_ name: String) -> PostgresColumnType {
return .init(.custom(name))
}
/// Creates an array type from a `PostgreSQLDataType`.
public static func array(_ dataType: PostgresColumnType) -> PostgresColumnType {
return .init(dataType.primitive, isArray: true)
}
let primitive: Primitive
let isArray: Bool
private init(_ primitive: Primitive, isArray: Bool = false) {
self.primitive = primitive
self.isArray = isArray
}
enum Primitive: Equatable {
/// signed eight-byte integer
case bigint
/// autoincrementing eight-byte integer
case bigserial
/// fixed-length bit string
case bit(Int?)
/// variable-length bit string
case varbit(Int?)
/// logical Boolean (true/false)
case boolean
/// rectangular box on a plane
case box
/// binary data (“byte array”)
case bytea
/// fixed-length character string
case char(Int?)
/// variable-length character string
case varchar(Int?)
/// IPv4 or IPv6 network address
case cidr
/// circle on a plane
case circle
/// calendar date (year, month, day)
case date
/// floating-point number (8 bytes)
case doublePrecision
/// IPv4 or IPv6 host address
case inet
/// signed four-byte integer
case integer
/// time span
case interval
/// textual JSON data
case json
/// binary JSON data, decomposed
case jsonb
/// infinite line on a plane
case line
/// line segment on a plane
case lseg
/// MAC (Media Access Control) address
case macaddr
/// MAC (Media Access Control) address (EUI-64 format)
case macaddr8
/// currency amount
case money
/// exact numeric of selectable precision
case numeric(Int?, Int?)
/// geometric path on a plane
case path
/// PostgreSQL Log Sequence Number
case pgLSN
/// geometric point on a plane
case point
/// closed geometric path on a plane
case polygon
/// single precision floating-point number (4 bytes)
case real
/// signed two-byte integer
case smallint
/// autoincrementing two-byte integer
case smallserial
/// autoincrementing four-byte integer
case serial
/// variable-length character string
case text
/// time of day (no time zone)
case time(Int?)
/// time of day, including time zone
case timetz(Int?)
/// date and time (no time zone)
case timestamp(Int?)
/// date and time, including time zone
case timestamptz(Int?)
/// text search query
case tsquery
/// text search document
case tsvector
/// user-level transaction ID snapshot
case txidSnapshot
/// universally unique identifier
case uuid
/// XML data
case xml
/// User-defined type
case custom(String)
public func serialize(to serializer: inout SQLSerializer) {
serializer.write(self.string)
}
/// See `SQLSerializable`.
private var string: String {
switch self {
case .bigint: return "BIGINT"
case .bigserial: return "BIGSERIAL"
case .varbit(let n):
if let n = n {
return "VARBIT(" + n.description + ")"
} else {
return "VARBIT"
}
case .varchar(let n):
if let n = n {
return "VARCHAR(" + n.description + ")"
} else {
return "VARCHAR"
}
case .bit(let n):
if let n = n {
return "BIT(" + n.description + ")"
} else {
return "BIT"
}
case .boolean: return "BOOLEAN"
case .box: return "BOX"
case .bytea: return "BYTEA"
case .char(let n):
if let n = n {
return "CHAR(" + n.description + ")"
} else {
return "CHAR"
}
case .cidr: return "CIDR"
case .circle: return "CIRCLE"
case .date: return "DATE"
case .doublePrecision: return "DOUBLE PRECISION"
case .inet: return "INET"
case .integer: return "INTEGER"
case .interval: return "INTERVAL"
case .json: return "JSON"
case .jsonb: return "JSONB"
case .line: return "LINE"
case .lseg: return "LSEG"
case .macaddr: return "MACADDR"
case .macaddr8: return "MACADDER8"
case .money: return "MONEY"
case .numeric(let s, let p):
if let s = s, let p = p {
return "NUMERIC(" + s.description + ", " + p.description + ")"
} else {
return "NUMERIC"
}
case .path: return "PATH"
case .pgLSN: return "PG_LSN"
case .point: return "POINT"
case .polygon: return "POLYGON"
case .real: return "REAL"
case .smallint: return "SMALLINT"
case .smallserial: return "SMALLSERIAL"
case .serial: return "SERIAL"
case .text: return "TEXT"
case .time(let p):
if let p = p {
return "TIME(" + p.description + ")"
} else {
return "TIME"
}
case .timetz(let p):
if let p = p {
return "TIMETZ(" + p.description + ")"
} else {
return "TIMETZ"
}
case .timestamp(let p):
if let p = p {
return "TIMESTAMP(" + p.description + ")"
} else {
return "TIMESTAMP"
}
case .timestamptz(let p):
if let p = p {
return "TIMESTAMPTZ(" + p.description + ")"
} else {
return "TIMESTAMPTZ"
}
case .tsquery: return "TSQUERY"
case .tsvector: return "TSVECTOR"
case .txidSnapshot: return "TXID_SNAPSHOT"
case .uuid: return "UUID"
case .xml: return "XML"
case .custom(let custom): return custom
}
}
}
/// See `SQLSerializable`.
public func serialize(to serializer: inout SQLSerializer) {
self.primitive.serialize(to: &serializer)
if self.isArray {
serializer.write("[]")
}
}
}
| 26.737564 | 86 | 0.56659 |
f8b949e151dff34d9f16c265f1a335d908aa2a9e | 370 | //
// UserModelObject.swift
// SDAO
//
// Created by incetro on 26/08/2018.
//
import SDAO
import RealmSwift
// MARK: - UserModelObject
final class UserModelObject: RealmModel {
/// User's name
@objc dynamic var name: String = ""
/// User's age
@objc dynamic var age: Int = 0
/// User's dialogs
let dialogs = List<DialogModelObject>()
}
| 15.416667 | 43 | 0.635135 |
1ab5c8bc3cd548e4a8d7a0703d45e5c130ef7c7e | 188 | //
// AudiVC.swift
// SwinjectFails
//
// Created by Alexander Cyon on 2016-10-17.
// Copyright © 2016 Alexander Cyon. All rights reserved.
//
import UIKit
class AudiVC: CarVC {
}
| 12.533333 | 57 | 0.670213 |
e2d7e01e3c58b7cf62f8fb3f4d42d83ad819fa63 | 860 | //
// Extensions.swift
// OkLog
//
// Created by Diego Trevisan Lara on 30/06/2018.
//
#if !COCOAPODS
import OkLog
#endif
import Alamofire
protocol IOkLogAlamofire: IOkLog {
static func log<T>(_ dataResponse: DataResponse<T>, shortenUrl: Bool)
static func getUrl<T>(_ dataResponse: DataResponse<T>, shortenUrl: Bool) -> String
}
extension OkLog: IOkLogAlamofire {
public static func log<T>(_ dataResponse: DataResponse<T>, shortenUrl: Bool = true) {
log(request: dataResponse.request, response: dataResponse.response, data: dataResponse.data, shortenUrl: shortenUrl)
}
public static func getUrl<T>(_ dataResponse: DataResponse<T>, shortenUrl: Bool = true) -> String {
return getUrl(request: dataResponse.request, response: dataResponse.response, data: dataResponse.data, shortenUrl: shortenUrl)
}
}
| 29.655172 | 134 | 0.712791 |
890518e779ad0707bb4c5db2aa7906adb21e1195 | 268 | //
// User.swift
// ESGist
//
// Created by Tomohiro Kumagai on H27/07/20.
// Copyright © 平成27年 EasyStyle G.K. All rights reserved.
//
extension Gist.User {
public enum UserType : String, Decodable, Sendable {
case user = "User"
}
}
| 16.75 | 57 | 0.597015 |
e9bd44c1bb3683380ef1c7046aa21ea6de807d16 | 12,383 | //
// CreditCardType.swift
// FlatPaymentMethod
//
// Created by Ampe on 8/7/18.
//
import Foundation
// MARK: - Credit Card Types
public enum CreditCardType: Equatable, Hashable {
case visa(type: VisaType)
case amex
case unionPay
case mastercard
case maestro
case dinersClub(type: DinersClubType)
case discover
case jcb
case uatp
case dankort
case interpayment
}
// MARK: - All Cards
public extension CreditCardType {
public static let all: [CreditCardType] = [.visa(type: .visa),
.visa(type: .electron),
.amex,
.unionPay,
.mastercard,
.maestro,
.dinersClub(type: .carteBlanche),
.dinersClub(type: .international),
.dinersClub(type: .usbc),
.discover,
.jcb,
.uatp,
.dankort,
.interpayment]
}
// MARK: - Diners Card Types
public enum DinersClubType: Equatable {
case carteBlanche
case international
case usbc
}
// MARK: - Visa Card Types
public enum VisaType: Equatable {
case visa
case electron
}
// MARK: - Public Methods For Card Validation
public extension CreditCardType {
func isValid(_ accountNumber: String) -> Bool {
return requirement.isValid(accountNumber) && Mathematics.luhnCheck(accountNumber)
}
func isPrefixValid(_ accountNumber: String) -> Bool {
return requirement.isPrefixValid(accountNumber)
}
}
// MARK: - Public Property Methods
public extension CreditCardType {
func segmentGrouping(for length: Int) -> [Int] {
if let assignedGrouping = segmentGrouping[length] {
return assignedGrouping
} else {
return Mathematics.defaultGrouping(for: length)
}
}
}
// MARK: - Public Getters
public extension CreditCardType {
var name: String {
switch self {
case .amex:
return "American Express"
case .unionPay:
return "Union Pay"
case .dinersClub(let type):
switch type {
case .carteBlanche:
return "Diner's Club - Carte Blanche"
case .international:
return "Diner's Club - International"
case .usbc:
return "Diner's Club - United States & Canada"
}
case .discover:
return "Discover Card"
case .jcb:
return "JCB"
case .maestro:
return "Maestro"
case .dankort:
return "Dankort"
case .mastercard:
return "Mastercard"
case .visa(let type):
switch type {
case .visa:
return "Visa"
case .electron:
return "Visa Electron"
}
case .uatp:
return "UATP"
case .interpayment:
return "Interpayment"
}
}
var logoDark: UIImage? {
switch self {
case .amex:
return UIImage.for(#imageLiteral(resourceName: "amex"))
case .unionPay:
return UIImage.for(#imageLiteral(resourceName: "union-pay"))
case .dinersClub:
return UIImage.for(#imageLiteral(resourceName: "diners-club"))
case .discover:
return UIImage.for(#imageLiteral(resourceName: "discover"))
case .jcb:
return UIImage.for(#imageLiteral(resourceName: "jcb"))
case .maestro:
return UIImage.for(#imageLiteral(resourceName: "maestro"))
case .dankort:
return UIImage.for(#imageLiteral(resourceName: "dankort"))
case .mastercard:
return UIImage.for(#imageLiteral(resourceName: "mastercard"))
case .visa:
return UIImage.for(#imageLiteral(resourceName: "visa"))
case .uatp:
return UIImage.for(#imageLiteral(resourceName: "uatp"))
case .interpayment:
return UIImage.for(#imageLiteral(resourceName: "interpay"))
}
}
}
// MARK: - Main Validation Method On Array Of Credit Card Type
public extension Array where Element == CreditCardType {
func validate(prefix: String) -> [Element] {
// have an array of credit cards and length of prefix to compare against
// if there are multiple cards we want to find the card with the number of digits closest to the prefix length
// need to filter out non-matching prefixes
// if there are multiple cards with this same prefix length, return an array of cards
var minPrefixLength: Int = 0
var potentialCardsDictionary: [Int: Set<CreditCardType>] = [:]
// itterate over every card in the array and look at the potential
// prefixes of each card
forEach { card in
// ensure that this card has any valid prefixes
// before continuing into the heavier lifting processes
guard card.isPrefixValid(prefix) else {
return
}
card.requirement.prefixes.forEach { potentialPrefix in
// potential prefix matches input value
// this is to avoid adding a card which has
// no matching prefix to the input
guard potentialPrefix.hasCommonPrefix(with: prefix) else {
return
}
// ensure potential prefix length is greater than or equal to
// the running minimum prefix length count
// this is to avoid adding cards with shorter prefixes
// when the prefix matches a more specific prefix
guard potentialPrefix.count >= minPrefixLength else {
return
}
// add card belonging to potential prefix to the dictionary
// of potential cards with a value of the potential
// prefixes length
if potentialCardsDictionary[potentialPrefix.count] != nil {
potentialCardsDictionary[potentialPrefix.count]?.insert(card)
} else {
potentialCardsDictionary[potentialPrefix.count] = [card]
}
// ensure the length of the potential prefix does not
// exceed that of the entered prefix
// this is to avoid having a minimum prefix length
// which is larger than the current length of the entered
// prefix
// if this were to happen, we would exclude cards which
// shoud still be included in the set of potential cards
guard potentialPrefix.count <= prefix.count else {
return
}
// update the minimum prefix length to that of the
// potential prefix length
minPrefixLength = potentialPrefix.count
}
}
// we want to include all cards with the minPrefixLength
// as well as all cards with potentialPrefix values longer
// than the minPrefixLength
var possibleCards: Set<CreditCardType> = []
// extract all lengths from the dictionary
potentialCardsDictionary.keys
.filter { length in
// take all lengths equal to or larger than the minimum prefix length
length >= minPrefixLength
}.forEach { length in
// extract cards for these lengths from the dictionary
guard let cards = potentialCardsDictionary[length] else {
return
}
// construct array of cards from these values
cards.forEach { card in
possibleCards.insert(card)
}
}
return Array(possibleCards)
}
}
// MARK: - Constants For Determining Card Type
private extension CreditCardType {
// per https://baymard.com/checkout-usability/credit-card-patterns
// Feb 3, 2017 article publish date
// Aug 7, 2018 implementation date
// Aug 7, 2018 implementation updated date
var requirement: CreditCardTypeValidationRequirement {
let prefixes: [PrefixContainable]
let lengths: [Int]
switch self {
case .amex:
prefixes = ["34", "37"]
lengths = [15]
case .unionPay:
prefixes = ["62"]
lengths = [16, 17, 18, 19]
case .dinersClub(let type):
switch type {
case .carteBlanche:
prefixes = ["300"..."305"]
lengths = [14]
case .international:
prefixes = ["309", "36", "38"..."39"]
lengths = [14]
case .usbc:
prefixes = ["54", "55"]
lengths = [16]
}
case .discover:
prefixes = ["6011", "622126"..."622925", "644"..."649", "65"]
lengths = [16]
case .jcb:
prefixes = ["3528"..."3589"]
lengths = [16]
case .maestro:
prefixes = ["500000"..."509999", "560000"..."589999", "600000"..."699999"]
lengths = [12, 13, 14, 15, 16, 17, 18, 19]
case .dankort:
prefixes = ["5019"]
lengths = [16]
case .mastercard:
prefixes = ["51"..."55"]
lengths = [16]
case .visa(let type):
switch type {
case .visa:
prefixes = ["4"]
lengths = [13, 14, 15, 16, 17, 18, 19]
case .electron:
prefixes = ["4026", "417500", "4405", "4508", "4844", "4913", "4917"]
lengths = [16]
}
case .uatp:
prefixes = ["1"]
lengths = [15]
case .interpayment:
prefixes = ["636"]
lengths = [16, 17, 18, 19]
}
return CreditCardTypeValidationRequirement(prefixes: prefixes, lengths: lengths)
}
// per https://baymard.com/checkout-usability/credit-card-patterns
// Feb 3, 2017 article publish date
// Aug 7, 2018 implementation date
// Aug 7, 2018 implementation updated date
var segmentGrouping: [Int: [Int]] {
switch self {
case .amex:
return [16: [4, 6, 5]]
case .unionPay:
return [16: [4, 4, 4, 4],
19: [6, 13]]
case .dinersClub(let type):
switch type {
case .carteBlanche:
return [14: [4, 6, 4]]
case .international:
return [14: [4, 6, 4]]
case .usbc:
return [16: [4, 4, 4, 4]]
}
case .discover:
return [16: [4, 4, 4, 4]]
case .jcb:
return [16: [4, 4, 4, 4]]
case .maestro:
return [13: [4, 4, 5],
15: [4, 6, 5],
16: [4, 4, 4, 4],
19: [4, 4, 4, 4, 3]]
case .dankort:
return [16: [4, 4, 4, 4]]
case .mastercard:
return [16: [4, 4, 4, 4]]
case .visa(let type):
switch type {
case .visa:
return [16: [4, 4, 4, 4]]
case .electron:
return [16: [4, 4, 4, 4]]
}
case .uatp:
return [15: [4, 5, 6]]
case .interpayment:
return [16: [4, 4, 4, 4]]
}
}
// per scraping the internet
// Aug 7, 2018 implementation date
// Aug 7, 2018 implementation updated date
var cvvLength: Int {
switch self {
case .amex:
return 4
default:
return 3
}
}
}
| 34.493036 | 118 | 0.503674 |
eddfc5631bb9fdce117b24f24cec3f8b76854bab | 698 | //
// CommentTableViewCell.swift
// homeWork_1
//
// Created by Admin on 11/28/18.
// Copyright © 2018 User. All rights reserved.
//
import UIKit
class CommentTableViewCell: UITableViewCell {
@IBOutlet weak var imageViewAva: UIImageView!
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var labelText: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func load(_ comment: VkComment) {
labelName.text = comment.sender.getFullName()
labelText.text = comment.text
imageViewAva.sd_setImage(with: URL(string: comment.sender.imageUrl100), placeholderImage: UIImage(named: "noPhoto"))
}
}
| 22.516129 | 124 | 0.664756 |
dd2b8588fdac95763a3df3abd9e3dc0d5374b1d6 | 4,603 | //
// XHBGuideMaskView.swift
// blackboard
//
// Created by 研发部-001 on 2019/9/19.
// Copyright © 2019 xkb. All rights reserved.
//
import UIKit
class XHBGuideMaskView: UIControl {
private var showViews: [UIView] = [] // 引导提示
private var viewFrames: [CGRect] = [] // 引导提示定位
private var transparentPaths: [UIBezierPath] = [] // 引导透明区域,为 nil 时,铺满显示区域
private var showOrder: [Int]? // 显示个数,默认一次只显示一个引导页
private var clickIndex = -1 // 点击次数
private var hasShowGuide = 0 // 已经展示引导页数量
private var guideNumber = 0 // 引导总数量
private var overLayerPath: UIBezierPath?
private var fillLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.frame = UIScreen.main.bounds
return layer
}()
init(nums: Int) {
super.init(frame: UIScreen.main.bounds)
guideNumber = nums
createUI()
createActions()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createUI() {
backgroundColor = .clear
let maskColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
self.layer.addSublayer(fillLayer)
refreshMask()
fillLayer.path = self.overLayerPath?.cgPath
fillLayer.fillRule = CAShapeLayerFillRule.evenOdd
fillLayer.fillColor = maskColor.cgColor
}
private func createActions() {
addTarget(self, action: #selector(clickNext), for: UIControl.Event.touchUpInside)
}
// 创建透明层区域
private func createOverLayerPath() -> UIBezierPath {
let overlayPath = UIBezierPath(rect: self.bounds)
overlayPath.usesEvenOddFillRule = true
return overlayPath
}
/// 添加蒙版上的指定View
///
/// - Parameters:
/// - views: 提示 view
/// - viewFrame: 提示 view 定位
/// - transparentViews: 透明区域 CGRect
@objc func addViews(views: [UIView], viewFrame: [CGRect], transparentViews: [CGRect], orders: [Int]? = nil) {
showOrder = orders
showViews = views
viewFrames = viewFrame
for item in transparentViews {
let frame = item
let radius = 8 //item.layer.cornerRadius
let transparentPath = UIBezierPath.init(roundedRect: frame, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: radius, height: radius))
transparentPaths.append(transparentPath)
}
}
/// 绘制透明区域
private func addTransparentPath(transparentPath: UIBezierPath) {
overLayerPath?.append(transparentPath)
fillLayer.path = overLayerPath?.cgPath
}
/// 点击显示下一张引导页,如果没有退出显示
@objc private func clickNext() {
if hasShowGuide >= guideNumber {
dismissMaskView()
return
}
clickIndex += 1
/// 单张引导逻辑
func showGuides(_ nums: Int = 1) {
if clickIndex < showViews.count {
refreshMask()
subviews.forEach { (view) in
view.removeFromSuperview()
}
for index in hasShowGuide..<hasShowGuide + nums where index < transparentPaths.count {
addTransparentPath(transparentPath: transparentPaths[index])
}
addGuideView(nums)
} else {
dismissMaskView()
}
hasShowGuide += nums
}
if let showOrder = showOrder,
clickIndex < showOrder.count, showOrder[clickIndex] + hasShowGuide <= guideNumber {
showGuides(showOrder[clickIndex])
return
}
showGuides()
}
private func refreshMask() {
overLayerPath = createOverLayerPath()
}
/// 添加一张引导图
private func addGuideView(_ nums: Int = 1) {
for index in hasShowGuide..<nums + hasShowGuide {
let v = showViews[index]
let frame = viewFrames[index]
v.frame = frame
addSubview(showViews[index])
}
}
func showMaskViewInView(view: UIView?) {
self.alpha = 0
if let view = view {
view.addSubview(self)
} else {
UIApplication.shared.keyWindow?.addSubview(self)
}
UIView.animate(withDuration: 0.3) {
self.alpha = 1
}
clickNext()
}
/// 销毁蒙层,默认点击区域后自动销毁
func dismissMaskView() {
UIView.animate(withDuration: 0.3, animations: {
self.alpha = 0
}) { _ in
self.removeFromSuperview()
}
}
deinit {
showViews.removeAll()
}
}
| 29.132911 | 167 | 0.584184 |
7671287a0a5826909492cfd418c7c796f7ead2df | 2,442 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_repeatwhile -o %t/main
// This unusual use of 'sh' allows the path of the profraw file to be
// substituted by %target-run.
// RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main
// RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_repeatwhile -o - | %FileCheck %s --check-prefix=SIL
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_repeatwhile -o - | %FileCheck %s --check-prefix=IR
// RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_repeatwhile -o - | %FileCheck %s --check-prefix=SIL-OPT
// need to check Opt support
// %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_repeatwhile -o - | %FileCheck %s --check-prefix=IR-OPT
// REQUIRES: profile_runtime
// REQUIRES: executable_test
// REQUIRES: OS=macosx
// SIL-LABEL: // pgo_repeatwhile.guessWhile
// SIL-LABEL: sil @$s15pgo_repeatwhile10guessWhile1xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
// IR-LABEL: define swiftcc i32 @"$s15pgo_repeatwhile10guessWhile1xs5Int32VAE_tF"
// IR-OPT-LABEL: define swiftcc i32 @"$s15pgo_repeatwhile10guessWhile1xs5Int32VAE_tF"
public func guessWhile(x: Int32) -> Int32 {
// SIL: cond_br {{.*}} !true_count(176400) !false_count(420)
// SIL: cond_br {{.*}} !true_count(420) !false_count(42)
// SIL-OPT: cond_br {{.*}} !true_count(176400) !false_count(420)
// SIL-OPT: cond_br {{.*}} !true_count(420) !false_count(42)
var ret : Int32 = 0
var currX : Int32 = 0
repeat {
var currInnerX : Int32 = x*42
repeat {
ret += currInnerX
currInnerX -= 1
} while (currInnerX > 0)
currX += 1
} while (currX < x)
return ret
}
func main() {
var guesses : Int32 = 0;
for _ in 1...42 {
guesses += guessWhile(x: 10)
}
}
main()
// IR: !{!"branch_weights", i32 176401, i32 421}
// IR: !{!"branch_weights", i32 421, i32 43}
// IR-OPT: !{!"branch_weights", i32 176401, i32 421}
// IR-OPT: !{!"branch_weights", i32 421, i32 43}
| 42.842105 | 195 | 0.690008 |
09c9c67949625093c47388732944c1d8b3211e7d | 8,540 | //
// ViewController.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import UIKit
import OAuthSwift
import SwiftHTTP
import SwiftDialog
import JSONJoy
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var services = ["Github"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "OAuth"
let tableView: UITableView = UITableView(frame: self.view.bounds, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func doOAuthTwitter(){
let oauthswift = OAuth1Swift(
consumerKey: Twitter["consumerKey"]!,
consumerSecret: Twitter["consumerSecret"]!,
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizeUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
)
//oauthswift.authorize_url_handler = WebViewController()
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/twitter")!, success: {
credential, response in
self.showAlertView("Twitter", message: "auth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
var parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.twitter.com/1.1/statuses/mentions_timeline.json", parameters: parameters,
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println(jsonDict)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
}
)
}
func doOAuthFlickr(){
let oauthswift = OAuth1Swift(
consumerKey: Flickr["consumerKey"]!,
consumerSecret: Flickr["consumerSecret"]!,
requestTokenUrl: "https://www.flickr.com/services/oauth/request_token",
authorizeUrl: "https://www.flickr.com/services/oauth/authorize",
accessTokenUrl: "https://www.flickr.com/services/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/flickr")!, success: {
credential, response in
self.showAlertView("Flickr", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
let url :String = "https://api.flickr.com/services/rest/"
let parameters :Dictionary = [
"method" : "flickr.photos.search",
"api_key" : Flickr["consumerKey"]!,
"user_id" : "128483205@N08",
"format" : "json",
"nojsoncallback" : "1",
"extras" : "url_q,url_z"
]
oauthswift.client.get(url, parameters: parameters,
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println(jsonDict)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthGithub(){
let oauthswift = OAuth2Swift(
consumerKey: Github["consumerKey"]!,
consumerSecret: Github["consumerSecret"]!,
authorizeUrl: "https://github.com/login/oauth/authorize",
accessTokenUrl: "https://github.com/login/oauth/access_token",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/github")!, scope: "user,repo", state: state, success: {
credential, response, parameters in
//self.showAlertView("Github", message: "oauth_token:\(credential.oauth_token)")
self.popgitrepo(credential.oauth_token)
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func snapshot() -> NSData {
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.layer.renderInContext(UIGraphicsGetCurrentContext())
let fullScreenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(fullScreenshot, nil, nil, nil)
return UIImageJPEGRepresentation(fullScreenshot, 0.5)
}
func popgitrepo(token:String){
var request = HTTPTask()
request.requestSerializer = HTTPRequestSerializer()
request.requestSerializer.headers["Authorization"] = "token "+token
request.GET("https://api.github.com/user/repos", parameters: nil, completionHandler: {(response: HTTPResponse) in
if let err = response.error {
println("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
if let data = response.responseObject as? NSData {
//let str = NSString(data: data, encoding: NSUTF8StringEncoding)
var repolist = RepoList(JSONDecoder(data))
let dv = DialogViewController(root: self.getRootElement(repolist))
self.navigationController?.presentViewController(dv, animated: true, completion: nil)
}
})
}
func getRootElement(repolist: RepoList) -> RootElement {
let customHeaderLabel = UILabel(frame: CGRect.zeroRect)
customHeaderLabel.autoresizingMask = .FlexibleWidth
customHeaderLabel.text = "Root Elements (+ custom header)"
customHeaderLabel.font = UIFont(name: "AmericanTypewriter-Bold", size: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline).pointSize)
customHeaderLabel.sizeToFit()
customHeaderLabel.textAlignment = .Center
let root = RootElement(
title: "SwiftDialog",
sections: [
SectionElement(header: "列表")
],
groups: [
"apts": 0
]
)
for item in repolist.addresses! {
let se = StringElement(item.name!, onSelect: { element in self.clickMeTapped(item.url!) })
root.sections[0].elements.append(se)
}
return root
}
func clickMeTapped(url:String) {
UIApplication.sharedApplication().openURL(NSURL(string: url)!)
}
func showAlertView(title: String, message: String) {
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return services.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel?.text = services[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
var service: String = services[indexPath.row]
switch service {
case "Twitter":
doOAuthTwitter()
case "Flickr":
doOAuthFlickr()
case "Github":
doOAuthGithub()
default:
println("default (check ViewController tableView)")
}
tableView.deselectRowAtIndexPath(indexPath, animated:true)
}
}
| 41.456311 | 147 | 0.609719 |
8901150f531d1bb5787159e7626df05aa7808a42 | 627 | //
// Configuration.swift
// ISS informations
//
// Created by Craig Josse on 26/06/2020.
// Copyright © 2020 Craig Josse. All rights reserved.
//
import Foundation
enum StatusCode: Int {
case success = 0, error, notUpdated, locationProblem, alreadyUpdated, connectionProblem
}
struct Configuration {
static let scheme = "http"
static let httpMethod = "GET"
static let host = "api.open-notify.org"
static let port = 80
static let slash = "/"
}
struct Endpoints {
static let issPosition = "iss-now.json"
static let peopleInSpace = "astros.json"
static let issPass = "iss-pass.json"
}
| 22.392857 | 91 | 0.685805 |
69835e3b6955e7a819b39e99d322f0d42de79e25 | 193 | import Foundation
import IrohaCrypto
struct ExportMnemonicData {
let account: AccountItem
let mnemonic: IRMnemonicProtocol
let derivationPath: String?
let networkType: Chain
}
| 19.3 | 36 | 0.772021 |
5b9fb7b48a21798f315438356bbd5a5ed7a947c9 | 3,608 | import XCTest
import Combine
@testable import Earnings_Meter
class MeterViewModelTests: XCTestCase {
private var cancelBag = Set<AnyCancellable>()
func testCurrentReading() throws {
let calendar = Calendar.iso8601(in: .london)
let fakeNow_10_00_AM = calendar.date(from: .init(year: 2020, month: 7, day: 21, hour: 10, minute: 0))!
let fakeNow_11_00_AM = calendar.date(from: .init(year: 2020, month: 7, day: 21, hour: 11, minute: 0))!
var fakeTimeNow = fakeNow_10_00_AM
var environment = AppEnvironment.unitTest
environment.date = { fakeTimeNow }
environment.currentCalendar = { calendar }
environment.formatters.dateStyles.shortTime = .testShortTimeStyle
// Given
let appViewModel = AppViewModel(meterSettings: .fake(ofType: .day_worker_0900_to_1700),
environment: environment)
// When
let meterViewModel = MeterViewModel()
meterViewModel.inputs.environmentObjects.send(appViewModel)
// Then
XCTAssertEqual("meter-background", meterViewModel.backgroundImage)
XCTAssertEqual("meter.header.earnings.today.title", meterViewModel.headerTextKey)
XCTAssertEqual("09:00", meterViewModel.progressBarStartTimeText)
XCTAssertEqual("17:00", meterViewModel.progressBarEndTimeText)
XCTAssertEqual(50, meterViewModel.currentReading.amountEarned)
XCTAssertEqual(1/8, meterViewModel.currentReading.progress)
XCTAssertEqual(.atWork, meterViewModel.currentReading.status)
// ... start the meter around 11am (reading should update)
meterViewModel.inputs.appear.send() // Starts the meter
fakeTimeNow = fakeNow_11_00_AM
let expectedReading = expectation(description: "updatedReading")
meterViewModel.$currentReading.dropFirst()
.sink { _ in expectedReading.fulfill() }
.store(in: &cancelBag)
wait(for: [expectedReading], timeout: 1.0)
XCTAssertEqual(100, meterViewModel.currentReading.amountEarned)
XCTAssertEqual(2/8, meterViewModel.currentReading.progress)
XCTAssertEqual(.atWork, meterViewModel.currentReading.status)
}
func testTapSettings() {
let calendar = Calendar.iso8601()
let fakeNow_10_00_AM = calendar.date(from: .init(year: 2020, month: 7, day: 21, hour: 10, minute: 0))!
let fakeTimeNow = fakeNow_10_00_AM
var environment = AppEnvironment.unitTest
environment.date = { fakeTimeNow }
environment.currentCalendar = { calendar }
environment.formatters.dateStyles.shortTime = .testShortTimeStyle
// Given
let appViewModel = AppViewModel(meterSettings: .fake(ofType: .day_worker_0900_to_1700),
environment: environment)
// When
let tappedSettingsOutputAction = expectation(description: "tappedSettingsOutputAction")
let meterViewModel = MeterViewModel()
meterViewModel.inputs.environmentObjects.send(appViewModel)
meterViewModel
.outputActions
.didTapSettings
.sink { _ in tappedSettingsOutputAction.fulfill() }
.store(in: &cancelBag)
meterViewModel.inputs.appear.send()
meterViewModel.inputs.tapSettingsButton.send()
// Then
wait(for: [tappedSettingsOutputAction], timeout: 1.0)
}
}
| 39.648352 | 110 | 0.644956 |
bb4352b11ad9c66f74f00c7a9709328d5e6084cf | 7,203 | //
// AppDelegate.swift
// Pock
//
// Created by Pierluigi Galdi on 08/09/17.
// Copyright © 2017 Pierluigi Galdi. All rights reserved.
//
import Cocoa
import Defaults
import Preferences
import Fabric
import Crashlytics
import Magnet
@_exported import PockKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
static var `default`: AppDelegate {
return NSApp.delegate as! AppDelegate
}
/// Core
fileprivate var _navController: PKTouchBarNavController?
var navController: PKTouchBarNavController? { return _navController }
/// Timer
fileprivate var automaticUpdatesTimer: Timer?
/// Status bar Pock icon
fileprivate let pockStatusbarIcon = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
/// Preferences
fileprivate let generalPreferencePane: GeneralPreferencePane = GeneralPreferencePane()
fileprivate let dockWidgetPreferencePane: DockWidgetPreferencePane = DockWidgetPreferencePane()
fileprivate let statusWidgetPreferencePane: StatusWidgetPreferencePane = StatusWidgetPreferencePane()
fileprivate let controlCenterWidgetPreferencePane: ControlCenterWidgetPreferencePane = ControlCenterWidgetPreferencePane()
fileprivate let nowPlayingWidgetPreferencePane: NowPlayingPreferencePane = NowPlayingPreferencePane()
fileprivate var preferencesWindowController: PreferencesWindowController!
/// Finish launching
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
NSApp.isAutomaticCustomizeTouchBarMenuItemEnabled = true
/// Initialize Crashlytics
if isProd {
UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true])
Fabric.with([Crashlytics.self])
}
/// Check for accessibility (needed for badges to work)
self.checkAccessibility()
/// Preferences
self.preferencesWindowController = PreferencesWindowController(preferencePanes: [
generalPreferencePane,
dockWidgetPreferencePane,
statusWidgetPreferencePane,
controlCenterWidgetPreferencePane,
nowPlayingWidgetPreferencePane
])
/// Check for status bar icon
if let button = pockStatusbarIcon.button {
button.image = NSImage(named: "pock-inner-icon")
button.image?.isTemplate = true
/// Create menu
let menu = NSMenu(title: "Pock Options")
menu.addItem(withTitle: "Preferences…".localized, action: #selector(openPreferences), keyEquivalent: ",")
menu.addItem(withTitle: "Customize…".localized, action: #selector(openCustomization), keyEquivalent: "c")
menu.addItem(NSMenuItem.separator())
menu.addItem(withTitle: "Support this project".localized, action: #selector(openDonateURL), keyEquivalent: "s")
menu.addItem(NSMenuItem.separator())
menu.addItem(withTitle: "Quit Pock".localized, action: #selector(NSApp.terminate), keyEquivalent: "q")
pockStatusbarIcon.menu = menu
}
/// Check for updates
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { [weak self] in
self?.checkForUpdates()
})
/// Register for notification
NSWorkspace.shared.notificationCenter.addObserver(self,
selector: #selector(toggleAutomaticUpdatesTimer),
name: .shouldEnableAutomaticUpdates,
object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self,
selector: #selector(reloadPock),
name: .shouldReloadPock,
object: nil)
toggleAutomaticUpdatesTimer()
registerGlobalHotKey()
/// Present Pock
self.reloadPock()
/// Set Pock inactive
NSApp.deactivate()
///Reload Control Center Widget every 1 second in order to sync volume item icon with system
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(reloadControlCenterWidget), userInfo: nil, repeats: true)
}
@objc func reloadControlCenterWidget() {
NSWorkspace.shared.notificationCenter.post(name: .shouldReloadControlCenterWidget, object: nil)
}
@objc func reloadPock() {
_navController?.dismiss()
_navController = nil
let mainController: PockMainController = PockMainController.load()
_navController = PKTouchBarNavController(rootController: mainController)
}
private func registerGlobalHotKey() {
if let keyCombo = KeyCombo(doubledCocoaModifiers: .control) {
let hotKey = HotKey(identifier: "TogglePock", keyCombo: keyCombo) { [weak self] _ in
self?._navController?.toggle()
}
hotKey.register()
}
}
@objc private func toggleAutomaticUpdatesTimer() {
if Defaults[.enableAutomaticUpdates] {
automaticUpdatesTimer = Timer.scheduledTimer(timeInterval: 86400 /*24h*/, target: self, selector: #selector(checkForUpdates), userInfo: nil, repeats: true)
}else {
automaticUpdatesTimer?.invalidate()
automaticUpdatesTimer = nil
}
}
/// Will terminate
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
_navController?.dismiss()
_navController = nil
}
/// Check for updates
@objc private func checkForUpdates() {
generalPreferencePane.hasLatestVersion(completion: { [weak self] versionNumber, downloadURL in
guard let versionNumber = versionNumber, let downloadURL = downloadURL else { return }
self?.generalPreferencePane.newVersionAvailable = (versionNumber, downloadURL)
DispatchQueue.main.async { [weak self] in
self?.openPreferences()
}
})
}
/// Check for accessibility
@discardableResult
private func checkAccessibility() -> Bool {
let checkOptPrompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString
let options = [checkOptPrompt: true]
let accessEnabled = AXIsProcessTrustedWithOptions(options as CFDictionary?)
return accessEnabled
}
/// Open preferences
@objc private func openPreferences() {
preferencesWindowController.show()
}
@objc private func openCustomization() {
(_navController?.rootController as? PockMainController)?.openCustomization()
}
@objc private func openDonateURL() {
guard let url = URL(string: "https://paypal.me/pigigaldi") else { return }
NSWorkspace.shared.open(url)
}
}
| 40.240223 | 167 | 0.642649 |
fc56198007e47c33210762a0b2f19768d3b285a4 | 7,874 | //
// SetPlayerName.swift
// Nostalgia
//
// Created by Vincenzo Ajello on 06/03/18.
// Copyright © 2018 mskaline. All rights reserved.
//
import UIKit
class SetPlayerName: UIView, SKJoystickDelegate
{
let letters:[String] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","U","R","S","T","U","V","W","X","Y","Z"]
var labels:[UILabel] = []
var currentLabelIndex = 0
var latestInputTime = NSDate().timeIntervalSince1970
var scoreLabel:UILabel!
var score:Int!
var delegate:GameEventDelegate!
override init(frame: CGRect)
{
super.init(frame:frame)
let gameOverLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 160, height: 40))
gameOverLabel.center = CGPoint.init(x: self.center.x, y: self.center.y - 80)
gameOverLabel.font = UIFont.init(name: "Pixel-Art", size: 28)
gameOverLabel.backgroundColor = UIColor.clear
gameOverLabel.textAlignment = NSTextAlignment.center
gameOverLabel.textColor = UIColor.white
gameOverLabel.adjustsFontSizeToFitWidth = true
gameOverLabel.text = "game over !"
self.addSubview(gameOverLabel)
let firstLetter = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 40, height: 40))
firstLetter.center = CGPoint.init(x: self.center.x-42, y: self.center.y-10)
firstLetter.font = UIFont.init(name: "Pixel-Art", size: 38)
firstLetter.backgroundColor = UIColor.clear
firstLetter.textAlignment = NSTextAlignment.right
firstLetter.textColor = UIColor.white
firstLetter.adjustsFontSizeToFitWidth = true
firstLetter.text = "A"
self.addSubview(firstLetter)
let secondLetter = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 35, height: 40))
secondLetter.center = CGPoint.init(x: self.center.x, y: self.center.y-10)
secondLetter.font = UIFont.init(name: "Pixel-Art", size: 38)
secondLetter.backgroundColor = UIColor.clear
secondLetter.textAlignment = NSTextAlignment.center
secondLetter.textColor = UIColor.white
secondLetter.adjustsFontSizeToFitWidth = true
secondLetter.text = "A"
self.addSubview(secondLetter)
let thirdLetter = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 40, height: 40))
thirdLetter.center = CGPoint.init(x: self.center.x+42, y: self.center.y-10)
thirdLetter.font = UIFont.init(name: "Pixel-Art", size: 38)
thirdLetter.backgroundColor = UIColor.clear
thirdLetter.textAlignment = NSTextAlignment.left
thirdLetter.adjustsFontSizeToFitWidth = true
thirdLetter.textColor = UIColor.white
thirdLetter.text = "A"
self.addSubview(thirdLetter)
let endLetter = UILabel.init(frame: CGRect.init(x: 0, y: 0, width:43, height:20))
endLetter.center = CGPoint.init(x: self.center.x+87, y: self.center.y-2)
endLetter.font = UIFont.init(name: "Pixel-Art", size: 18)
endLetter.backgroundColor = UIColor.clear
endLetter.textAlignment = NSTextAlignment.left
endLetter.textColor = UIColor.white
endLetter.text = "end"
self.addSubview(endLetter)
let yourScoreLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 160, height: 40))
yourScoreLabel.center = CGPoint.init(x: self.center.x, y: self.center.y + 50)
yourScoreLabel.font = UIFont.init(name: "Pixel-Art", size: 16)
yourScoreLabel.backgroundColor = UIColor.clear
yourScoreLabel.textAlignment = NSTextAlignment.center
yourScoreLabel.textColor = UIColor.white
yourScoreLabel.adjustsFontSizeToFitWidth = true
yourScoreLabel.text = "your score:"
self.addSubview(yourScoreLabel)
scoreLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 160, height: 40))
scoreLabel.center = CGPoint.init(x: self.center.x, y: self.center.y + 70)
scoreLabel.font = UIFont.init(name: "Pixel-Art", size: 22)
scoreLabel.backgroundColor = UIColor.clear
scoreLabel.textAlignment = NSTextAlignment.center
scoreLabel.textColor = UIColor.white
scoreLabel.adjustsFontSizeToFitWidth = true
self.addSubview(scoreLabel)
labels.append(firstLetter)
labels.append(secondLetter)
labels.append(thirdLetter)
labels.append(endLetter)
selectLabel(label: firstLetter)
}
//
// MARK : JOYSTICK DELEGATE METHODS
//
func joystickUpdatedDirection(sender: AnyObject)
{
guard let stick = sender as? SKJoystick else { return }
let now = NSDate().timeIntervalSince1970
if (latestInputTime + 1) >= now {return}
latestInputTime = now
let dir = stick.direction
if dir == Sense.RIGHT
{
self.goToNextLabel()
}
if dir == Sense.LEFT
{
self.goToPrevLabel()
}
if dir == Sense.UP
{
self.goToPrevLetter()
}
if dir == Sense.DOWN
{
self.goToNextLetter()
}
}
func joystickReleased(sender: AnyObject)
{
latestInputTime = 0
}
func joystickButtonPressed(sender: AnyObject)
{
if (self.labels.count - 1) == self.currentLabelIndex
{
let userName = self.getCurrentName()
guard let _ = delegate?.savePlayerScore(points: score, nickName: userName) else { return }
}
else
{
self.goToNextLabel()
}
}
//
// MARK : UTILITY METHODS
//
func goToNextLetter()
{
changeLetter(mod:1)
}
func goToPrevLetter()
{
changeLetter(mod:-1)
}
func goToNextLabel()
{
changeLabel(mod:1)
}
func goToPrevLabel()
{
changeLabel(mod:-1)
}
func changeLabel(mod:Int)
{
currentLabelIndex = currentLabelIndex + mod
if currentLabelIndex < 0 { currentLabelIndex = labels.count-1 }
if currentLabelIndex > labels.count - 1 { currentLabelIndex = 0 }
let label = labels[currentLabelIndex]
selectLabel(label: label)
}
func changeLetter(mod:Int)
{
let currentLabel = labels[currentLabelIndex]
guard let currentLetter = currentLabel.text else {return}
guard let currentIndex = letters.index(of: currentLetter) else {return}
var newIndex = currentIndex + mod
if newIndex < 0 { newIndex = letters.count - 1 }
if newIndex > letters.count - 1 { newIndex = 0 }
let newLetter = letters[newIndex]
currentLabel.text = newLetter
}
func selectLabel(label:UILabel)
{
removeAllAnimations()
UIView.animate(withDuration: TimeInterval(0.8), delay: 0, options: [.repeat], animations:
{
label.alpha = 0.5
},
completion:
{
(completed) in
print("button animation stops")
})
}
func removeAllAnimations()
{
for label in labels
{
label.layer.removeAllAnimations()
label.alpha = 1.0
}
}
func getCurrentName() -> String
{
var currentName = ""
for label in labels
{
guard let l = label.text else { break }
if l == "end" {break}
currentName = "\(currentName)\(l)"
}
return currentName
}
func setScore(score:Int)
{
self.score = score
self.scoreLabel.text = "\(score)"
}
required init?(coder aDecoder: NSCoder)
{super.init(coder: aDecoder)}
}
| 31.496 | 136 | 0.595631 |
f8005ef7862fa30b81fb05041205af03b2cad7cb | 1,110 | //
// Changes.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-02-11.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
public typealias Changes1MDB = (id:Double, adult:Bool?)
public struct ChangesMDB{
public var id: Int64!
public var adult: Bool!
public init(results: JSON){
id = results["id"].int64
adult = results["adult"].bool
}
static func initReturn(_ json: JSON)->[ChangesMDB]{
var changes = [ChangesMDB]()
for i in 0 ..< json.count {
changes.append(ChangesMDB(results: json[i]))
}
return changes
}
public static func changes(changeType: String, page: Double?, startDate: String? = nil, endDate:String? = nil, completionHandler: @escaping (_ clientReturn: ClientReturn, _ data: [ChangesMDB]?) -> ()) -> (){
Client.Changes(changeType: "movie", page: 1, startDate: nil, endDate: nil){
apiReturn in
var changes: [ChangesMDB]?
if(apiReturn.error == nil){
changes = ChangesMDB.initReturn(apiReturn.json!["results"])
}
completionHandler(apiReturn, changes)
}
}
}
| 24.666667 | 208 | 0.651351 |
8a83fa360eb3b4d6bf33d9ef1c9481c3d93bbdd4 | 136 | import UIKit
struct AccountInfoViewModel {
let title: String
let address: String
let name: String
let icon: UIImage?
}
| 15.111111 | 29 | 0.691176 |
62ea861488b9c7840a4ce048191abc487dfb4134 | 916 | //
// TreeTraverse.swift
// algoritm
//
// Created by xuwenquan on 2018/9/18.
// Copyright © 2018年 Qiaobangzhu. All rights reserved.
//
import Foundation
public typealias GetChildrensCallback = (Any) -> [Any]
public typealias DoSomethingCallBack = (Any) -> Bool // return true if should stop
@objc open class TreeTraverse : NSObject {
@objc open class func dfs_inorder( _ root : Any? , _ getChildsClosure : GetChildrensCallback , _ doSomethingClosure: DoSomethingCallBack ) -> Bool {
if let node = root {
if doSomethingClosure(node) {
return true
}
let childs = getChildsClosure( node )
for child in childs {
if dfs_inorder( child , getChildsClosure , doSomethingClosure ) {
return true
}
}
}
return false
}
}
| 26.171429 | 154 | 0.575328 |
224c604bde364888e96755ae57a3b205136991ef | 1,829 | //
// String + toDuration.swift
//
// Copyright (c) 2017 Ben Murphy
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
extension String {
/// Convert the string representation of a time duration to a Time Interval.
///
/// - Returns: A TimeInterval.
func toDuration() -> TimeInterval? {
let comps = self.components(separatedBy: ":")
guard
!comps.contains(where: { Int($0) == nil }),
!comps.contains(where: { Int($0)! < 0 })
else { return nil }
return comps
.reversed()
.enumerated()
.map { i, e in
(Double(e) ?? 0)
*
pow(Double(60), Double(i))
}
.reduce(0, +)
}
}
| 34.509434 | 82 | 0.642428 |
e0728615613415e675113f0d52488828498b04c1 | 265 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol C {
class d: e!.init()
typealias e : d {
| 26.5 | 87 | 0.728302 |
11e722b9a24d406b3a103f5e4d72bf3823f92169 | 657 | import Vapor
extension Droplet {
func setupRoutes() throws {
get("hello") { req in
var json = JSON()
try json.set("hello", "world")
return json
}
get("plaintext") { req in
return "Hello, world!"
}
// response to requests to /info domain
// with a description of the request
get("info") { req in
return req.description
}
get("description") { req in return req.description }
try resource("scanSwitch", ScanSwitchController.self)
try resource("measurements", MeasurementController.self)
}
}
| 24.333333 | 64 | 0.543379 |
d7ba691758a6a217a9faf1955f3f70dea26195d0 | 1,166 | //
// LogEntry.swift
//
//
// Created by Martin Troup on 29.09.2021.
//
import Foundation
struct LogEntry {
let level: Level
let timestamp: Double
let message: String
let sessionID: UUID
}
// MARK: - LogEntry + Encodable
extension LogEntry: Encodable {
enum CodingKeys: String, CodingKey {
case level = "severity"
case timestamp
case message
case sessionID = "sessionName"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(serverLevelName(for: level), forKey: .level)
try container.encode(timestamp, forKey: .timestamp)
try container.encode(message, forKey: .message)
try container.encode(sessionID.uuidString, forKey: .sessionID)
}
private func serverLevelName(for level: Level) -> String {
switch level {
case .warn:
return "WARNING"
case .system, .process:
return "INFO"
default:
return level.rawValue.uppercased()
}
}
}
// MARK: - LogEntryBatch
typealias LogEntryBatch = Array<LogEntry>
| 23.32 | 73 | 0.629503 |
ac6bd3eab57f91e2d76e65d166d2101666fedcb9 | 6,273 | /*
SwiftTaggerID3_ComplexTypesFrame_Tests.swift
SwiftTaggerID3
Copyright ©2020 Nolaine Crusher. All rights reserved.
*/
import XCTest
@testable import SwiftTaggerID3
class SwiftTaggerID3_ComplexTypesFrame_Tests: XCTestCase {
func testPresetOptionsReadingV24() throws {
let tag = tagV24
XCTAssertNil(tag.fileType.fileType)
XCTAssertNil(tag.fileType.fileTypeRefinement)
XCTAssertEqual(tag.fileType.additionalInformation, "File Type")
XCTAssertEqual(tag.genre.genreCategory, .Audiobook)
XCTAssertEqual(tag.genre.genre, "Genre Type")
XCTAssertNil(tag.mediaType.mediaType)
XCTAssertNil(tag.mediaType.mediaTypeRefinement)
XCTAssertEqual(tag.mediaType.additionalInformation, "Media Type")
}
func testPresetOptionsReadingV23() throws {
let tag = tagV23
XCTAssertNil(tag.fileType.fileType)
XCTAssertNil(tag.fileType.fileTypeRefinement)
XCTAssertEqual(tag.fileType.additionalInformation, "File Type")
XCTAssertEqual(tag.genre.genreCategory, .Audiobook)
XCTAssertEqual(tag.genre.genre, "Genre Type")
XCTAssertNil(tag.mediaType.mediaType)
XCTAssertNil(tag.mediaType.mediaTypeRefinement)
XCTAssertEqual(tag.mediaType.additionalInformation, "Media Type")
}
func testPresetOptionsReadingV22() throws {
let tag = tagV22
XCTAssertNil(tag.fileType.fileType)
XCTAssertNil(tag.fileType.fileTypeRefinement)
XCTAssertEqual(tag.fileType.additionalInformation, "File Type")
XCTAssertEqual(tag.genre.genreCategory, .Audiobook)
XCTAssertEqual(tag.genre.genre, "Genre Type")
XCTAssertNil(tag.mediaType.mediaType)
XCTAssertNil(tag.mediaType.mediaTypeRefinement)
XCTAssertEqual(tag.mediaType.additionalInformation, "Media Type")
}
func testPresetOptionsWriting() throws {
var tag = tagNoMeta
tag.genre.genreCategory = .Blues
tag.genre.genre = "Blues Refinement"
tag.mediaType.mediaType = .otherDigital
tag.mediaType.mediaTypeRefinement = .analogTransfer
tag.mediaType.additionalInformation = "Additional Information"
tag.fileType.fileType = .MPG
tag.fileType.fileTypeRefinement = .mpegLayerIII
tag.fileType.additionalInformation = "Additional Information"
let outputUrl = tempOutputDirectory
XCTAssertNoThrow(try mp3NoMeta.write(tag: &tag, version: .v2_4, outputLocation: outputUrl))
let outputMp3 = try Mp3File(location: outputUrl)
let output = try Tag(mp3File: outputMp3)
XCTAssertEqual(output.genre.genreCategory, .Blues)
XCTAssertEqual(output.genre.genre, "Blues Refinement")
XCTAssertEqual(output.mediaType.mediaType, .otherDigital)
XCTAssertEqual(output.mediaType.mediaTypeRefinement, .analogTransfer)
XCTAssertEqual(output.mediaType.additionalInformation, "Additional Information")
XCTAssertEqual(output.fileType.fileType, .MPG)
XCTAssertEqual(output.fileType.fileTypeRefinement, .mpegLayerIII)
XCTAssertEqual(output.fileType.additionalInformation, "Additional Information")
}
func testPresetOptionsOverWriting() throws {
var tag = tagV24
tag.genre.genreCategory = .Blues
tag.genre.genre = "Blues Refinement"
tag.mediaType.mediaType = .otherDigital
tag.mediaType.mediaTypeRefinement = .analogTransfer
tag.mediaType.additionalInformation = "Additional Information"
tag.fileType.fileType = .MPG
tag.fileType.fileTypeRefinement = .mpegLayerIII
tag.fileType.additionalInformation = "Additional Information"
let outputUrl = tempOutputDirectory
XCTAssertNoThrow(try mp3NoMeta.write(tag: &tag, version: .v2_4, outputLocation: outputUrl))
let outputMp3 = try Mp3File(location: outputUrl)
let output = try Tag(mp3File: outputMp3)
XCTAssertEqual(output.genre.genreCategory, .Blues)
XCTAssertEqual(output.genre.genre, "Blues Refinement")
XCTAssertEqual(output.mediaType.mediaType, .otherDigital)
XCTAssertEqual(output.mediaType.mediaTypeRefinement, .analogTransfer)
XCTAssertEqual(output.mediaType.additionalInformation, "Additional Information")
XCTAssertEqual(output.fileType.fileType, .MPG)
XCTAssertEqual(output.fileType.fileTypeRefinement, .mpegLayerIII)
XCTAssertEqual(output.fileType.additionalInformation, "Additional Information")
}
func testSetToNil() throws {
var tag = tagV24
tag.genre.genreCategory = nil
tag.genre.genre = nil
tag.mediaType.mediaType = nil
tag.mediaType.mediaTypeRefinement = nil
tag.mediaType.additionalInformation = nil
tag.fileType.fileType = nil
tag.fileType.fileTypeRefinement = nil
tag.fileType.additionalInformation = nil
XCTAssertNil(tag.frames.first(where: {$0.key == .genre}))
XCTAssertNil(tag.frames.first(where: {$0.key == .mediaType}))
XCTAssertNil(tag.frames.first(where: {$0.key == .fileType}))
let outputUrl = tempOutputDirectory
XCTAssertNoThrow(try mp3NoMeta.write(tag: &tag, version: .v2_4, outputLocation: outputUrl))
let outputMp3 = try Mp3File(location: outputUrl)
let output = try Tag(mp3File: outputMp3)
XCTAssertNil(output.genre.genreCategory)
XCTAssertNil(output.genre.genre)
XCTAssertNil(output.mediaType.mediaType)
XCTAssertNil(output.mediaType.mediaTypeRefinement)
XCTAssertNil(output.mediaType.additionalInformation)
XCTAssertNil(output.fileType.fileType)
XCTAssertNil(output.fileType.fileTypeRefinement)
XCTAssertNil(output.fileType.additionalInformation)
XCTAssertNil(output.frames.first(where: {$0.key == .genre}))
XCTAssertNil(output.frames.first(where: {$0.key == .mediaType}))
XCTAssertNil(output.frames.first(where: {$0.key == .fileType}))
}
}
| 39.955414 | 99 | 0.68468 |
f8ec7e15c2185d066c4412edbd5d1071154e1fee | 3,242 | //
// Experiment.swift
// PlanoutKit
//
// Created by David Christiandy on 29/07/19.
// Copyright © 2019 Traveloka. All rights reserved.
//
import Foundation
/// Represents an instance of an experiment.
///
/// An experiment has unique (within its namespace) name and reference to experiment definition.
class Experiment {
/// The Experiment "blueprint" used for this instance.
let definition: ExperimentDefinition
/// Represents the experiment instance name.
let name: String
/// Experiment salt.
let salt: String
// Flag whether a unit has been assigned to this experiment.
private var exposureLogged: Bool = false
// Private interpreter instance to forward ReadableAssignments method calls.
private var _interpreter: Interpreter?
required init(_ definition: ExperimentDefinition, name: String, salt: String) {
self.definition = definition
self.name = name
self.salt = salt
}
/// Assigns unit to an experiment.
///
/// - Parameters:
/// - unit: The unit model to be assigned to.
/// - logger: Exposure logger instance.
/// - Throws: OperationError
func assign(_ unit: Unit, logger: PlanOutLogger) throws {
// return immediately if interpreter already exists.
if let _ = _interpreter {
return
}
let interpreter = Interpreter(serialization: self.definition.script, salt: salt, unit: unit)
// evaluate the experiment.
try interpreter.evaluateExperiment()
// store the interpreter for later, (i.e. forwarding ReadableAssignment methods to the interpreter).
self._interpreter = interpreter
// do not log if the unit is exposed to a default experiment.
guard !definition.isDefaultExperiment else { return }
logExposureIfNeeded(with: logger, interpreter: interpreter)
}
/// Logs exposure data.
///
/// The exposure will only be logged once per experiment assignment. It is also overridable depending on interpreter's assignment results; for example, if the evaluation throws an `OperationError.stop` with boolean flag set to `false`, this means that the exposure will never be logged for this unit.
///
/// - Parameters:
/// - logger: Object responsible for logging.
/// - interpreter: The evaluated interpreter, which contains assigned parameters and inputs.
func logExposureIfNeeded(with logger: PlanOutLogger, interpreter: Interpreter) {
guard interpreter.shouldLogExposure, !exposureLogged, let params = try? interpreter.getParams() else {
return
}
let log = ExposureLog(experiment: self, inputs: interpreter.inputs, params: params)
logger.logExposure(log)
exposureLogged = true
}
}
extension Experiment: ReadableAssignment {
public func get(_ name: String) throws -> Any? {
return try self._interpreter?.get(name)
}
public func get<T>(_ name: String, defaultValue: T) throws -> T {
return try self._interpreter?.get(name, defaultValue: defaultValue) ?? defaultValue
}
public func getParams() throws -> [String: Any] {
return try self._interpreter?.getParams() ?? [:]
}
}
| 34.489362 | 304 | 0.676743 |
2ffa04fb291d4c607ca73a53e9fc0eaa810254fe | 24,300 | //
// RangeConverter.swift
// StringEx
//
// Created by Andrey Golovchak on 01/07/2020.
// Copyright © 2020 Andrew Golovchak. All rights reserved.
//
import Foundation
public enum RangeConversionMode {
case inner
case outer
}
class RangeConverter {
private var storage: HTMLTagStorage
private var resultStringCount: Int
private var rawStringCount: Int
private var lowerBound = 0
private var upperBound = 0
private var lowerBoundFound = false
private var upperBoundFound = false
private var result: SelectorResult!
private var resultTagPair: HTMLTagPair!
private var startTagPosition: Int!
private var endTagPosition: Int!
private var rawRange: Range<Int>!
private var mode: RangeConversionMode = .outer
var range: Range<Int>? {
if lowerBound <= upperBound {
return lowerBound..<upperBound
}
return nil
}
init(storage: HTMLTagStorage, resultStringCount: Int, rawStringCount: Int) {
self.storage = storage
self.resultStringCount = resultStringCount
self.rawStringCount = rawStringCount
}
func convert(_ result: SelectorResult, mode: RangeConversionMode) -> Range<Int>? {
self.result = result
self.mode = mode
if storage.count == 0 {
return convertExactRange()
}
lowerBoundFound = false
upperBoundFound = false
if let resultTagPair = result.tag, let startTagPosition = resultTagPair.startTag.position, let endTagPosition = resultTagPair.endTag.position, let rawRange = resultTagPair.rawRange {
self.resultTagPair = resultTagPair
self.startTagPosition = startTagPosition
self.endTagPosition = endTagPosition
self.rawRange = rawRange
// Empty tag selection <span />: .tag("span")
if result.range.lowerBound == startTagPosition && result.range.upperBound == endTagPosition && startTagPosition == endTagPosition {
return convertEmptyTagSelection()
}
// Entire tag selection: .tag("span")
if result.range.lowerBound == startTagPosition && result.range.upperBound == endTagPosition {
return convertEntireSelection(tagPair: resultTagPair)
}
// Prepend to tag: .tag("span") => .range(0..<0)
if result.range.lowerBound == startTagPosition && result.range.upperBound == startTagPosition {
return convertPrepend(tagPair: resultTagPair)
}
// Append to tag: .tag("span") => .range(Int.max..<Int.max)
if result.range.lowerBound == endTagPosition && result.range.upperBound == endTagPosition {
return convertAppend(tagPair: resultTagPair)
}
// Left side selection: .tag("span") => .range(0..<5)
if result.range.lowerBound == startTagPosition && result.range.upperBound < endTagPosition {
return convertLeftSideSelection(tagPair: resultTagPair)
}
// Right side selection: .tag("span") => .range(5..<Int.max)
if result.range.lowerBound > startTagPosition && result.range.upperBound == endTagPosition {
return convertRightSideSelection(tagPair: resultTagPair)
}
// Insert to tag: .tag("span") => .range(5..<5)
if result.range.lowerBound > startTagPosition && result.range.upperBound < endTagPosition && result.range.lowerBound == result.range.upperBound {
return convertInsertion(tagPair: resultTagPair)
}
// Inner selection: .tag("span") => .range(5..<6)
if result.range.lowerBound > startTagPosition && result.range.upperBound < endTagPosition {
return convertSelection(tagPair: resultTagPair)
}
} else {
// Entire selection
if result.range.lowerBound == 0 && result.range.upperBound == resultStringCount {
return convertEntireSelection()
}
// Prepend
if result.range.lowerBound == 0 && result.range.upperBound == 0 {
return convertPrepend()
}
// Append
if result.range.lowerBound == resultStringCount && result.range.upperBound == resultStringCount {
return convertAppend()
}
// Left side selection
if result.range.lowerBound == 0 && result.range.upperBound < resultStringCount {
return convertLeftSideSelection()
}
// Right side selection
if result.range.lowerBound > 0 && result.range.upperBound == resultStringCount {
return convertRightSideSelection()
}
// Insertion
if result.range.lowerBound == result.range.upperBound {
return convertInsertion()
}
// Inner selection
return convertSelection()
}
return nil
}
}
extension RangeConverter {
private func convertExactRange() -> Range<Int>? {
return result.range
}
private func convertEmptyTagSelection() -> Range<Int>? {
lowerBound = rawRange.lowerBound
upperBound = rawRange.upperBound
if mode == .inner {
var innerTags = [HTMLTag]()
storage.forEachTag(in: resultTagPair) { (tag, _, _) -> Bool in
innerTags.append(tag)
return true
}
let count = innerTags.count
if count > 0 {
for (index, tag) in innerTags.enumerated() {
if tag is HTMLStartTag {
if let siblingTag = tag.siblingTag, let lowerBound = tag.rawRange?.upperBound, let upperBound = siblingTag.rawRange?.lowerBound {
if siblingTag === innerTags[count - index - 1] {
self.lowerBound = lowerBound
self.upperBound = upperBound
} else {
break
}
}
} else {
break
}
}
}
}
return range
}
private func convertEntireSelection(tagPair: HTMLTagPair? = nil) -> Range<Int>? {
switch mode {
case .outer:
if tagPair == nil {
lowerBound = 0
upperBound = rawStringCount
} else {
lowerBound = rawRange.lowerBound
upperBound = rawRange.upperBound
}
case .inner:
if tagPair == nil {
lowerBound = 0
upperBound = result.range.upperBound
} else {
lowerBound = rawRange.lowerBound
upperBound = lowerBound + result.range.count
}
storage.forEachTag(in: tagPair) { (tag, position, _) -> Bool in
// Lower bound
if position == result.range.lowerBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition > result.range.lowerBound && siblingPosition < result.range.upperBound {
lowerBoundFound = true
}
}
} else {
lowerBoundFound = true
}
if !lowerBoundFound {
lowerBound += tag.length
}
// Upper bound
if position == result.range.upperBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition == result.range.lowerBound || siblingPosition == result.range.upperBound {
upperBoundFound = true
}
}
}
if !upperBoundFound {
upperBound += tag.length
}
return !lowerBoundFound || !upperBoundFound
}
}
return range
}
private func convertPrepend(tagPair: HTMLTagPair? = nil) -> Range<Int>? {
if tagPair == nil {
lowerBound = 0
} else {
lowerBound = rawRange.lowerBound
}
if mode == .inner {
storage.forEachTag(in: tagPair) { (tag, position, _) -> Bool in
if position == result.range.lowerBound {
lowerBound += tag.length
return true
}
return false
}
}
upperBound = lowerBound
return range
}
private func convertAppend(tagPair: HTMLTagPair? = nil) -> Range<Int>? {
if tagPair == nil {
upperBound = rawStringCount
} else {
upperBound = rawRange.upperBound
}
if mode == .inner {
storage.forEachTag(in: tagPair) { (tag, position, _) -> Bool in
if position == result.range.upperBound {
upperBound -= tag.length
}
return true
}
}
lowerBound = upperBound
return range
}
private func convertLeftSideSelection(tagPair: HTMLTagPair? = nil) -> Range<Int>? {
if tagPair == nil {
lowerBound = 0
upperBound = result.range.upperBound
} else {
lowerBound = rawRange.lowerBound
upperBound = lowerBound + result.range.count
}
storage.forEachTag(in: tagPair) { (tag, position, _) -> Bool in
switch mode {
case .outer:
// Lower bound
if position == result.range.lowerBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition >= result.range.lowerBound && siblingPosition <= result.range.upperBound {
lowerBoundFound = true
}
}
} else {
lowerBoundFound = true
}
if !lowerBoundFound {
lowerBound += tag.length
}
// Upper bound
if position > result.range.upperBound {
upperBoundFound = true
} else if position == result.range.upperBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition > result.range.upperBound {
upperBoundFound = true
}
}
}
if !upperBoundFound {
upperBound += tag.length
}
case .inner:
// Lower bound
if position == result.range.lowerBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition > result.range.lowerBound && siblingPosition < result.range.upperBound {
lowerBoundFound = true
}
}
} else {
lowerBoundFound = true
}
if !lowerBoundFound {
lowerBound += tag.length
}
// Upper bound
if position == result.range.upperBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition <= result.range.lowerBound || siblingPosition >= result.range.upperBound {
upperBoundFound = true
}
}
} else if position > result.range.upperBound {
upperBoundFound = true
}
if !upperBoundFound {
upperBound += tag.length
}
}
return !lowerBoundFound || !upperBoundFound
}
return range
}
private func convertRightSideSelection(tagPair: HTMLTagPair? = nil) -> Range<Int>? {
if tagPair == nil {
lowerBound = result.range.lowerBound
upperBound = result.range.upperBound
} else {
lowerBound = rawRange.lowerBound - startTagPosition + result.range.lowerBound
upperBound = lowerBound + result.range.count
}
storage.forEachTag(in: tagPair) { (tag, position, tagRange) -> Bool in
switch mode {
case .outer:
// Lower bound
if position > result.range.lowerBound {
lowerBoundFound = true
} else if position < result.range.lowerBound {
lowerBound += tag.length
} else if position == result.range.lowerBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition < result.range.lowerBound {
lowerBound = tagRange.upperBound
}
}
}
// Upper bound
if position == result.range.upperBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition < result.range.lowerBound {
upperBoundFound = true
}
}
}
if !upperBoundFound {
upperBound += tag.length
}
case .inner:
// Lower bound
if position > result.range.lowerBound {
lowerBoundFound = true
} else if position == result.range.lowerBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition > result.range.lowerBound && siblingPosition < result.range.upperBound {
lowerBoundFound = true
}
}
}
if !lowerBoundFound {
lowerBound += tag.length
}
// Upper bound
if position == result.range.upperBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition == result.range.lowerBound || siblingPosition == result.range.upperBound {
upperBoundFound = true
}
}
}
if !upperBoundFound {
upperBound += tag.length
}
}
return !lowerBoundFound || !upperBoundFound
}
return range
}
private func convertInsertion(tagPair: HTMLTagPair? = nil) -> Range<Int>? {
if tagPair == nil {
lowerBound = result.range.lowerBound
} else {
lowerBound = rawRange.lowerBound - startTagPosition + result.range.lowerBound
}
var innerTags = [HTMLTag]()
storage.forEachTag(in: tagPair) { (tag, position, _) -> Bool in
if position == result.range.lowerBound {
innerTags.append(tag)
} else if position < result.range.lowerBound {
lowerBound += tag.length
} else if position > result.range.lowerBound {
return false
}
return true
}
upperBound = lowerBound
var count = innerTags.count
if count > 0 {
switch mode {
case .outer:
for tag in innerTags {
if let siblingTag = tag.siblingTag, let siblingPosition = siblingTag.position, let tagRange = tag.rawRange, let siblingRange = siblingTag.rawRange {
if siblingPosition < result.range.lowerBound {
lowerBound = tagRange.upperBound
upperBound = lowerBound
} else if siblingPosition > result.range.lowerBound {
upperBound = tagRange.lowerBound
break
} else if siblingPosition == result.range.lowerBound && tag is HTMLStartTag {
upperBound = siblingRange.upperBound
}
}
}
case .inner:
var index1 = -1
var index2 = -1
var index3 = -1
var index4 = -1
for (index, tag) in innerTags.enumerated() {
if let siblingTag = tag.siblingTag, let siblingPosition = siblingTag.position {
if siblingPosition < result.range.lowerBound {
if index1 < 0 {
index1 = index
}
index2 = index
} else if siblingPosition > result.range.lowerBound {
if index3 < 0 {
index3 = index
}
index4 = index
}
}
}
if index1 == 0 && index2 == (count - 1) && index4 < 0 {
if let lowerBound = innerTags[index1].rawRange?.lowerBound {
self.lowerBound = lowerBound
self.upperBound = lowerBound
}
} else if index4 == (count - 1) && index3 == 0 && index1 < 0 {
if let upperBound = innerTags[index4].rawRange?.upperBound {
self.lowerBound = upperBound
self.upperBound = upperBound
}
} else if index2 >= 0 && index3 >= 0 && index2 == (index3 - 1) {
if let upperBound = innerTags[index2].rawRange?.upperBound {
self.lowerBound = upperBound
self.upperBound = upperBound
}
} else {
if index1 >= 0 && index4 < 0 {
if index2 == (count - 1) {
innerTags = Array(innerTags[0..<index1])
} else {
innerTags = Array(innerTags[(index2 + 1)..<count])
}
} else if index4 >= 0 && index1 < 0 {
if index3 == 0 {
innerTags = Array(innerTags[(index4 + 1)..<count])
} else {
innerTags = Array(innerTags[0..<index3])
}
} else if index2 >= 0 && index3 >= 0 {
innerTags = Array(innerTags[(index2 + 1)..<index3])
}
count = innerTags.count
for (index, tag) in innerTags.enumerated() {
if tag is HTMLStartTag {
if let siblingTag = tag.siblingTag, let lowerBound = tag.rawRange?.upperBound, let upperBound = siblingTag.rawRange?.lowerBound {
if siblingTag === innerTags[count - index - 1] {
self.lowerBound = lowerBound
self.upperBound = upperBound
} else {
break
}
}
} else {
break
}
}
}
}
}
return range
}
private func convertSelection(tagPair: HTMLTagPair? = nil) -> Range<Int>? {
if tagPair == nil {
lowerBound = result.range.lowerBound
upperBound = result.range.upperBound
} else {
lowerBound = rawRange.lowerBound - startTagPosition + result.range.lowerBound
upperBound = lowerBound + result.range.count
}
storage.forEachTag(in: tagPair) { (tag, position, tagRange) -> Bool in
switch mode {
case .outer:
// Lower bound
if position > result.range.lowerBound {
lowerBoundFound = true
} else if position < result.range.lowerBound {
lowerBound += tag.length
} else if position == result.range.lowerBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition < result.range.lowerBound || siblingPosition > result.range.upperBound {
lowerBound = tagRange.upperBound
}
}
}
// Upper bound
if position > result.range.upperBound {
upperBoundFound = true
} else if position == result.range.upperBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition < result.range.lowerBound || siblingPosition > result.range.upperBound {
upperBoundFound = true
}
}
}
if !upperBoundFound {
upperBound += tag.length
}
case .inner:
// Lower bound
if position > result.range.lowerBound {
lowerBoundFound = true
} else if position == result.range.lowerBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition > result.range.lowerBound && siblingPosition < result.range.upperBound {
lowerBoundFound = true
}
}
}
if !lowerBoundFound {
lowerBound += tag.length
}
// Upper bound
if position > result.range.upperBound {
upperBoundFound = true
} else if position == result.range.upperBound {
if let siblingPosition = tag.siblingTag?.position {
if siblingPosition <= result.range.lowerBound || siblingPosition >= result.range.upperBound {
upperBoundFound = true
}
}
}
if !upperBoundFound {
upperBound += tag.length
}
}
return !lowerBoundFound || !upperBoundFound
}
return range
}
}
| 36.818182 | 190 | 0.456461 |
f863ce989bed6d4edd28960a21940331ff0d08fd | 3,652 | //
// UIImage+Orientation.swift
// WeScan
//
// Created by Boris Emorine on 2/16/18.
// Copyright © 2018 WeTransfer. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
/// Data structure to easily express rotation options.
struct RotationOptions: OptionSet {
let rawValue: Int
static let flipOnVerticalAxis = RotationOptions(rawValue: 1)
static let flipOnHorizontalAxis = RotationOptions(rawValue: 2)
}
/// Returns the same image with a portrait orientation.
func applyingPortraitOrientation() -> UIImage {
switch imageOrientation {
case .up:
return rotated(by: Measurement(value: Double.pi, unit: .radians), options: []) ?? self
case .down:
return rotated(by: Measurement(value: Double.pi, unit: .radians), options: [.flipOnVerticalAxis, .flipOnHorizontalAxis]) ?? self
case .left:
return self
case .right:
return rotated(by: Measurement(value: Double.pi / 2.0, unit: .radians), options: []) ?? self
default:
return self
}
}
/// Rotate the image by the given angle, and perform other transformations based on the passed in options.
///
/// - Parameters:
/// - rotationAngle: The angle to rotate the image by.
/// - options: Options to apply to the image.
/// - Returns: The new image rotated and optentially flipped (@see options).
func rotated(by rotationAngle: Measurement<UnitAngle>, options: RotationOptions = []) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
let rotationInRadians = CGFloat(rotationAngle.converted(to: .radians).value)
let transform = CGAffineTransform(rotationAngle: rotationInRadians)
let cgImageSize = CGSize(width: cgImage.width, height: cgImage.height)
var rect = CGRect(origin: .zero, size: cgImageSize).applying(transform)
rect.origin = .zero
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let renderer = UIGraphicsImageRenderer(size: rect.size, format: format)
let image = renderer.image { renderContext in
renderContext.cgContext.translateBy(x: rect.midX, y: rect.midY)
renderContext.cgContext.rotate(by: rotationInRadians)
let x = options.contains(.flipOnVerticalAxis) ? -1.0 : 1.0
let y = options.contains(.flipOnHorizontalAxis) ? 1.0 : -1.0
renderContext.cgContext.scaleBy(x: CGFloat(x), y: CGFloat(y))
let drawRect = CGRect(origin: CGPoint(x: -cgImageSize.width / 2.0, y: -cgImageSize.height / 2.0), size: cgImageSize)
renderContext.cgContext.draw(cgImage, in: drawRect)
}
return image
}
/// Rotates the image based on the information collected by the accelerometer
func withFixedOrientation() -> UIImage {
var imageAngle: Double = 0.0
var shouldRotate = true
switch CaptureSession.current.editImageOrientation {
case .up:
shouldRotate = false
case .left:
imageAngle = Double.pi / 2
case .right:
imageAngle = -(Double.pi / 2)
case .down:
imageAngle = Double.pi
default:
shouldRotate = false
}
if shouldRotate,
let finalImage = rotated(by: Measurement(value: imageAngle, unit: .radians)) {
return finalImage
} else {
return self
}
}
}
| 36.158416 | 140 | 0.607612 |
7137e6d5421f8c90d735b1e2d129ac41d2a6cc99 | 1,940 | //
// ValidationRule.swift
// SchemaValidator
//
// Created by Sathyavijayan Vittal on 04/06/2015.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import Foundation
public enum ValidationRuleType :Int{
case Array
case Dictionary
case Unknown
case Validator
case Null
case Error
}
public class ValidationRule: Swift.ArrayLiteralConvertible, Swift.DictionaryLiteralConvertible {
/// Private object
private var _object: Any?
/// Private type
private var _type: ValidationRuleType = .Null
private var _error: NSError?
public required init(object: Any?) {
self.object = object
}
public required convenience init(arrayLiteral elements: Validator...) {
self.init(object: elements)
}
public required convenience init(dictionaryLiteral elements: (String, ValidationRule)...) {
var dict: [String: ValidationRule] = [:]
for t in elements {
dict[t.0] = t.1
}
self.init(object: dict)
}
public required convenience init(_ validator: Validator) {
self.init(object: validator)
}
/// Object in JSON
public var object: Any? {
get {
return _object
}
set {
_object = newValue
switch newValue {
case let validator as Validator:
_type = .Validator
case let array as [Validator]:
_type = .Array
case let dictionary as [String : ValidationRule]:
_type = .Dictionary
default:
_type = .Unknown
_object = NSNull()
_error = NSError(domain: SchemaValidatorErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
public func type() -> ValidationRuleType {
return _type
}
}
| 25.194805 | 144 | 0.583505 |
bf76b0319614e503fdff5a5e973fd23c5410445d | 3,293 | //
// FileSystemRepositoryTests.swift
// XRepositoryRxTests
//
// Created by Oleksandr Potapov on 16.12.2021.
//
import XCTest
import XRepository
@testable import XRepositoryFileSystem
class FileSystemRepositoryTests: XCTestCase {
fileprivate var repository: FileSystemRepository<Employee>!
fileprivate let testEmployees: [Employee] = [
Employee(name: "Quirin", age: 21, data: Data()),
Employee(name: "Stefan", age: 24, data: Data()),
Employee(name: "Sebi", age: 22, data: Data()),
Employee(name: "Malte" ,age: 24, data: Data()),
Employee(name: "Joan", age: 23, data: Data()),
]
override func setUp() {
super.setUp()
repository = FileSystemRepository(directory: .caches)
addRandomMockObjects(to: repository)
}
func testGetAll() {
let allObjects = repository.getAll()
XCTAssertEqual(allObjects.underestimatedCount, testEmployees.count)
}
func testDeleteAll() {
let deletionError = repository.deleteAll()
let allObjects = repository.getAll()
XCTAssert(allObjects.isEmpty && deletionError == nil)
}
func testFilter() {
repository.create(Employee(name: "Torsten", age: 19, data: Data()))
repository.create(Employee(name: "Torben", age: 21, data: Data()))
repository.create(Employee(name: "Tim", age: 87, data: Data()))
repository.create(Employee(name: "Struppi", age: 3, data: Data()))
let newEmployeeName = "Zementha"
repository.create(Employee(name: newEmployeeName, age: 34, data: Data()))
let filteredEmployees = repository.getElements(filteredByPredicate: \.name == newEmployeeName)
guard let firstEmployee = filteredEmployees.first else { return }
XCTAssertEqual(firstEmployee.name, newEmployeeName)
XCTAssertEqual(filteredEmployees.count, 1)
}
func testSortingAscending() {
let stdlibSortedEmployees = testEmployees.sorted(by: { $0.age < $1.age })
let filteredEmployees = repository.getElements(sortedBy: \.age)
XCTAssert(filteredEmployees.first?.age == stdlibSortedEmployees.first?.age)
XCTAssert(filteredEmployees.last?.age == stdlibSortedEmployees.last?.age)
}
func testSortingDescending() {
let stdlibSortedEmployees = testEmployees.sorted(by: { $0.age > $1.age })
let filteredEmployees = repository.getElements(sortedBy: \.age).reversed()
XCTAssert(filteredEmployees.first?.age == stdlibSortedEmployees.first?.age)
XCTAssert(filteredEmployees.last?.age == stdlibSortedEmployees.last?.age)
}
func testDistinct() {
let stdlibFilteredAges = Set(testEmployees.map { $0.age })
let distinctAgeEmployees = repository.getElements(distinctUsing: \.age)
let ages = distinctAgeEmployees.map { $0.age }
XCTAssert(stdlibFilteredAges.count == ages.count)
}
// MARK: Helper Methods
private func addRandomMockObjects(to repository: FileSystemRepository<Employee>) {
repository.deleteAll()
repository.create(testEmployees)
}
}
class Employee: IdentifiableCodable {
var id: String = ""
var name: String = ""
var age: Int = 0
var data: Data = Data()
convenience init(name: String, age: Int, data: Data) {
self.init()
self.id = name
self.name = name
self.age = age
self.data = data
}
}
| 29.936364 | 98 | 0.689341 |
bfbe91d08198cdada95d69bb9bf3359f756f9940 | 2,880 | import UIKit
import Combine
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var subscriptions = Set<AnyCancellable>()
example(of: "Dynamically adjusting Demand") {
final class IntSubscriber: Subscriber {
typealias Input = Int
typealias Failure = Never
func receive(subscription: Subscription) {
subscription.request(.max(2))
}
func receive(_ input: Int) -> Subscribers.Demand {
print("Received value", input)
switch input {
case 1:
return .max(2)
case 3:
return .max(1)
default:
return .none
}
}
func receive(completion: Subscribers.Completion<Never>) {
print("Received completion", completion)
}
}
let subscriber = IntSubscriber()
let subject = PassthroughSubject<Int, Never>()
subject.subscribe(subscriber)
subject.send(1)
subject.send(2)
subject.send(3)
subject.send(4)
subject.send(5)
subject.send(6)
}
/// Copyright (c) 2021 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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.
| 35.555556 | 83 | 0.721528 |
bb946c18a32ef227372e2f01fab1ab8895e6a352 | 657 | // 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 S(f()
println(x: C {
class A {
class a<S : S<T where T.B == F>
}
class A : e(")
}
class c : a {
let d{
if true {
protocol c : C {
if true {
protocol A {
protocol c : A {
extension
var d = {
protocol l : S<S : e
let d{
var d = {
class B<Int>: a {
}
class B<T where T>
let d{
println(")
}
class B : P {
class A : f { func f()
protocol A : f { func f<T.h
typealias e = F>
println(f<(f
func b<b
class B == F>: b { func f
class : BooleanType, A {
(f(f<b ()
class B? {
}
typealias e : P
| 15.642857 | 87 | 0.622527 |
9b1741505fea8bc0379e77a262ef132d09308e43 | 2,448 | //
// AppDelegate.swift
// BookRoomChatbot
//
// Created by mahbub on 3/19/18.
// Copyright © 2018 Fulda University Of Applied Sciences. All rights reserved.
//
import UIKit
import ApiAI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let configuration = AIDefaultConfiguration()
configuration.clientAccessToken = "368d93c79f584e2d8c95447f646d2935"
let apiAI = ApiAI.shared()
apiAI?.configuration = configuration
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:.
}
}
| 44.509091 | 285 | 0.745507 |
21ec70c4b5ad3ab429c6e5222c27ff21ccc820ce | 3,463 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Commands
import PackageModel
import SPMTestSupport
import TSCBasic
import Workspace
import XCTest
class BuildPerfTests: XCTestCasePerf {
@discardableResult
func execute(args: [String] = [], packagePath: AbsolutePath) throws -> (stdout: String, stderr: String) {
// FIXME: We should pass the SWIFT_EXEC at lower level.
return try SwiftPMProduct.SwiftBuild.execute(args + [], packagePath: packagePath, env: ["SWIFT_EXEC": UserToolchain.default.swiftCompilerPath.pathString])
}
func clean(packagePath: AbsolutePath) throws {
_ = try SwiftPMProduct.SwiftPackage.execute(["clean"], packagePath: packagePath)
}
func testTrivialPackageFullBuild() throws {
#if !os(macOS)
try XCTSkipIf(true, "test is only supported on macOS")
#endif
try runFullBuildTest(for: "DependencyResolution/Internal/Simple", product: "foo")
}
func testTrivialPackageNullBuild() throws {
#if !os(macOS)
try XCTSkipIf(true, "test is only supported on macOS")
#endif
try runNullBuildTest(for: "DependencyResolution/Internal/Simple", product: "foo")
}
func testComplexPackageFullBuild() throws {
#if !os(macOS)
try XCTSkipIf(true, "test is only supported on macOS")
#endif
try runFullBuildTest(for: "DependencyResolution/External/Complex", app: "app", product: "Dealer")
}
func testComplexPackageNullBuild() throws {
#if !os(macOS)
try XCTSkipIf(true, "test is only supported on macOS")
#endif
try runNullBuildTest(for: "DependencyResolution/External/Complex", app: "app", product: "Dealer")
}
func runFullBuildTest(for name: String, app appString: String? = nil, product productString: String) throws {
try fixture(name: name) { fixturePath in
let app = fixturePath.appending(components: (appString ?? ""))
let triple = UserToolchain.default.triple
let product = app.appending(components: ".build", triple.platformBuildPathComponent(), "debug", productString)
try self.execute(packagePath: app)
measure {
try! self.clean(packagePath: app)
try! self.execute(packagePath: app)
XCTAssertFileExists(product)
}
}
}
func runNullBuildTest(for name: String, app appString: String? = nil, product productString: String) throws {
try fixture(name: name) { fixturePath in
let app = fixturePath.appending(components: (appString ?? ""))
let triple = UserToolchain.default.triple
let product = app.appending(components: ".build", triple.platformBuildPathComponent(), "debug", productString)
try self.execute(packagePath: app)
measure {
try! self.execute(packagePath: app)
XCTAssertFileExists(product)
}
}
}
}
| 39.804598 | 162 | 0.628357 |
56ee8f0d165982d1084321a3574d2d0efc783be1 | 1,361 | ////
//// GuidingPhase.swift
//// CoreML-in-ARKit
////
//// Created by Min Young Chang on 4/28/21.
//// Copyright © 2021 Yehor Chernenko. All rights reserved.
////
//
import Foundation
import AVFoundation
class GuidingTool {
enum targetDirection {
case onScreen
case goUp
case goDown
case goLeft
case goRight
}
func getDirectionMessage(targetDirection: targetDirection, distance: Float) -> String {
switch targetDirection {
case .onScreen:
return """
on Screen
\(round(distance * 100) / 100.0) m
"""
case .goUp:
return "go Up"
case .goDown:
return "go Down"
case .goLeft:
return "go Left"
case .goRight:
return "go Right"
}
}
func checkTargetDirection(pixelValues: simd_float4) -> targetDirection {
if ((pixelValues.x >= 0.2) && (pixelValues.x <= 0.8) && (pixelValues.y >= 0.1) && (pixelValues.y <= 0.9)) {
return .onScreen
} else if (pixelValues.x < 0.35) {
return .goLeft
} else if (pixelValues.x > 0.65) {
return .goRight
} else if (pixelValues.y < 0.3) {
return .goDown
} else {
return .goUp
}
}
}
| 25.679245 | 115 | 0.510654 |
11a309a499d7e14d5176ce021e94a478368ad2c6 | 1,424 | //
// Furniture_AppUITests.swift
// Furniture AppUITests
//
// Created by Balaji on 13/08/20.
//
import XCTest
class Furniture_AppUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.116279 | 182 | 0.658006 |
f93248b87ec4ce1fea75578f93624de3dbd3aca1 | 3,192 | //
// AppDelegate.swift
//
// Copyright (c) 2016 ChildhoodAndy (http://dabing1022.github.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 50.666667 | 285 | 0.756579 |
0877d495d0c83c1fc47b17cdb88af9421cfcd0fc | 12,881 | //
// ApiResource.swift
// ivy-sdk
//
// Created by Praphin SP on 23/11/21.
//
import Foundation
import Alamofire
class InternetConnectivity {
class var isConnected:Bool {
return NetworkReachabilityManager()?.isReachable ?? false
}
}
let concurrentQueue = DispatchQueue(label: "com.queue.Concurrent", attributes: .concurrent)
var workItems = [DispatchWorkItem]()
class ApiResource: NSObject {
static var isTokenRefreshing = false
static var isTokenUpdated = false
func apiRequest(urlStr : String, method: HTTPMethod, header : [String:String]?, parameters: [String:Any]?, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
let headers: HTTPHeaders = [
// "x-id-token": AppVariable.shared.getValueFromUserDefault(key: DataKey.idToken) as? String ?? "",
// "x-access-token": UserData.shared?.token ?? ""
"x-id-token": "",
"x-access-token": ""
]
do {
guard let url = try urlStr.addingUrlPercentEncoding()?.asURL() else { return
print("not valid url : \(urlStr)")
}
let dataRequest = AF.request(url, method: method, parameters: parameters, encoding: URLEncoding.default, headers: headers)
dataRequest.responseJSON { (response) in
DispatchQueue.main.async {
if method == .head {
let value: Any? = response.response?.allHeaderFields
completion(response.response?.statusCode ?? 600, value,nil)
} else {
switch response.result {
case .success(let value):
completion(response.response?.statusCode ?? 600, value,nil)
case .failure(let error):
completion(response.response?.statusCode ?? 600, nil,error)
}
}
}
}
}catch {
print("not valid url : \(urlStr)")
}
}
func getApiCall(url : String, headers : [String:String]?, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
self.apiCallWithToken(urlStr: url, method: .get, header: headers, parameters: nil) { (code, response, error) in
DispatchQueue.main.async {
completion(code, response , error)
}
}
}
func postApiCall(url : String, parameters: [String:Any], headers : [String:String]?, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
self.apiCallWithToken(urlStr: url, method: .post, header: headers, parameters: parameters) { (code, response, error) in
DispatchQueue.main.async {
completion(code, response, error)
}
}
}
func deleteApiCall(url : String, parameters: [String:Any]?, headers : [String:String]?, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
self.apiCallWithToken(urlStr: url, method: .delete, header: headers, parameters: parameters) { (code, response, error) in
DispatchQueue.main.async {
completion(code, response, error)
}
}
}
func patchApiCall(url : String, parameters: [String:Any], headers : [String:String]?, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
self.apiCallWithToken(urlStr: url, method: .patch, header: headers, parameters: parameters) { (code, response, error) in
DispatchQueue.main.async {
completion(code, response, error)
}
}
}
func headApiCall(url : String, headers : [String:String]?, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
self.apiCallWithToken(urlStr: url, method: .head, header: headers, parameters: nil) { (code, response, error) in
DispatchQueue.main.async {
completion(code, response, error)
}
}
}
func apiCallWithToken(urlStr : String, method: HTTPMethod, header : [String:String]?, parameters: [String:Any]?, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
let u = urlStr
let callWithDelay: (()->Void) = {
self.apiCallWithToken(urlStr: urlStr, method: method, header: header, parameters: parameters) { (code, response, error) in
completion(code, response, error)
}
} // in case token refreshing
var headerData = [String: String]()
if let header = header {
headerData = header
}
// headerData["x-id-token"] = AppVariable.shared.getValueFromUserDefault(key: DataKey.idToken) as? String
// headerData["x-access-token"] = UserData.shared?.token
headerData["x-id-token"] = SDKVariables.shared.SDK_CLIENT_ID ?? ""
headerData["x-access-token"] = SDKVariables.shared.SDK_CLIENT_TOKEN ?? ""
print("headers: \(headerData)")
self.apiCall(urlStr: urlStr, method: method, header: headerData, parameters: parameters) { (code, response, error) in
print(response)
if code == 401 {
completion(code, response, error)
// let work: DispatchWorkItem? = DispatchWorkItem {
//
// var isTokenExist = false
//
// if isTokenExist {
// if ApiResource.isTokenUpdated {
// print("token-> token updated by another api: \(u)")
// workItems.removeAll()
// callWithDelay()
// }
// else if ApiResource.isTokenRefreshing == false {
// print("token-> updating token: \(u)")
// ApiResource.isTokenRefreshing = true
// var dict = [String: String]()
// dict["token"] = UserData.shared?.token
// dict["refreshtoken"] = UserData.shared?.refreshtoken
// self.apiCall(urlStr: URLConstants.refreshTokenURL, method: .post, header: nil, parameters: dict) { (code, response, error) in
// if code == 200, let response = response as? [String:Any], let dataDict = response["data"] as? [String:Any] {
// print("token-> token updated: \(u)")
// let newToken = dataDict["token"]
// let newRefreshtoken = dataDict["refreshtoken"]
// UserData.shared?.token = newToken as? String
// UserData.shared?.refreshtoken = newRefreshtoken as? String
// UserData.shared?.save()
// ApiResource.isTokenRefreshing = false
// ApiResource.isTokenUpdated = true
// workItems.removeAll()
// callWithDelay()
// }
// else {
// print("token-> token expired need to logout: \(u)")
// for work in workItems {
// work.cancel()
// }
// workItems.removeAll()
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// ApiResource.isTokenRefreshing = false
// if !appDelegate!.isSplashRunning {
// AppRouter.loadSessionExpiredView()
// }
// //clear scheduled/ fired notification
// LocalNotificationManager.shared.deleteAll()
// completion(code, response, error)
// }
// }
// }
// }
// else {
// completion(code, response, error)
// }
// }
// else {
// print("token-> token expired need to logout: \(u)")
// for work in workItems {
// work.cancel()
// }
// workItems.removeAll()
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// ApiResource.isTokenRefreshing = false
// }
// }
// }
// if let work = work {
// workItems.append(work)
// }
// concurrentQueue.async(flags: .barrier) {
// work?.perform()
// }
}
else {
completion(code, response, error)
}
}
}
func apiCall(urlStr : String, method: HTTPMethod, header : [String:String]?, parameters: [String:Any]?, encoding: ParameterEncoding = JSONEncoding.default, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
if let r = NetworkReachabilityManager(), !r.isReachable {
completion(600, nil,nil)
return
}
else {
}
do {
let completeUrlStr = urlStr.addingUrlPercentEncoding()
guard let url = try completeUrlStr?.asURL() else { return
print("not valid url : \(urlStr)")
}
var headers: HTTPHeaders?
if let header = header {
headers = HTTPHeaders(header)
}
let dataRequest = AF.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers)
dataRequest.responseJSON { (response) in
DispatchQueue.main.async {
if method == .head {
let value: Any? = response.response?.allHeaderFields
completion(response.response?.statusCode ?? 600, value,nil)
}
else {
switch response.result {
case .success(let value):
completion(response.response?.statusCode ?? 600, value,nil)
case .failure(let error):
completion(response.response?.statusCode ?? 600, nil,error)
}
}
}
}
} catch {
print("not valid url : \(urlStr)")
}
}
func fileUpload(urlStr : String, data: Data, param: [String:String], completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
let headers: HTTPHeaders? = HTTPHeaders(param)
let uploadRequest = AF.upload(data, to: urlStr, method: .put, headers: headers)
uploadRequest.response(queue: DispatchQueue.global()) { (response) in
if response.response?.statusCode == 200 {
completion(response.response?.statusCode ?? 600, nil ,nil)
}
else {
completion(response.response?.statusCode ?? 600, nil,response.error)
}
}
}
func fileDownload(urlStr : String, fileName: String, completion:@escaping ((_ code: Int, _ response: Any?, _ error: Error?)->Void)) {
let destination: DownloadRequest.Destination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
documentsURL.appendPathComponent(fileName)
return (documentsURL, [.removePreviousFile])
}
AF.download(urlStr, to: destination).response { response in
if response.fileURL != nil {
print(response.fileURL!)
completion(response.response?.statusCode ?? 200, nil ,nil)
} else {
completion(response.response?.statusCode ?? 600, nil ,nil)
}
}
}
}
| 43.224832 | 240 | 0.485909 |
903ede0ccd4872678ad26a2521a9f543a1ad30c5 | 754 | //
// MPNewsMedia-metadata.swift
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
struct MPNewsMediaMetadata : Codable {
let format : String?
let height : Int?
let url : String?
let width : Int?
enum CodingKeys: String, CodingKey {
case format = "format"
case height = "height"
case url = "url"
case width = "width"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
format = try values.decodeIfPresent(String.self, forKey: .format)
height = try values.decodeIfPresent(Int.self, forKey: .height)
url = try values.decodeIfPresent(String.self, forKey: .url)
width = try values.decodeIfPresent(Int.self, forKey: .width)
}
}
| 24.322581 | 81 | 0.720159 |
b94ac3f665775973d9cec5d1dabd47f2533b1821 | 219 | //
// {Name}PresenterViewInterface.swift
// {project}
//
// Created by {author} on {date}.
//
import Foundation
import UIKit
protocol {Name}PresenterViewInterface: PresenterViewInterface {
func viewDidLoad()
}
| 15.642857 | 63 | 0.716895 |
db85a2c6e2aee81c0ec29d98979ea2bf13a49342 | 1,045 | extension UIColor {
convenience init(hexString: String, alpha: CGFloat = 1.0) {
let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
}
| 26.794872 | 101 | 0.545455 |
acfb72e603e0c49a84fed77e80904b9c4b3a068b | 910 | //
// LunarSmallDateWidgetView.swift
// ClendarWidgetExtension
//
// Created by Vinh Nguyen on 11/01/2021.
// Copyright © 2021 Vinh Nguyen. All rights reserved.
//
import SwiftUI
struct LunarSmallDateWidgetView: View {
let entry: WidgetEntry
var body: some View {
VStack(alignment: .center) {
Text(entry.date.toMonthString.localizedUppercase)
.font(.boldFontWithSize(18))
.foregroundColor(.gray)
Text(entry.date.toFullDayString)
.font(.boldFontWithSize(20))
.foregroundColor(.appRed)
Text(entry.date.toDateString)
.font(.boldFontWithSize(45))
.foregroundColor(.appDark)
Text(DateFormatter.lunarDateString(forDate: entry.date))
.font(.boldFontWithSize(20))
.foregroundColor(.red)
}.padding(.all)
}
}
| 29.354839 | 68 | 0.598901 |
e2ba8bdbee230823dfdb7878577d9132e2abc1ad | 218 | //
// TemplateCell.swift
// TemplateCell
//
// Created by myToys Tech Lab on 28/10/16.
// Copyright © 2016 myToys Tech Lab. All rights reserved.
//
import UIKit
final class TemplateCell: UITableViewCell {
}
| 15.571429 | 58 | 0.688073 |
48212ca2d0c16ceecf9483582542c0b3f89c66b7 | 356 | //
// Constant.swift
// MyiOSApp
//
// Created by Soufiane Salouf on 6/8/20.
// Copyright © 2020 Soufiane Salouf. All rights reserved.
//
import Foundation
struct Constants {
// MARK: - Networking config
static let BASE_URL = "http://127.0.0.1:8000/"
static let CONNECTION = BASE_URL + "api/"
static let TIMEOUT_SECONDS = 30.0
}
| 19.777778 | 58 | 0.654494 |
e6824d6a6228e51a94e935f6b45a56f56ed817e3 | 2,568 | //
// DictionaryUITests.swift
// DictionaryUITests
//
// Created by Xiaolin Wang on 04/07/2017.
// Copyright © 2017 Xiaolin Wang. All rights reserved.
//
import XCTest
class DictionaryUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
let app = XCUIApplication()
let button = app/*@START_MENU_TOKEN@*/.keyboards.buttons["키보드 가리기"]/*[[".keyboards.buttons[\"키보드 가리기\"]",".buttons[\"키보드 가리기\"]"],[[[-1,1],[-1,0]]],[1]]@END_MENU_TOKEN@*/
let textField = app.textFields["검색..."]
button.tap()
XCTAssert(textField.frame.minY>0)
textField.tap()
button.tap()
textField.tap()
textField.typeText("test")
let searchButton = app/*@START_MENU_TOKEN@*/.keyboards.buttons["Search"]/*[[".keyboards.buttons[\"Search\"]",".buttons[\"Search\"]"],[[[-1,1],[-1,0]]],[1]]@END_MENU_TOKEN@*/
searchButton.tap()
XCUIDevice.shared.orientation = .landscapeLeft
XCUIDevice.shared.orientation = .portrait
XCUIDevice.shared.orientation = .faceUp
app/*@START_MENU_TOKEN@*/.otherElements["PopoverDismissRegion"]/*[[".otherElements[\"팝업 닫기\"]",".otherElements[\"PopoverDismissRegion\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
textField.tap()
app/*@START_MENU_TOKEN@*/.textFields["검색..."].buttons["텍스트 지우기"]/*[[".textFields[\"검색...\"].buttons[\"텍스트 지우기\"]",".buttons[\"텍스트 지우기\"]"],[[[-1,1],[-1,0]]],[1]]@END_MENU_TOKEN@*/.tap()
searchButton.tap()
textField.typeText("\n")
button.tap()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 42.098361 | 193 | 0.620327 |
7a262971e6cef72ce6ff2d003c21b9a4dd3322b5 | 319 | //
// HYRecommendFooterView.swift
// Himalayan
//
// Created by Adonis_HongYang on 2020/3/17.
// Copyright © 2020 Adonis_HongYang. All rights reserved.
//
import UIKit
class HYRecommendFooterView: HYBaseCollectionReusableView {
override func setupUI() {
self.backgroundColor = FooterViewColor
}
}
| 19.9375 | 59 | 0.724138 |
d610fe0490a8341e382d726c38c565b3f27e8531 | 587 | //
// UIImage+resize.swift
// ProperMediaViewDemo
//
// Created by Murawaki on 2017/03/30.
// Copyright © 2017年 Murawaki. All rights reserved.
//
import UIKit
public extension UIImage {
public func resizeImage(size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
_ = UIGraphicsGetCurrentContext()
draw(in: CGRect(x:0, y:0, width:size.width, height:size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? self
}
}
| 24.458333 | 72 | 0.657581 |
dd39a583e9914ed8730f2d8d7308f7c972afc0a3 | 539 | //
// Bill1ViewCell.swift
// SlideMenuControllerSwift
//
// Created by Manish Dwibedy on 11/10/16.
// Copyright © 2016 Yuji Hato. All rights reserved.
//
import UIKit
class Bill1ViewCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
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
}
}
| 20.730769 | 65 | 0.673469 |
e2cfb1fe54f1a8034c438cb02f5e6314d15a786b | 1,397 | //
// ContactListAppDemoUITests.swift
// ContactListAppDemoUITests
//
// Created by Ajay Bandi on 4/18/22.
//
import XCTest
class ContactListAppDemoUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.261905 | 182 | 0.662849 |
f5b3145a8ece92797b1acfe51fa2aa28060d057f | 2,154 | //
// AppDelegate.swift
// OhMySwiftPodLib
//
// Created by ChenYu Xiao on 07/04/2015.
// Copyright (c) 2015 ChenYu Xiao. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.829787 | 285 | 0.75441 |
f863ecc039a17fd94dafe98a2fc269cd7e1ff25f | 2,919 | //
// BoardSizeViewController.swift
// UltimatePegSolitaire
//
// Created by Maksim Khrapov on 11/3/19.
// Copyright © 2019 Maksim Khrapov. All rights reserved.
//
// https://www.ultimatepegsolitaire.com/
// https://github.com/mkhrapov/ultimate-peg-solitaire
//
// 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
final class SetBoardSizeViewController: UIViewController {
@IBOutlet weak var boardSizeView: SetBoardSizeView!
@IBOutlet weak var rowsStepper: UIStepper!
@IBOutlet weak var columnsStepper: UIStepper!
@IBOutlet weak var rowsLabel: UILabel!
@IBOutlet weak var columnsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Set Board Size"
let backItem = UIBarButtonItem()
backItem.title = "Board Size"
navigationItem.backBarButtonItem = backItem
boardSizeView.rows = GlobalStateManager.shared.newBoard.Y
boardSizeView.columns = GlobalStateManager.shared.newBoard.X
rowsLabel.text = "Rows: \(boardSizeView.rows)"
columnsLabel.text = "Columns: \(boardSizeView.columns)"
rowsStepper.minimumValue = 4.0
rowsStepper.maximumValue = 20.0
rowsStepper.stepValue = 1.0
rowsStepper.value = Double(boardSizeView.rows)
columnsStepper.minimumValue = 4.0
columnsStepper.maximumValue = 20.0
columnsStepper.stepValue = 1.0
columnsStepper.value = Double(boardSizeView.columns)
}
@IBAction func rowsStepperAction(_ sender: UIStepper) {
let rows = Int(floor(sender.value))
boardSizeView.rows = rows
boardSizeView.setNeedsDisplay()
rowsLabel.text = "Rows: \(boardSizeView.rows)"
setNewBoard()
}
@IBAction func columnsStepperAction(_ sender: UIStepper) {
let columns = Int(floor(sender.value))
boardSizeView.columns = columns
boardSizeView.setNeedsDisplay()
columnsLabel.text = "Columns: \(boardSizeView.columns)"
setNewBoard()
}
private func setNewBoard() {
let x = boardSizeView.columns
let y = boardSizeView.rows
let allowed = Array(repeating: 1, count: x*y)
GlobalStateManager.shared.solvable = nil
GlobalStateManager.shared.newBoard = Board(x, y, 0, 0, "New Board", allowed)
}
}
| 32.797753 | 84 | 0.675231 |
5b0c294cbb5f742a89e416d99dd1ee4b9f715acf | 1,419 | //
// PreworkUITests.swift
// PreworkUITests
//
// Created by Federico Marti Garro on 8/18/21.
//
import XCTest
class PreworkUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33 | 182 | 0.656096 |
8738a391f81e80173e4ca9861003866ad6cd7fa8 | 17,111 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlowLite
import UIKit
class ImageSegmentator {
/// TensorFlow Lite `Interpreter` object for performing inference on a given model.
private var interpreter: Interpreter
/// Dedicated DispatchQueue for TF Lite operations.
private let tfLiteQueue: DispatchQueue
/// TF Lite Model's input and output shapes.
private let batchSize: Int
private let inputImageWidth: Int
private let inputImageHeight: Int
private let inputPixelSize: Int
private let outputImageWidth: Int
private let outputImageHeight: Int
private let outputClassCount: Int
/// Label list contains name of all classes the model can regconize.
private let labelList: [String]
// MARK: - Initialization
/// Load label list from file.
private static func loadLabelList() -> [String]? {
guard
let labelListPath = Bundle.main.path(
forResource: Constants.labelsFileName,
ofType: Constants.labelsFileExtension
)
else {
return nil
}
// Parse label list file as JSON.
do {
let data = try Data(contentsOf: URL(fileURLWithPath: labelListPath), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let labelList = jsonResult as? [String] { return labelList } else { return nil }
} catch {
print("Error parsing label list file as JSON.")
return nil
}
}
/// Create a new Image Segmentator instance.
static func newInstance(completion: @escaping ((Result<ImageSegmentator>) -> Void)) {
// Create a dispatch queue to ensure all operations on the Intepreter will run serially.
let tfLiteQueue = DispatchQueue(label: "org.tensorflow.examples.lite.image_segmentation")
// Run initialization in background thread to avoid UI freeze.
tfLiteQueue.async {
// Construct the path to the model file.
guard
let modelPath = Bundle.main.path(
forResource: Constants.modelFileName,
ofType: Constants.modelFileExtension
)
else {
print(
"Failed to load the model file with name: "
+ "\(Constants.modelFileName).\(Constants.modelFileExtension)")
DispatchQueue.main.async {
completion(
.error(
InitializationError.invalidModel(
"\(Constants.modelFileName).\(Constants.modelFileExtension)"
)))
}
return
}
// Construct the path to the label list file.
guard let labelList = loadLabelList() else {
print(
"Failed to load the label list file with name: "
+ "\(Constants.labelsFileName).\(Constants.labelsFileExtension)"
)
DispatchQueue.main.async {
completion(
.error(
InitializationError.invalidLabelList(
"\(Constants.labelsFileName).\(Constants.labelsFileExtension)"
)))
}
return
}
// Specify the options for the TF Lite `Interpreter`.
var options: Interpreter.Options?
var delegates: [Delegate]?
#if targetEnvironment(simulator)
// Use CPU for inference as MetalDelegate does not support iOS simulator.
options = Interpreter.Options()
options?.threadCount = 2
#else
// Use Neural Engine on iPhone Xs and later
delegates = [CoreMLDelegate()]
#endif
do {
// Create the `Interpreter`.
let interpreter = try Interpreter(
modelPath: modelPath,
options: options,
delegates: delegates
)
// Allocate memory for the model's input `Tensor`s.
try interpreter.allocateTensors()
// Read TF Lite model input and output shapes.
let inputShape = try interpreter.input(at: 0).shape
let outputShape = try interpreter.output(at: 0).shape
// Create an ImageSegmentator instance and return.
let segmentator = ImageSegmentator(
tfLiteQueue: tfLiteQueue,
interpreter: interpreter,
inputShape: inputShape,
outputShape: outputShape,
labelList: labelList
)
DispatchQueue.main.async {
completion(.success(segmentator))
}
} catch let error {
print("Failed to create the interpreter with error: \(error.localizedDescription)")
DispatchQueue.main.async {
completion(.error(InitializationError.internalError(error)))
}
return
}
}
}
/// Initialize Image Segmentator instance.
fileprivate init(
tfLiteQueue: DispatchQueue,
interpreter: Interpreter,
inputShape: Tensor.Shape,
outputShape: Tensor.Shape,
labelList: [String]
) {
// Store TF Lite intepreter
self.interpreter = interpreter
// Read input shape from model.
self.batchSize = inputShape.dimensions[0]
self.inputImageWidth = inputShape.dimensions[1]
self.inputImageHeight = inputShape.dimensions[2]
self.inputPixelSize = inputShape.dimensions[3]
// Read output shape from model.
self.outputImageWidth = outputShape.dimensions[1]
self.outputImageHeight = outputShape.dimensions[2]
self.outputClassCount = outputShape.dimensions[3]
// Store label list
self.labelList = labelList
// Store the dedicated DispatchQueue for TFLite.
self.tfLiteQueue = tfLiteQueue
}
// MARK: - Image Segmentation
/// Run segmentation on a given image.
/// - Parameter image: the target image.
/// - Parameter completion: the callback to receive segmentation result.
func runSegmentation(
_ image: UIImage, completion: @escaping ((Result<SegmentationResult>) -> Void)
) {
tfLiteQueue.async {
let outputTensor: Tensor
var startTime: Date = Date()
var preprocessingTime: TimeInterval = 0
var inferenceTime: TimeInterval = 0
var postprocessingTime: TimeInterval = 0
var visualizationTime: TimeInterval = 0
do {
// Preprocessing: Resize the input UIImage to match with TF Lite model input shape.
guard
let rgbData = image.scaledData(
with: CGSize(width: self.inputImageWidth, height: self.inputImageHeight),
byteCount: self.inputImageWidth * self.inputImageHeight * self.inputPixelSize
* self.batchSize,
isQuantized: false
)
else {
DispatchQueue.main.async {
completion(.error(SegmentationError.invalidImage))
}
print("Failed to convert the image buffer to RGB data.")
return
}
// Calculate preprocessing time.
var now = Date()
preprocessingTime = now.timeIntervalSince(startTime)
startTime = Date()
// Allocate memory for the model's input `Tensor`s.
try self.interpreter.allocateTensors()
// Copy the RGB data to the input `Tensor`.
try self.interpreter.copy(rgbData, toInputAt: 0)
// Run inference by invoking the `Interpreter`.
try self.interpreter.invoke()
// Get the output `Tensor` to process the inference results.
outputTensor = try self.interpreter.output(at: 0)
// Calculate inference time.
now = Date()
inferenceTime = now.timeIntervalSince(startTime)
startTime = Date()
} catch let error {
print("Failed to invoke the interpreter with error: \(error.localizedDescription)")
DispatchQueue.main.async {
completion(.error(SegmentationError.internalError(error)))
}
return
}
// Postprocessing: Find the class with highest confidence for each pixel.
let parsedOutput = self.parseOutputTensor(outputTensor: outputTensor)
// Calculate postprocessing time.
// Note: You may find postprocessing very slow if you run the sample app with Debug build.
// You will see significant speed up if you rerun using Release build, or change
// Optimization Level in the project's Build Settings to the same value with Release build.
var now = Date()
postprocessingTime = now.timeIntervalSince(startTime)
startTime = Date()
// Visualize result into images.
guard
let resultImage = ImageSegmentator.imageFromSRGBColorArray(
pixels: parsedOutput.segmentationImagePixels,
width: self.inputImageWidth,
height: self.inputImageHeight
),
let overlayImage = image.overlayWithImage(image: resultImage, alpha: 0.5)
else {
print("Failed to visualize segmentation result.")
DispatchQueue.main.async {
completion(.error(SegmentationError.resultVisualizationError))
}
return
}
// Construct a dictionary of classes found in the image and each class's color used in
// visualization.
let colorLegend = self.classListToColorLegend(classList: parsedOutput.classList)
// Calculate visualization time.
now = Date()
visualizationTime = now.timeIntervalSince(startTime)
// Create a representative object that contains the segmentation result.
let result = SegmentationResult(
array: parsedOutput.segmentationMap,
resultImage: resultImage,
overlayImage: overlayImage,
preprocessingTime: preprocessingTime,
inferenceTime: inferenceTime,
postProcessingTime: postprocessingTime,
visualizationTime: visualizationTime,
colorLegend: colorLegend
)
// Return the segmentation result.
DispatchQueue.main.async {
completion(.success(result))
}
}
}
/// Post-processing: Convert TensorFlow Lite output tensor to segmentation map and its color
/// representation.
private func parseOutputTensor(outputTensor: Tensor)
-> (segmentationMap: [[Int]], segmentationImagePixels: [UInt32], classList: Set<Int>)
{
// Initialize the varibles to store postprocessing result.
var segmentationMap = [[Int]](
repeating: [Int](repeating: 0, count: self.outputImageHeight),
count: self.outputImageWidth
)
var segmentationImagePixels = [UInt32](
repeating: 0, count: self.outputImageHeight * self.outputImageWidth)
var classList: Set<Int> = []
// Convert TF Lite model output to a native Float32 array for parsing.
let logits = outputTensor.data.toArray(type: Float32.self)
var valMax: Float32 = 0.0
var val: Float32 = 0.0
var indexMax = 0
// Looping through the output array
for x in 0..<self.outputImageWidth {
for y in 0..<self.outputImageHeight {
// For each pixel, find the class that have the highest probability.
valMax = logits[self.coordinateToIndex(x: x, y: y, z: 0)]
indexMax = 0
for z in 1..<self.outputClassCount {
val = logits[self.coordinateToIndex(x: x, y: y, z: z)]
if logits[self.coordinateToIndex(x: x, y: y, z: z)] > valMax {
indexMax = z
valMax = val
}
}
// Store the most likely class to the output.
segmentationMap[x][y] = indexMax
classList.insert(indexMax)
// Lookup the color legend for the class.
// Using modulo to reuse colors on segmentation model with large number of classes.
let legendColor = Constants.legendColorList[indexMax % Constants.legendColorList.count]
segmentationImagePixels[x * self.outputImageHeight + y] = legendColor
}
}
return (segmentationMap, segmentationImagePixels, classList)
}
// MARK: - Utils
/// Construct an UIImage from a list of sRGB pixels.
private static func imageFromSRGBColorArray(pixels: [UInt32], width: Int, height: Int) -> UIImage?
{
guard width > 0 && height > 0 else { return nil }
guard pixels.count == width * height else { return nil }
// Make a mutable copy
var data = pixels
// Convert array of pixels to a CGImage instance.
let cgImage = data.withUnsafeMutableBytes { (ptr) -> CGImage in
let ctx = CGContext(
data: ptr.baseAddress,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: MemoryLayout<UInt32>.size * width,
space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue
+ CGImageAlphaInfo.premultipliedFirst.rawValue
)!
return ctx.makeImage()!
}
// Convert the CGImage instance to an UIImage instance.
return UIImage(cgImage: cgImage)
}
/// Convert 3-dimension index (image_width x image_height x class_count) to 1-dimension index
private func coordinateToIndex(x: Int, y: Int, z: Int) -> Int {
return x * outputImageHeight * outputClassCount + y * outputClassCount + z
}
/// Look up the colors used to visualize the classes found in the image.
private func classListToColorLegend(classList: Set<Int>) -> [String: UIColor] {
var colorLegend: [String: UIColor] = [:]
let sortedClassIndexList = classList.sorted()
sortedClassIndexList.forEach { classIndex in
// Look up the color legend for the class.
// Using modulo to reuse colors on segmentation model with large number of classes.
let color = Constants.legendColorList[classIndex % Constants.legendColorList.count]
// Convert the color from sRGB UInt32 representation to UIColor.
let a = CGFloat((color & 0xFF00_0000) >> 24) / 255.0
let r = CGFloat((color & 0x00FF_0000) >> 16) / 255.0
let g = CGFloat((color & 0x0000_FF00) >> 8) / 255.0
let b = CGFloat(color & 0x0000_00FF) / 255.0
colorLegend[labelList[classIndex]] = UIColor(red: r, green: g, blue: b, alpha: a)
}
return colorLegend
}
}
// MARK: - Types
/// Callback type for image segmentation request.
typealias ImageSegmentationCompletion = (SegmentationResult?, Error?) -> Void
/// Representation of the image segmentation result.
struct SegmentationResult {
/// Segmentation result as an array. Each value represents the most likely class the pixel
/// belongs to.
let array: [[Int]]
/// Visualization of the segmentation result.
let resultImage: UIImage
/// Overlay the segmentation result on input image.
let overlayImage: UIImage
/// Processing time.
let preprocessingTime: TimeInterval
let inferenceTime: TimeInterval
let postProcessingTime: TimeInterval
let visualizationTime: TimeInterval
/// Dictionary of classes found in the image, and the color used to represent the class in
/// segmentation result visualization.
let colorLegend: [String: UIColor]
}
/// 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 in when doing image segmentation
enum SegmentationError: Error {
// Invalid input image
case invalidImage
// TF Lite Internal Error when initializing
case internalError(Error)
// Invalid input image
case resultVisualizationError
}
// MARK: - Constants
private enum Constants {
/// Label list that the segmentation model detects.
static let labelsFileName = "deeplabv3_labels"
static let labelsFileExtension = "json"
/// The TF Lite segmentation model file
static let modelFileName = "deeplabv3_257_mv_gpu"
static let modelFileExtension = "tflite"
/// List of colors to visualize segmentation result.
static let legendColorList: [UInt32] = [
0xFFFF_B300, // Vivid Yellow
0xFF80_3E75, // Strong Purple
0xFFFF_6800, // Vivid Orange
0xFFA6_BDD7, // Very Light Blue
0xFFC1_0020, // Vivid Red
0xFFCE_A262, // Grayish Yellow
0xFF81_7066, // Medium Gray
0xFF00_7D34, // Vivid Green
0xFFF6_768E, // Strong Purplish Pink
0xFF00_538A, // Strong Blue
0xFFFF_7A5C, // Strong Yellowish Pink
0xFF53_377A, // Strong Violet
0xFFFF_8E00, // Vivid Orange Yellow
0xFFB3_2851, // Strong Purplish Red
0xFFF4_C800, // Vivid Greenish Yellow
0xFF7F_180D, // Strong Reddish Brown
0xFF93_AA00, // Vivid Yellowish Green
0xFF59_3315, // Deep Yellowish Brown
0xFFF1_3A13, // Vivid Reddish Orange
0xFF23_2C16, // Dark Olive Green
0xFF00_A1C2, // Vivid Blue
]
}
| 34.497984 | 100 | 0.673368 |
f43a9f8664d65a027bed42fe8d796573e1949f01 | 1,995 | //
// Copyright (c) 2020 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Foundation
import UIKit
/// A view representing a split text item.
internal final class FormSplitTextItemView: FormItemView<FormSplitTextItem> {
/// Initializes the split text item view.
///
/// - Parameter item: The item represented by the view.
internal required init(item: FormSplitTextItem) {
super.init(item: item)
addSubview(stackView)
stackView.adyen.anchore(inside: self)
}
@available(*, unavailable)
internal required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override internal var childItemViews: [AnyFormItemView] {
return [leftItemView, rightItemView]
}
// MARK: - Text Items
private lazy var leftItemView: AnyFormItemView = {
let leftItemView = item.leftItem.build(with: FormItemViewBuilder())
leftItemView.accessibilityIdentifier = item.leftItem.identifier
leftItemView.preservesSuperviewLayoutMargins = true
return leftItemView
}()
private lazy var rightItemView: AnyFormItemView = {
let rightItemView = item.rightItem.build(with: FormItemViewBuilder())
rightItemView.accessibilityIdentifier = item.rightItem.identifier
rightItemView.preservesSuperviewLayoutMargins = true
return rightItemView
}()
// MARK: - Layout
private lazy var stackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: childItemViews)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.preservesSuperviewLayoutMargins = true
stackView.axis = .horizontal
stackView.alignment = .top
stackView.distribution = .fillEqually
stackView.spacing = 16
return stackView
}()
}
| 31.171875 | 100 | 0.673684 |
e6855c6e7182824f441978e6581b8a62166ef791 | 1,905 | //
// OperationTask.swift
// TestNetworkLayers
//
// Created by vinhdd on 3/22/18.
// Copyright © 2018 Rikkeisoft. All rights reserved.
//
import UIKit
import Hydra
import SwiftyJSON
class OperationTask<T: ModelResponseProtocol>: OperationProtocol {
// MARK: - Variables
typealias Output = T
var request: Request! {
return self.request
}
init() { }
// MARK: - Executing functions
func execute(with dispatcher: DispatcherProtocol? = nil, retry: Int? = 1) -> Promise<Output> {
let finalDispatcher = dispatcher ?? NetworkDispatcher.shared
return Promise<Output>({ resolve, reject, status in
do {
try finalDispatcher.execute(request: self.request, retry: retry).then({ response in
let data = self.parse(response: response)
if let output = data.output { resolve(output) }
if let error = data.error { reject(error) }
}).catch(reject)
} catch {
reject(error)
}
})
}
func cancel(with dispatcher: DispatcherProtocol? = nil) {
let finalDispatcher = dispatcher ?? NetworkDispatcher.shared
finalDispatcher.cancel()
}
private func parse(response: Response) -> (output: T?, error: Error?) {
switch response {
case .json(let json):
return (output: T(json: json), error: nil)
case .data(let data):
do {
let json = try JSON.init(data: data)
return (output: T(json: json), error: nil)
} catch {
return (output: nil, error: error)
}
case .error(_, let error):
if let error = error {
return (output: nil, error: error)
}
return (output: nil, error: nil)
}
}
}
| 29.307692 | 99 | 0.545407 |
8ada4bd209c0e126397bbc4fca75af5880f7e8fd | 884 | //
// PreworkTests.swift
// PreworkTests
//
// Created by MAC on 1/16/21.
//
import XCTest
@testable import Prework
class PreworkTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26 | 111 | 0.659502 |
1ebafbbabcde5acd0d82aa2f9f92fe7f48ce8935 | 595 | //
// UITextView+font.swift
// YSAssist
//
// Created by yaoshuai on 2021/1/1.
//
import Foundation
import YSKit
// MARK: - UITextView字体扩展
extension YSOriginalObjectProtocol where OriginalObjectType: UITextView{
@discardableResult func font(_ ofSize: CGFloat) -> OriginalObjectType{
originalObject.font = UIFont.ys.create(ofSize)
return originalObject
}
@discardableResult func font(_ ofSize: CGFloat, type: UIFont.Weight) -> OriginalObjectType{
originalObject.font = UIFont.ys.create(ofSize, type: type)
return originalObject
}
}
| 23.8 | 95 | 0.70084 |
760e84a0da99cbd13197b8478820b10de18233f3 | 2,306 | //
// SceneDelegate.swift
// Fav Places
//
// Created by Kiratijuta Bhumichitr on 26/1/2565 BE.
//
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.509434 | 147 | 0.71379 |
29f5b3640ea67d2fa0e89dd17ec6ad74f594e2f3 | 8,653 | //
// Copyright (c) 2020 Related Code - http://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 Butterfly2View: UIViewController {
@IBOutlet var labelSubTitle: UILabel!
@IBOutlet var labelDescription: UILabel!
@IBOutlet var segmentedControl: UISegmentedControl!
@IBOutlet var labelDate: UILabel!
@IBOutlet var labelTimer1: UILabel!
@IBOutlet var labelTimer2: UILabel!
@IBOutlet var viewStopWatch: UIView!
@IBOutlet var buttonPlus: UIButton!
@IBOutlet var tableView: UITableView!
@IBOutlet var layoutConstraintTableViewHeight: NSLayoutConstraint!
@IBOutlet var labelprocess: UILabel!
@IBOutlet var labelName: UILabel!
@IBOutlet var labelReps: UILabel!
private var repeats: [[String: String]] = []
//---------------------------------------------------------------------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
title = "Butterfly"
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .always
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "ellipsis"), style: .plain, target: self, action: #selector(actionMenu(_:)))
viewStopWatch.layer.borderWidth = 1
viewStopWatch.layer.borderColor = AppColor.Border.cgColor
buttonPlus.layer.borderWidth = 1
buttonPlus.layer.borderColor = AppColor.Border.cgColor
tableView.register(UINib(nibName: "Butterfly2Cell", bundle: Bundle.main), forCellReuseIdentifier: "Butterfly2Cell")
loadData()
updateUI()
layoutConstraintTableViewHeight.constant = CGFloat(45 * repeats.count)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateUI()
}
// MARK: - Data methods
//---------------------------------------------------------------------------------------------------------------------------------------------
func loadData() {
labelSubTitle.text = "4 / 15 reps"
labelDescription.text = "This course is designed for the complete beginner, so there’s no need to be wary if you have no previous yoga experience."
labelDate.text = "05 Apr 2020"
labelTimer1.text = "00:00:00"
labelTimer2.text = "00:00"
labelprocess.text = "1/2"
labelName.text = "Machine Bench Press"
labelReps.text = "4 / 15 reps."
repeats.removeAll()
var dict1: [String: String] = [:]
dict1["title"] = "50 kg / 10 reps"
dict1["time"] = "1:40"
repeats.append(dict1)
var dict2: [String: String] = [:]
dict2["title"] = "80 kg / 8 reps"
dict2["time"] = "2:15"
repeats.append(dict2)
var dict3: [String: String] = [:]
dict3["title"] = "50 kg / 10 reps"
dict3["time"] = "1:12"
repeats.append(dict3)
refreshTableView()
}
// MARK: - Refresh methods
//---------------------------------------------------------------------------------------------------------------------------------------------
func refreshTableView() {
tableView.reloadData()
}
// MARK: - Helper methods
//---------------------------------------------------------------------------------------------------------------------------------------------
func updateUI() {
let background = UIColor.systemBackground.image(segmentedControl.frame.size)
let selected = AppColor.Theme.image(segmentedControl.frame.size)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.white], for: .selected)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : AppColor.Theme], for: .normal)
segmentedControl.setBackgroundImage(background, for: .normal, barMetrics: .default)
segmentedControl.setBackgroundImage(selected, for: .selected, barMetrics: .default)
segmentedControl.setDividerImage(UIColor.clear.image(), forLeftSegmentState: .normal, rightSegmentState: [.normal, .highlighted, .selected], barMetrics: .default)
segmentedControl.layer.borderWidth = 1
segmentedControl.layer.borderColor = AppColor.Theme.cgColor
}
// MARK: - User actions
//---------------------------------------------------------------------------------------------------------------------------------------------
@objc func actionMenu(_ sender: UIButton) {
print(#function)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
@IBAction func actionSegmentChange(_ sender: UISegmentedControl) {
print(#function)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
@IBAction func actionPlay(_ sender: UIButton) {
print(#function)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
@IBAction func actionStopWatch(_ sender: UIButton) {
print(#function)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
@IBAction func actionPlus(_ sender: UIButton) {
print(#function)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
@IBAction func actionNext(_ sender: UIButton) {
print(#function)
}
}
// MARK: - UITableViewDataSource
//-------------------------------------------------------------------------------------------------------------------------------------------------
extension Butterfly2View: UITableViewDataSource {
//---------------------------------------------------------------------------------------------------------------------------------------------
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repeats.count
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Butterfly2Cell", for: indexPath) as! Butterfly2Cell
cell.bindData(index: indexPath, data: repeats[indexPath.row])
return cell
}
}
// MARK: - UITableViewDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
extension Butterfly2View: UITableViewDelegate {
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(#function)
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - UIColor
//-------------------------------------------------------------------------------------------------------------------------------------------------
fileprivate extension UIColor {
//---------------------------------------------------------------------------------------------------------------------------------------------
func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { rendererContext in
setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
}
| 40.624413 | 164 | 0.482954 |
fecae909b5090fdf8da0ab77abee26aea0ed5e73 | 3,674 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
@testable import PersistenceExporter
import OpenTelemetryApi
import OpenTelemetrySdk
import XCTest
class PersistenceSpanExporterDecoratorTests: XCTestCase {
class SpanExporterMock: SpanExporter {
let onExport: ([SpanData]) -> SpanExporterResultCode
let onFlush: () -> SpanExporterResultCode
let onShutdown: () -> Void
init(onExport: @escaping ([SpanData]) -> SpanExporterResultCode,
onFlush: @escaping () -> SpanExporterResultCode = { return .success },
onShutdown: @escaping () -> Void = {}) {
self.onExport = onExport
self.onFlush = onFlush
self.onShutdown = onShutdown
}
@discardableResult func export(spans: [SpanData]) -> SpanExporterResultCode {
return onExport(spans)
}
func flush() -> SpanExporterResultCode {
return onFlush()
}
func shutdown() {
onShutdown()
}
}
override func setUp() {
super.setUp()
temporaryDirectory.create()
}
override func tearDown() {
temporaryDirectory.delete()
super.tearDown()
}
func testWhenExportMetricIsCalled_thenSpansAreExported() throws {
let spansExportExpectation = self.expectation(description: "spans exported")
let exporterShutdownExpectation = self.expectation(description: "exporter shut down")
let mockSpanExporter = SpanExporterMock(onExport: { spans in
spans.forEach { span in
if span.name == "SimpleSpan" &&
span.events.count == 1 &&
span.events.first!.name == "My event" {
spansExportExpectation.fulfill()
}
}
return .success
}, onShutdown: {
exporterShutdownExpectation.fulfill()
})
let persistenceSpanExporter =
try PersistenceSpanExporterDecorator(
spanExporter: mockSpanExporter,
storageURL: temporaryDirectory.url,
writerQueue: DispatchQueue(label: "spanWriterQueue"),
readerQueue: DispatchQueue(label: "spanReaderQueue"),
exportQueue: DispatchQueue(label: "spanExportQueue"),
exportCondition: { return true },
performancePreset: PersistencePerformancePreset.mockWith(
storagePerformance: StoragePerformanceMock.writeEachObjectToNewFileAndReadAllFiles,
synchronousWrite: true,
exportPerformance: ExportPerformanceMock.veryQuick))
let instrumentationLibraryName = "SimpleExporter"
let instrumentationLibraryVersion = "semver:0.1.0"
let tracer = OpenTelemetrySDK.instance.tracerProvider.get(instrumentationName: instrumentationLibraryName, instrumentationVersion: instrumentationLibraryVersion) as! TracerSdk
let spanProcessor = SimpleSpanProcessor(spanExporter: persistenceSpanExporter)
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor)
simpleSpan(tracer: tracer)
spanProcessor.shutdown()
waitForExpectations(timeout: 10, handler: nil)
}
private func simpleSpan(tracer: TracerSdk) {
let span = tracer.spanBuilder(spanName: "SimpleSpan").setSpanKind(spanKind: .client).startSpan()
span.addEvent(name: "My event", timestamp: Date())
span.end()
}
}
| 36.376238 | 183 | 0.616494 |
2fe6358f25b396b83903a4892cb100d9f112f190 | 785 | //
// GHBodyLabel.swift
// GithubApp
//
// Created by Umut Can Arslan on 27.03.2022.
//
import UIKit
class GHBodyLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(textAlignment: NSTextAlignment) {
self.init(frame: .zero)
self.textAlignment = textAlignment
}
private func configure() {
textColor = .secondaryLabel
font = UIFont.preferredFont(forTextStyle: .body)
adjustsFontForContentSizeCategory = true
adjustsFontSizeToFitWidth = true
minimumScaleFactor = 0.75
lineBreakMode = .byWordWrapping
}
}
| 21.805556 | 59 | 0.626752 |
de1076f8155810eb0e2856c1ce4340017cf62e64 | 11,556 | /*
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
-------------------------------------------------------------------------
This file defines JSON support infrastructure. It is not designed to be general
purpose JSON utilities, but rather just the infrastructure which SwiftPM needs
to manage serialization of data through JSON.
*/
// MARK: JSON Item Definition
/// A JSON value.
///
/// This type uses container wrappers in order to allow for mutable elements.
public enum JSON {
/// The null value.
case null
/// A boolean value.
case bool(Bool)
/// An integer value.
///
/// While not strictly present in JSON, we use this as a convenience to
/// parsing code.
case int(Int)
/// A floating-point value.
case double(Double)
/// A string.
case string(String)
/// An array.
case array([JSON])
/// A dictionary.
case dictionary([String: JSON])
/// An ordered dictionary.
case orderedDictionary(KeyValuePairs<String, JSON>)
}
/// A JSON representation of an element.
public protocol JSONSerializable {
/// Return a JSON representation.
func toJSON() -> JSON
}
extension JSON: CustomStringConvertible {
public var description: Swift.String {
switch self {
case .null: return "null"
case .bool(let value): return value.description
case .int(let value): return value.description
case .double(let value): return value.description
case .string(let value): return value.debugDescription
case .array(let values): return values.description
case .dictionary(let values): return values.description
case .orderedDictionary(let values): return values.description
}
}
}
/// Equatable conformance.
extension JSON: Equatable {
public static func == (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case (.null, .null): return true
case (.null, _): return false
case (.bool(let a), .bool(let b)): return a == b
case (.bool, _): return false
case (.int(let a), .int(let b)): return a == b
case (.int, _): return false
case (.double(let a), .double(let b)): return a == b
case (.double, _): return false
case (.string(let a), .string(let b)): return a == b
case (.string, _): return false
case (.array(let a), .array(let b)): return a == b
case (.array, _): return false
case (.dictionary(let a), .dictionary(let b)): return a == b
case (.dictionary, _): return false
case (.orderedDictionary(let a), .orderedDictionary(let b)): return a == b
case (.orderedDictionary, _): return false
}
}
}
// MARK: JSON Encoding
extension JSON {
/// Encode a JSON item into a string of bytes.
public func toBytes(prettyPrint: Bool = false) -> ByteString {
let stream = BufferedOutputByteStream()
write(to: stream, indent: prettyPrint ? 0 : nil)
if prettyPrint {
stream.write("\n")
}
return stream.bytes
}
/// Encode a JSON item into a JSON string
public func toString(prettyPrint: Bool = false) -> String {
return toBytes(prettyPrint: prettyPrint).description
}
}
/// Support writing to a byte stream.
extension JSON: ByteStreamable {
public func write(to stream: WritableByteStream) {
write(to: stream, indent: nil)
}
public func write(to stream: WritableByteStream, indent: Int?) {
func indentStreamable(offset: Int? = nil) -> ByteStreamable {
return Format.asRepeating(string: " ", count: indent.flatMap({ $0 + (offset ?? 0) }) ?? 0)
}
let shouldIndent = indent != nil
switch self {
case .null:
stream <<< "null"
case .bool(let value):
stream <<< Format.asJSON(value)
case .int(let value):
stream <<< Format.asJSON(value)
case .double(let value):
// FIXME: What happens for NaN, etc.?
stream <<< Format.asJSON(value)
case .string(let value):
stream <<< Format.asJSON(value)
case .array(let contents):
stream <<< "[" <<< (shouldIndent ? "\n" : "")
for (i, item) in contents.enumerated() {
if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") }
stream <<< indentStreamable(offset: 2)
item.write(to: stream, indent: indent.flatMap({ $0 + 2 }))
}
stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "]"
case .dictionary(let contents):
// We always output in a deterministic order.
stream <<< "{" <<< (shouldIndent ? "\n" : "")
for (i, key) in contents.keys.sorted().enumerated() {
if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") }
stream <<< indentStreamable(offset: 2) <<< Format.asJSON(key) <<< ": "
contents[key]!.write(to: stream, indent: indent.flatMap({ $0 + 2 }))
}
stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "}"
case .orderedDictionary(let contents):
stream <<< "{" <<< (shouldIndent ? "\n" : "")
for (i, item) in contents.enumerated() {
if i != 0 { stream <<< "," <<< (shouldIndent ? "\n" : " ") }
stream <<< indentStreamable(offset: 2) <<< Format.asJSON(item.key) <<< ": "
item.value.write(to: stream, indent: indent.flatMap({ $0 + 2 }))
}
stream <<< (shouldIndent ? "\n" : "") <<< indentStreamable() <<< "}"
}
}
}
// MARK: JSON Decoding
import Foundation
enum JSONDecodingError: Swift.Error {
/// The input byte string is malformed.
case malformed
}
// NOTE: This implementation is carefully crafted to work correctly on both
// Linux and OS X while still compiling for both. Thus, the implementation takes
// Any even though it could take AnyObject on OS X, and it uses converts to
// direct Swift types (for Linux) even though those don't apply on OS X.
//
// This allows the code to be portable, and expose a portable API, but it is not
// very efficient.
private let nsBooleanType = type(of: NSNumber(value: false))
extension JSON {
private static func convertToJSON(_ object: Any) -> JSON {
switch object {
case is NSNull:
return .null
case let value as String:
return .string(value)
case let value as NSNumber:
// Check if this is a boolean.
//
// FIXME: This is all rather unfortunate and expensive.
if type(of: value) === nsBooleanType {
return .bool(value != 0)
}
// Check if this is an exact integer.
//
// FIXME: This is highly questionable. Aside from the performance of
// decoding in this fashion, it means clients which truly have
// arrays of real numbers will need to be prepared to see either an
// .int or a .double. However, for our specific use case we usually
// want to get integers out of JSON, and so it seems an ok tradeoff
// versus forcing all clients to cast out of a double.
let asInt = value.intValue
if NSNumber(value: asInt) == value {
return .int(asInt)
}
// Otherwise, we have a floating point number.
return .double(value.doubleValue)
case let value as NSArray:
return .array(value.map(convertToJSON))
case let value as NSDictionary:
var result = [String: JSON]()
for (key, val) in value {
result[key as! String] = convertToJSON(val)
}
return .dictionary(result)
// On Linux, the JSON deserialization handles this.
case let asBool as Bool: // This is true on Linux.
return .bool(asBool)
case let asInt as Int: // This is true on Linux.
return .int(asInt)
case let asDouble as Double: // This is true on Linux.
return .double(asDouble)
case let value as [Any]:
return .array(value.map(convertToJSON))
case let value as [String: Any]:
var result = [String: JSON]()
for (key, val) in value {
result[key] = convertToJSON(val)
}
return .dictionary(result)
default:
fatalError("unexpected object: \(object) \(type(of: object))")
}
}
/// Load a JSON item from a Data object.
public init(data: Data) throws {
do {
let result = try JSONSerialization.jsonObject(with: data, options: [.allowFragments])
// Convert to a native representation.
//
// FIXME: This is inefficient; eventually, we want a way to do the
// loading and not need to copy / traverse all of the data multiple
// times.
self = JSON.convertToJSON(result)
} catch {
throw JSONDecodingError.malformed
}
}
/// Load a JSON item from a byte string.
public init(bytes: ByteString) throws {
try self.init(data: Data(bytes.contents))
}
/// Convenience initalizer for UTF8 encoded strings.
///
/// - Throws: JSONDecodingError
public init(string: String) throws {
let bytes = ByteString(encodingAsUTF8: string)
try self.init(bytes: bytes)
}
}
// MARK: - JSONSerializable helpers.
extension JSON {
public init(_ dict: [String: JSONSerializable]) {
self = .dictionary(dict.mapValues({ $0.toJSON() }))
}
}
extension Int: JSONSerializable {
public func toJSON() -> JSON {
return .int(self)
}
}
extension Double: JSONSerializable {
public func toJSON() -> JSON {
return .double(self)
}
}
extension String: JSONSerializable {
public func toJSON() -> JSON {
return .string(self)
}
}
extension Bool: JSONSerializable {
public func toJSON() -> JSON {
return .bool(self)
}
}
extension AbsolutePath: JSONSerializable {
public func toJSON() -> JSON {
return .string(pathString)
}
}
extension RelativePath: JSONSerializable {
public func toJSON() -> JSON {
return .string(pathString)
}
}
extension Array: JSONSerializable where Element: JSONSerializable {
public func toJSON() -> JSON {
return .array(self.map({ $0.toJSON() }))
}
}
extension Dictionary: JSONSerializable where Key == String, Value: JSONSerializable {
public func toJSON() -> JSON {
return .dictionary(self.mapValues({ $0.toJSON() }))
}
}
extension Optional where Wrapped: JSONSerializable {
public func toJSON() -> JSON {
switch self {
case .some(let wrapped): return wrapped.toJSON()
case .none: return .null
}
}
}
extension Sequence where Iterator.Element: JSONSerializable {
public func toJSON() -> JSON {
return .array(map({ $0.toJSON() }))
}
}
extension JSON: JSONSerializable {
public func toJSON() -> JSON {
return self
}
}
| 32.736544 | 102 | 0.582728 |
690dd7937e4dca183decf59cf5d570356d8adaf4 | 11,483 | //===----------------------------------------------------------------------===//
//
// 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
/// A channel handler that creates a child channel for each HTTP/2 stream.
///
/// In general in NIO applications it is helpful to consider each HTTP/2 stream as an
/// independent stream of HTTP/2 frames. This multiplexer achieves this by creating a
/// number of in-memory `HTTP2StreamChannel` objects, one for each stream. These operate
/// on `HTTP2Frame` objects as their base communication atom, as opposed to the regular
/// NIO `SelectableChannel` objects which use `ByteBuffer` and `IOData`.
public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboundHandler {
public typealias InboundIn = HTTP2Frame
public typealias InboundOut = HTTP2Frame
public typealias OutboundIn = HTTP2Frame
public typealias OutboundOut = HTTP2Frame
private var streams: [HTTP2StreamID: HTTP2StreamChannel] = [:]
private let inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture<Void>)?
private let channel: Channel
private var context: ChannelHandlerContext!
private var nextOutboundStreamID: HTTP2StreamID
private var connectionFlowControlManager: InboundWindowManager
private var flushState: FlushState = .notReading
public func handlerAdded(context: ChannelHandlerContext) {
// We now need to check that we're on the same event loop as the one we were originally given.
// If we weren't, this is a hard failure, as there is a thread-safety issue here.
self.channel.eventLoop.preconditionInEventLoop()
self.context = context
}
public func handlerRemoved(context: ChannelHandlerContext) {
self.context = nil
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
let streamID = frame.streamID
self.flushState.startReading()
guard streamID != .rootStream else {
// For stream 0 we forward all frames on to the main channel.
context.fireChannelRead(data)
return
}
if case .priority = frame.payload {
// Priority frames are special cases, and are always forwarded to the parent stream.
context.fireChannelRead(data)
return
}
if let channel = streams[streamID] {
channel.receiveInboundFrame(frame)
} else if case .headers = frame.payload {
let channel = HTTP2StreamChannel(allocator: self.channel.allocator,
parent: self.channel,
multiplexer: self,
streamID: streamID,
targetWindowSize: 65535)
self.streams[streamID] = channel
channel.configure(initializer: self.inboundStreamStateInitializer, userPromise: nil)
channel.receiveInboundFrame(frame)
} else {
// This frame is for a stream we know nothing about. We can't do much about it, so we
// are going to fire an error and drop the frame.
let error = NIOHTTP2Errors.NoSuchStream(streamID: streamID)
context.fireErrorCaught(error)
}
}
public func channelReadComplete(context: ChannelHandlerContext) {
if case .flushPending = self.flushState {
self.flushState = .notReading
context.flush()
} else {
self.flushState = .notReading
}
context.fireChannelReadComplete()
}
public func flush(context: ChannelHandlerContext) {
switch self.flushState {
case .reading, .flushPending:
self.flushState = .flushPending
case .notReading:
context.flush()
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
/* for now just forward */
context.write(data, promise: promise)
}
public func channelActive(context: ChannelHandlerContext) {
// We just got channelActive. Any previously existing channels may be marked active.
for channel in self.streams.values {
// We double-check the channel activity here, because it's possible action taken during
// the activation of one of the child channels will cause the parent to close!
if context.channel.isActive {
channel.performActivation()
}
}
context.fireChannelActive()
}
public func channelInactive(context: ChannelHandlerContext) {
for channel in self.streams.values {
channel.receiveStreamClosed(nil)
}
context.fireChannelInactive()
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
switch event {
case let evt as StreamClosedEvent:
if let channel = self.streams[evt.streamID] {
channel.receiveStreamClosed(evt.reason)
}
case let evt as NIOHTTP2WindowUpdatedEvent where evt.streamID == .rootStream:
// This force-unwrap is safe: we always have a connection window.
self.newConnectionWindowSize(newSize: evt.inboundWindowSize!, context: context)
case let evt as NIOHTTP2WindowUpdatedEvent:
if let channel = self.streams[evt.streamID], let windowSize = evt.inboundWindowSize {
channel.receiveWindowUpdatedEvent(windowSize)
}
case let evt as NIOHTTP2BulkStreamWindowChangeEvent:
// Here we need to pull the channels out so we aren't holding the streams dict mutably. This is because it
// will trigger an overlapping access violation if we do.
let channels = self.streams.values
for channel in channels {
channel.initialWindowSizeChanged(delta: evt.delta)
}
case let evt as NIOHTTP2StreamCreatedEvent:
if let channel = self.streams[evt.streamID] {
channel.networkActivationReceived()
}
default:
break
}
context.fireUserInboundEventTriggered(event)
}
private func newConnectionWindowSize(newSize: Int, context: ChannelHandlerContext) {
guard let increment = self.connectionFlowControlManager.newWindowSize(newSize) else {
return
}
// This is too much flushing, but for now it'll have to do.
let frame = HTTP2Frame(streamID: .rootStream, payload: .windowUpdate(windowSizeIncrement: increment))
context.writeAndFlush(self.wrapOutboundOut(frame), promise: nil)
}
/// Create a new `HTTP2StreamMultiplexer`.
///
/// - parameters:
/// - mode: The mode of the HTTP/2 connection being used: server or client.
/// - channel: The Channel to which this `HTTP2StreamMultiplexer` belongs.
/// - targetWindowSize: The target inbound connection and stream window size. Defaults to 65535 bytes.
/// - inboundStreamStateInitializer: A block that will be invoked to configure each new child stream
/// channel that is created by the remote peer. For servers, these are channels created by
/// receiving a `HEADERS` frame from a client. For clients, these are channels created by
/// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use
/// `createStreamChannel`.
public init(mode: NIOHTTP2Handler.ParserMode, channel: Channel, targetWindowSize: Int = 65535, inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture<Void>)? = nil) {
self.inboundStreamStateInitializer = inboundStreamStateInitializer
self.channel = channel
self.connectionFlowControlManager = InboundWindowManager(targetSize: Int32(targetWindowSize))
switch mode {
case .client:
self.nextOutboundStreamID = 1
case .server:
self.nextOutboundStreamID = 2
}
}
}
extension HTTP2StreamMultiplexer {
/// The state of the multiplexer for flush coalescing.
///
/// The stream multiplexer aims to perform limited flush coalescing on the read side by delaying flushes from the child and
/// parent channels until channelReadComplete is received. To do this we need to track what state we're in.
enum FlushState {
/// No channelReads have been fired since the last channelReadComplete, so we probably aren't reading. Let any
/// flushes through.
case notReading
/// We've started reading, but don't have any pending flushes.
case reading
/// We're in the read loop, and have received a flush.
case flushPending
mutating func startReading() {
if case .notReading = self {
self = .reading
}
}
}
}
extension HTTP2StreamMultiplexer {
/// Create a new `Channel` for a new stream initiated by this peer.
///
/// This method is intended for situations where the NIO application is initiating the stream. For clients,
/// this is for all request streams. For servers, this is for pushed streams.
///
/// - note:
/// Resources for the stream will be freed after it has been closed.
///
/// - parameters:
/// - promise: An `EventLoopPromise` that will be succeeded with the new activated channel, or
/// failed if an error occurs.
/// - streamStateInitializer: A callback that will be invoked to allow you to configure the
/// `ChannelPipeline` for the newly created channel.
public func createStreamChannel(promise: EventLoopPromise<Channel>?, _ streamStateInitializer: @escaping (Channel, HTTP2StreamID) -> EventLoopFuture<Void>) {
self.channel.eventLoop.execute {
let streamID = self.nextOutboundStreamID
self.nextOutboundStreamID = HTTP2StreamID(Int32(streamID) + 2)
let channel = HTTP2StreamChannel(allocator: self.channel.allocator,
parent: self.channel,
multiplexer: self,
streamID: streamID,
targetWindowSize: 65535) // TODO: make configurable
self.streams[streamID] = channel
channel.configure(initializer: streamStateInitializer, userPromise: promise)
}
}
}
// MARK:- Child to parent calls
extension HTTP2StreamMultiplexer {
internal func childChannelClosed(streamID: HTTP2StreamID) {
self.streams.removeValue(forKey: streamID)
}
internal func childChannelWrite(_ frame: HTTP2Frame, promise: EventLoopPromise<Void>?) {
self.context.write(self.wrapOutboundOut(frame), promise: promise)
}
internal func childChannelFlush() {
self.flush(context: context)
}
}
| 43.007491 | 191 | 0.641557 |
dbb78fd6a18b5e3b173f06f0dcfffc7be7dae555 | 3,160 | //
// RVIntentHandler.swift
// Patriot
//
// Created by Ron Lisle on 5/20/22.
//
import SwiftUI
import Intents
class RVHandler: NSObject, RVIntentHandling {
let application: UIApplication
init(application: UIApplication) {
self.application = application
}
//TODO: convert to async/await (see protocol)
func handle(intent: RVIntent, completion: @escaping (RVIntentResponse) -> Void) {
print("RVHandler handle RVIntent")
guard let device = intent.device,
let percent = intent.percent as? Int else {
print("handle(intent) missing arguments")
completion(RVIntentResponse(code: .failure, userActivity: nil))
return
}
if application.applicationState == .background {
// If app is in background, return .continueInApp to launch app
print("RVHandler in background")
PatriotModel.shared.sendMessage(topic: "patriot/\(device)", message: "\(percent)")
completion(RVIntentResponse(code: .success, userActivity: nil))
//completion(RVIntentResponse(code: .continueInApp, userActivity: nil))
} else {
print("RVHandler in foreground")
// Update UI
guard let deviceObj = PatriotModel.shared.getDevice(name: device) else {
print("handle(intent) device not found")
completion(RVIntentResponse(code: .failure, userActivity: nil))
return
}
deviceObj.manualSet(percent: percent)
completion(RVIntentResponse(code: .success, userActivity: nil))
}
}
func resolveDevice(for intent: RVIntent, with completion: @escaping (INStringResolutionResult) -> Swift.Void) {
guard let device = intent.device else {
print("RVHandler resolveDevice: needsValue")
completion(INStringResolutionResult.needsValue())
return
}
print("RVHandler resolveDevice: \(device)")
guard PatriotModel.shared.getDevice(name: device) != nil else {
print("RVHandler resolveDevice: unrecognized device \(device)")
completion(INStringResolutionResult.needsValue())
return
}
print("RVHandler resolveDevice: recognized device \(device)")
completion(INStringResolutionResult.success(with: device))
}
func resolvePercent(for intent: RVIntent, with completion: @escaping (RVPercentResolutionResult) -> Swift.Void) {
print("RVHandler resolvePercent")
//TODO:
guard let percent = intent.percent as? Int else {
print("RVHandler resolvePercent: needsValue")
completion(RVPercentResolutionResult.needsValue())
return
}
var goodPercent = percent
if goodPercent > 100 { goodPercent = 100 }
if goodPercent < 0 { goodPercent = 0 }
completion(RVPercentResolutionResult.success(with: goodPercent))
}
//TODO: Add confirm method
}
| 33.263158 | 117 | 0.606013 |
612fe1de1482924241b78ef664521364b97f3ff3 | 845 | //
// AddressDataStore.swift
// Nanopool Client
//
// Created by Florin Uscatu on 24/10/2019.
// Copyright © 2019 Florin Uscatu. All rights reserved.
//
import Foundation
class AddressDataStore {
private let savedAddressesKey = "savedAddresses"
static let shared = AddressDataStore()
func saveAddress(_ address: LocalAddress) throws {
var addresses = try getAddresses()
addresses.append(address)
let addressesData = try JSONEncoder().encode(addresses)
UserDefaults.standard.set(addressesData, forKey: savedAddressesKey)
}
func getAddresses() throws -> [LocalAddress] {
guard let addressesData = UserDefaults.standard.data(forKey: savedAddressesKey) else { return [] }
return try JSONDecoder().decode([LocalAddress].self, from: addressesData)
}
}
| 29.137931 | 106 | 0.688757 |
d600c491813919d53e338d55584f23156cb4511d | 4,424 | // RUN: %target-run-stdlib-swift | %FileCheck %s
// REQUIRES: executable_test
//
// Parts of this test depend on memory allocator specifics. The test
// should be rewritten soon so it doesn't expose legacy components
// like OpaqueString anyway, so we can just disable the failing
// configuration
//
// Memory allocator specifics also vary across platforms.
// REQUIRES: CPU=x86_64, OS=macosx
import Foundation
import Swift
func hex(_ x: UInt64) -> String { return String(x, radix:16) }
func hexAddrVal<T>(_ x: T) -> String {
return "@0x" + hex(UInt64(unsafeBitCast(x, to: UInt.self)))
}
func repr(_ x: NSString) -> String {
return "\(NSStringFromClass(object_getClass(x)!))\(hexAddrVal(x)) = \"\(x)\""
}
func repr(_ x: _StringRepresentation) -> String {
switch x._form {
case ._small:
return """
Small(count: \(x._count))
"""
case ._cocoa(let object):
return """
Cocoa(\
owner: \(hexAddrVal(object)), \
count: \(x._count))
"""
case ._native(let object):
return """
Native(\
owner: \(hexAddrVal(object)), \
count: \(x._count), \
capacity: \(x._capacity))
"""
case ._immortal(_):
return """
Unmanaged(count: \(x._count))
"""
}
}
func repr(_ x: String) -> String {
return "String(\(repr(x._classify()))) = \"\(x)\""
}
// ===------- Appending -------===
// CHECK-LABEL: --- Appending ---
print("--- Appending ---")
var s = "⓪" // start non-empty
// To make this test independent of the memory allocator implementation,
// explicitly request initial capacity.
s.reserveCapacity(16)
// CHECK-NEXT: String(Native(owner: @[[storage0:[x0-9a-f]+]], count: 3, capacity: 23)) = "⓪"
print("\(repr(s))")
// CHECK-NEXT: String(Native(owner: @[[storage0]], count: 4, capacity: 23)) = "⓪1"
s += "1"
print("\(repr(s))")
// CHECK-NEXT: String(Native(owner: @[[storage0]], count: 10, capacity: 23)) = "⓪1234567"
s += "234567"
print("\(repr(s))")
// CHECK-NEXT: String(Native(owner: @[[storage0]], count: 11, capacity: 23)) = "⓪12345678"
// CHECK-NOT: @[[storage0]],
s += "8"
print("\(repr(s))")
// CHECK-NEXT: String(Native(owner: @[[storage0]], count: 18, capacity: 23)) = "⓪123456789012345"
s += "9012345"
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-LABEL: (expecting reallocation)
print("(expecting reallocation)")
// Appending more than the next level of capacity only takes as much
// as required. I'm not sure whether this is a great idea, but the
// point is to prevent huge amounts of fragmentation when a long
// string is appended to a short one. The question, of course, is
// whether more appends are coming, in which case we should give it
// more capacity. It might be better to always grow to a multiple of
// the current capacity when the capacity is exceeded.
// CHECK-NEXT: String(Native(owner: @[[storage1:[x0-9a-f]+]], count: 54, capacity: 55))
// CHECK-NOT: @[[storage1]],
s += s + s
print("\(repr(s))")
// CHECK-NEXT: String(Native(owner: @[[storage1]], count: 55, capacity: 55))
s += "C"
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-LABEL: (expecting second reallocation)
print("(expecting second reallocation)")
// CHECK-NEXT: String(Native(owner: @[[storage2:[x0-9a-f]+]], count: 56, capacity: 119))
// CHECK-NOT: @[[storage1]],
s += "C"
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-LABEL: (expecting third reallocation)
print("(expecting third reallocation)")
// CHECK-NEXT: String(Native(owner: @[[storage3:[x0-9a-f]+]], count: 72, capacity: 119))
// CHECK-NOT: @[[storage2]],
s += "1234567890123456"
print("\(repr(s))")
var s1 = s
// CHECK-NEXT: String(Native(owner: @[[storage3]], count: 72, capacity: 119))
print("\(repr(s1))")
/// The use of later buffer capacity by another string forces
/// reallocation; however, the original capacity is kept by intact
// CHECK-LABEL: (expect copy to trigger reallocation without growth)
print("(expect copy to trigger reallocation without growth)")
// CHECK-NEXT: String(Native(owner: @[[storage4:[x0-9a-f]+]], count: 73, capacity: 87)) = "{{.*}}X"
// CHECK-NOT: @[[storage3]],
s1 += "X"
print("\(repr(s1))")
/// The original copy is left unchanged
// CHECK-NEXT: String(Native(owner: @[[storage3]], count: 72, capacity: 119))
print("\(repr(s))")
/// Appending to an empty string re-uses the RHS
// CHECK-NEXT: @[[storage3]],
var s2 = String()
s2 += s
print("\(repr(s2))")
| 29.105263 | 99 | 0.642857 |
d5aff4fbbd99cc51fa8400c7ff160ff208df701b | 4,619 | //
// ScanViewModel.swift
// BLE-iOS
//
// Created by James Taylor on 5/24/20.
// Copyright © 2020 James Taylor. All rights reserved.
//
// Developed using documentation available at
// https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/AboutCoreBluetooth/Introduction.html#//apple_ref/doc/uid/TP40013257
// This app acts a central to scanned peripherals. A peripheral typically has data that is needed by other devices.
// A central typically uses the information served up by a peripheral to accomplish some task.
// By default, your app is unable to perform Bluetooth Low Energy tasks while it is in the background or in a suspended state.
// You can declare background support for one or both of the Core Bluetooth background execution modes (there’s one for the central role, and one for the peripheral role).
// Even apps that support background processing may be terminated by the system at any time to free up memory for the current foreground app.
import Foundation
import CoreBluetooth
class BleDevice: Equatable, Hashable {
var peripheral: CBPeripheral? = nil;
var advertisementData: [String : Any] = [:];
var rssi: Double = 0.0
var connected: Bool = false
static func == (lhs: BleDevice, rhs: BleDevice) -> Bool {return lhs.peripheral == rhs.peripheral}
func hash(into hasher: inout Hasher) {hasher.combine(peripheral)}
}
class BluetoothViewModel: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {
@Published var results = [BleDevice]()
@Published var showActivityIndicator = false
@Published var isConnected = false
private var centralManager: CBCentralManager? = nil
override init() {
super.init()
centralManager = CBCentralManager.init(delegate: self, queue: nil)//specifying the dispatch queue as nil, the central manager dispatches central role events using the main queue
}
internal func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .resetting: print("BLE resetting")
case .unsupported: print("BLE unsupported")
case .unauthorized: print("BLE unauthorized")//TODO: Message user to authorize bluetooth
case .poweredOff: print("BLE turned off")//TODO: Message user to turn on bluetooth
case .poweredOn: print("BLE turned on")
case .unknown: print("BLE unknown state")
@unknown default: print("BLE unknown state \(central.state)")
}
print(central.state)
}
//MARK: - Scanning
func startScan(){
centralManager?.scanForPeripherals(withServices: nil, options: nil)//specifying nil for the first parameter, the central manager returns all discovered peripherals, regardless of their supported services
showActivityIndicator = centralManager?.isScanning ?? false
}
func stopScan(){
centralManager?.stopScan()
showActivityIndicator = centralManager?.isScanning ?? false
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
let device = BleDevice()
device.peripheral = peripheral
device.advertisementData = advertisementData
device.rssi = RSSI.doubleValue
if results.contains(device) { return }
results.append(device)
}
//MARK: - Connecting
func connectTo(peripheral: CBPeripheral) {
centralManager?.connect(peripheral, options: nil)
showActivityIndicator = true
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral){
results.first{ $0.peripheral == peripheral }?.connected = true
self.isConnected = true
self.showActivityIndicator = false
}
func disconnectFrom(peripheral: CBPeripheral) {
results.first{ $0.peripheral == peripheral }?.connected = false
centralManager?.cancelPeripheralConnection(peripheral)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
results.first{ $0.peripheral == peripheral }?.connected = false
self.isConnected = false
self.showActivityIndicator = false
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
results.first{ $0.peripheral == peripheral }?.connected = false
self.isConnected = false
self.showActivityIndicator = false
}
}
| 45.732673 | 211 | 0.713141 |
e5e64d3525870cebd5a07f579a6bd2ffa98daec4 | 727 | // RUN: %empty-directory(%t)
// RUN: %swift_driver_plain --driver-mode=swiftc -target armv7-none-linux-androideabihf -emit-executable %s -### 2>&1 | %FileCheck %s -check-prefix CHECK-ARMv7
// CHECK-ARMv7: clang{{(.exe)?"?}} -target armv7-unknown-linux-androideabi
// RUN: %swift_driver_plain --driver-mode=swiftc -target aarch64-mone-linux-androideabi -emit-executable %s -### 2>&1 | %FileCheck %s -check-prefix CHECK-ARM64
// CHECK-ARM64: clang{{(.exe)?"?}} -target aarch64-unknown-linux-android
// RUN: %swift_driver_plain --driver-mode=swiftc -target x86_64-none-linux-androideabi -emit-executable %s -### 2>&1 | %FileCheck %s -check-prefix CHECK-X64
// CHECK-X64: clang{{(.exe)?"?}} -target x86_64-unknown-linux-android
| 66.090909 | 159 | 0.712517 |
3358b702269948ee4d04241b3a84bc68943e1ce5 | 4,284 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// An end-to-end test that we can differentiate property accesses, with custom
// VJPs for the properties specified in various ways.
import StdlibUnittest
import DifferentiationUnittest
var E2EDifferentiablePropertyTests = TestSuite("E2EDifferentiableProperty")
struct TangentSpace : AdditiveArithmetic {
let x, y: Tracked<Float>
}
extension TangentSpace : Differentiable {
typealias TangentVector = TangentSpace
}
struct Space {
/// `x` is a computed property with a custom vjp.
var x: Tracked<Float> {
@differentiable(reverse)
get { storedX }
set { storedX = newValue }
}
@derivative(of: x)
func vjpX() -> (value: Tracked<Float>, pullback: (Tracked<Float>) -> TangentSpace) {
return (x, { v in TangentSpace(x: v, y: 0) } )
}
private var storedX: Tracked<Float>
@differentiable(reverse)
var y: Tracked<Float>
init(x: Tracked<Float>, y: Tracked<Float>) {
self.storedX = x
self.y = y
}
}
extension Space : Differentiable {
typealias TangentVector = TangentSpace
mutating func move(along direction: TangentSpace) {
x.move(along: direction.x)
y.move(along: direction.y)
}
}
E2EDifferentiablePropertyTests.testWithLeakChecking("computed property") {
let actualGrad = gradient(at: Space(x: 0, y: 0)) { (point: Space) -> Tracked<Float> in
return 2 * point.x
}
let expectedGrad = TangentSpace(x: 2, y: 0)
expectEqual(expectedGrad, actualGrad)
}
E2EDifferentiablePropertyTests.testWithLeakChecking("stored property") {
let actualGrad = gradient(at: Space(x: 0, y: 0)) { (point: Space) -> Tracked<Float> in
return 3 * point.y
}
let expectedGrad = TangentSpace(x: 0, y: 3)
expectEqual(expectedGrad, actualGrad)
}
struct GenericMemberWrapper<T : Differentiable> : Differentiable {
// Stored property.
@differentiable(reverse)
var x: T
func vjpX() -> (T, (T.TangentVector) -> GenericMemberWrapper.TangentVector) {
return (x, { TangentVector(x: $0) })
}
}
E2EDifferentiablePropertyTests.testWithLeakChecking("generic stored property") {
let actualGrad = gradient(at: GenericMemberWrapper<Tracked<Float>>(x: 1)) { point in
return 2 * point.x
}
let expectedGrad = GenericMemberWrapper<Tracked<Float>>.TangentVector(x: 2)
expectEqual(expectedGrad, actualGrad)
}
struct ProductSpaceSelfTangent : AdditiveArithmetic {
let x, y: Tracked<Float>
}
extension ProductSpaceSelfTangent : Differentiable {
typealias TangentVector = ProductSpaceSelfTangent
}
E2EDifferentiablePropertyTests.testWithLeakChecking("fieldwise product space, self tangent") {
let actualGrad = gradient(at: ProductSpaceSelfTangent(x: 0, y: 0)) { (point: ProductSpaceSelfTangent) -> Tracked<Float> in
return 5 * point.y
}
let expectedGrad = ProductSpaceSelfTangent(x: 0, y: 5)
expectEqual(expectedGrad, actualGrad)
}
struct ProductSpaceOtherTangentTangentSpace : AdditiveArithmetic {
let x, y: Tracked<Float>
}
extension ProductSpaceOtherTangentTangentSpace : Differentiable {
typealias TangentVector = ProductSpaceOtherTangentTangentSpace
}
struct ProductSpaceOtherTangent {
var x, y: Tracked<Float>
}
extension ProductSpaceOtherTangent : Differentiable {
typealias TangentVector = ProductSpaceOtherTangentTangentSpace
mutating func move(along direction: ProductSpaceOtherTangentTangentSpace) {
x.move(along: direction.x)
y.move(along: direction.y)
}
}
E2EDifferentiablePropertyTests.testWithLeakChecking("fieldwise product space, other tangent") {
let actualGrad = gradient(
at: ProductSpaceOtherTangent(x: 0, y: 0)
) { (point: ProductSpaceOtherTangent) -> Tracked<Float> in
return 7 * point.y
}
let expectedGrad = ProductSpaceOtherTangentTangentSpace(x: 0, y: 7)
expectEqual(expectedGrad, actualGrad)
}
E2EDifferentiablePropertyTests.testWithLeakChecking("computed property") {
struct TF_544 : Differentiable {
var value: Tracked<Float>
@differentiable(reverse)
var computed: Tracked<Float> {
get { value }
set { value = newValue }
}
}
let actualGrad = gradient(at: TF_544(value: 2.4)) { x in
return x.computed * x.computed
}
let expectedGrad = TF_544.TangentVector(value: 4.8)
expectEqual(expectedGrad, actualGrad)
}
runAllTests()
| 28.751678 | 124 | 0.732726 |
7259cc51ea133d21a0b619feaa0fa35573f84473 | 2,286 | //
// Authentication.swift
// TweetSearchApp
//
// Created by Mitsuaki Ihara on 2020/12/02.
//
import Foundation
struct Authentication {
func getBearerToken(consumerKey: String, consumerSecret: String,
success: @escaping (String) -> Void,
failure: @escaping (String) -> Void) {
var compnents = URLComponents(string: "https://api.twitter.com/oauth2/token")
compnents?.queryItems = [URLQueryItem(name: "grant_type", value: "client_credentials")]
var request = URLRequest(url: (compnents?.url)!)
request.httpMethod = "POST"
guard let credentialData = "\(consumerKey):\(consumerSecret)".data(using: String.Encoding.utf8) else { return }
let credential = credentialData.base64EncodedString(options: [])
let basicData = "Basic \(credential)"
request.setValue(basicData, forHTTPHeaderField: "Authorization")
let task: URLSessionTask = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
if let error = error {
failure(error.localizedDescription)
return
}
if let response = response as? HTTPURLResponse {
if response.statusCode != 200 {
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
let errors: Errors = try jsonDecoder.decode(Errors.self, from: data!)
failure(errors.errors.first!.message)
return
}
}
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
let token: Token = try jsonDecoder.decode(Token.self, from: data!)
success(token.accessToken)
} catch {
failure(error.localizedDescription)
}
})
task.resume()
}
}
| 40.105263 | 130 | 0.516623 |
115f0bcb2dd81685eabe3bd21615d5220f73bf6d | 801 | //
// TYPEPersistenceStrategy.swift
//
import AmberBase
import Foundation
public class Dictionary_C_Locale_IndexSet_D_PersistenceStrategy: PersistenceStrategy
{
public var types: Types
{
return Types.generic("Dictionary", [Types.type("Locale"), Types.type("IndexSet")])
}
public func save(_ object: Any) throws -> Data
{
guard let typedObject = object as? Dictionary<Locale, IndexSet> else
{
throw AmberError.wrongTypes(self.types, AmberBase.types(of: object))
}
let encoder = JSONEncoder()
return try encoder.encode(typedObject)
}
public func load(_ data: Data) throws -> Any
{
let decoder = JSONDecoder()
return try decoder.decode(Dictionary<Locale, IndexSet>.self, from: data)
}
} | 25.83871 | 90 | 0.659176 |
e8036f51e0afeb65e275f7065a3ced4d29131fa9 | 323 | //
// View+AnyView.swift
// SFPortfolioApp
//
// Created by Milen Valchev on 5.08.21.
//
import SwiftUI
extension View {
/// Provides more convenient and readable usage of `AnyView` transformation which can be attached directly in the view chain.
var anyView: AnyView {
AnyView(self)
}
}
| 17.944444 | 129 | 0.659443 |
0157ddeee0d805a57d6111e7de691d03ae173fd9 | 3,581 | //
// RxTest.swift
// Tests
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTest
import struct Foundation.TimeInterval
import struct Foundation.Date
import class Foundation.RunLoop
#if os(Linux)
import Foundation
#endif
#if TRACE_RESOURCES
#elseif RELEASE
#elseif os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
#elseif os(Linux)
#else
let failure = unhandled_case()
#endif
// because otherwise macOS unit tests won't run
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
#if os(Linux)
// TODO: Implement PerformanceTests.swift for Linux
func getMemoryInfo() -> (bytes: Int64, allocations: Int64) {
return (0, 0)
}
#endif
class RxTest
: XCTestCase {
#if TRACE_RESOURCES
fileprivate var startResourceCount: Int32 = 0
#endif
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
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()
}
}
extension RxTest {
struct Defaults {
static let created = 100
static let subscribed = 200
static let disposed = 1000
}
func sleep(_ time: TimeInterval) {
Thread.sleep(forTimeInterval: time)
}
func setUpActions(){
_ = Hooks.defaultErrorHandler // lazy load resource so resource count matches
_ = Hooks.customCaptureSubscriptionCallstack // lazy load resource so resource count matches
#if TRACE_RESOURCES
self.startResourceCount = Resources.total
//registerMallocHooks()
(startNumberOfAllocatedBytes, startNumberOfAllocations) = getMemoryInfo()
#endif
}
func tearDownActions() {
#if TRACE_RESOURCES
// give 5 sec to clean up resources
for _ in 0..<30 {
if self.startResourceCount < Resources.total {
// main schedulers need to finish work
print("Waiting for resource cleanup ...")
#if swift(>=4.2)
let mode = RunLoop.Mode.default
#else
let mode = RunLoopMode.defaultRunLoopMode
#endif
RunLoop.current.run(mode: mode, before: Date(timeIntervalSinceNow: 0.05))
}
else {
break
}
}
XCTAssertEqual(self.startResourceCount, Resources.total)
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
}
}
| 27.128788 | 190 | 0.628875 |
ff500f6a20710507c6f9f20bcf59e8688295a3d3 | 3,709 | //
// ViewController.swift
// NumericSpringingExamples
//
// Created by Geir-Kåre S. Wærp on 01/02/2020.
// Copyright © 2020 GK. All rights reserved.
//
import UIKit
class TableViewController: UIViewController {
enum ExampleViewController: Int, CaseIterable {
case translateRotateSquash
case gridTranslation
case freeformTranslation
case verticalBar
case horizontalBar
case sceneKitRotation
case rotationFollow
case lottieAnimation
case caShapeLayer
var viewController: UIViewController {
switch self {
case .translateRotateSquash:
return TranslateRotateSquashViewController()
case .gridTranslation:
return GridTranslationViewController()
case .freeformTranslation:
return FreeformTranslationViewController()
case .verticalBar:
return VerticalBarViewController()
case .horizontalBar:
return HorizontalBarViewController()
case .sceneKitRotation:
return SceneKitRotationViewController()
case .rotationFollow:
return RotationFollowViewController()
case .lottieAnimation:
return LottieAnimationViewController()
case .caShapeLayer:
return CAShapeLayerViewController()
}
}
var description: String {
switch self {
case .translateRotateSquash:
return "Translate, Rotate, Squash"
case .gridTranslation:
return "Grid Translation"
case .freeformTranslation:
return "Freeform Translation"
case .verticalBar:
return "Vertical Bar"
case .horizontalBar:
return "Horizontal Bar"
case .sceneKitRotation:
return "SceneKit Rotation"
case .rotationFollow:
return "Rotation Follow"
case .lottieAnimation:
return "Lottie Animation"
case .caShapeLayer:
return "CAShapeLayer"
}
}
}
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.configureTableView()
}
private func configureTableView() {
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let selectedIndexPath = self.tableView.indexPathForSelectedRow {
self.tableView.deselectRow(at: selectedIndexPath, animated: true)
}
}
}
extension TableViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ExampleViewController.allCases.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let example = ExampleViewController(rawValue: indexPath.row)!
cell.textLabel!.text = example.description
cell.accessoryType = .disclosureIndicator
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let example = ExampleViewController(rawValue: indexPath.row)!
let exampleVC = example.viewController
self.navigationController?.pushViewController(exampleVC, animated: true)
exampleVC.title = example.description
}
}
| 33.718182 | 100 | 0.620383 |
dd398ef948ffcfff7b02b2976304e2164b8ac485 | 623 | //
// FavoriteViewData.swift
// MyAirbnb
//
// Created by 김광준 on 06/08/2019.
// Copyright © 2019 Alex Lee. All rights reserved.
//
import Foundation
import UIKit
protocol FavoriteDataProtocol {}
struct FavoriteData {
var data: FavoriteDataProtocol
var cellStyle: CellStyle
enum CellStyle {
case one, three, title
}
}
struct OnePhoto: FavoriteDataProtocol {
let firstImage: UIImage
}
struct ThreePhoto: FavoriteDataProtocol {
let firstImage: UIImage
let secondImage: UIImage
let thirdImage: UIImage
}
struct TitleText: FavoriteDataProtocol {
let title: String
}
| 15.974359 | 51 | 0.704655 |
e2c15912595154cad6b95cd35f23972601822cb2 | 575 | //
// MTPerpetuaFilter.swift
// MetalFilters
//
// Created by alexiscn on 2018/6/8.
//
import Foundation
import MetalPetal
class MTPerpetuaFilter: MTFilter {
override class var name: String {
return "Perpetua"
}
override var borderName: String {
return "filterBorderPlainWhite.png"
}
override var fragmentName: String {
return "MTPerpetuaFragment"
}
override var samplers: [String : String] {
return [
"gradient": "perpetua_overlay.png",
"lookup": "perpetua_map.png",
]
}
} | 17.96875 | 47 | 0.617391 |
0a231482cc4d6f050e66aae332da065d98ea575f | 4,764 | /// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 SwiftUI
struct FlightSearchDetails: View {
var flight: FlightInformation
@Binding var showModal: Bool
@State private var rebookAlert = false
@State private var checkInFlight: CheckInInfo?
@State private var showFlightHistory = false
@EnvironmentObject var lastFlightInfo: AppEnvironment
var body: some View {
ZStack {
Image("background-view")
.resizable()
.frame(maxWidth: .infinity, maxHeight: .infinity)
VStack(alignment: .leading) {
HStack {
FlightDetailHeader(flight: flight)
Spacer()
Button("Close") {
self.showModal = false
}
}
if flight.status == .canceled {
Button("Rebook Flight") {
rebookAlert = true
}
.frame(height: 44.0)
.alert(isPresented: $rebookAlert) {
Alert(
title: Text("Contact Your Airline"),
message: Text(
"We cannot rebook this flight. Please contact the airline to reschedule this flight."
)
)
}
}
if flight.isCheckInAvailable {
Button("Check In for Flight") {
self.checkInFlight =
CheckInInfo(
airline: self.flight.airline,
flight: self.flight.number
)
}
.frame(height: 44.0)
.actionSheet(item: $checkInFlight) { flight in
ActionSheet(
title: Text("Check In"),
message: Text("Check in for \(flight.airline)" +
"Flight \(flight.flight)"),
buttons: [
.cancel(Text("Not Now")),
.destructive(Text("Reschedule"), action: {
print("Reschedule flight.")
}),
.default(Text("Check In"), action: {
print(
"Check-in for \(flight.airline) \(flight.flight)."
)
})
]
)
}
}
Button("On-Time History") {
showFlightHistory.toggle()
}
.frame(height: 44.0)
.popover(
isPresented: $showFlightHistory,
arrowEdge: .top) {
FlightTimeHistory(flight: self.flight)
}
FlightInfoPanel(flight: flight)
.padding()
.background(
RoundedRectangle(cornerRadius: 20.0)
.opacity(0.3)
)
Spacer()
}.foregroundColor(.white)
.padding()
}.onAppear {
lastFlightInfo.lastFlightId = flight.id
}
}
}
struct FlightSearchDetails_Previews: PreviewProvider {
static var previews: some View {
FlightSearchDetails(
flight: FlightData.generateTestFlight(date: Date()),
showModal: .constant(true)
).environmentObject(AppEnvironment())
}
}
| 36.646154 | 101 | 0.615659 |
fba26e08eb528001823c1d2e706a3fe06e13e05b | 2,576 | //
// PopLeftToRightInteractiveTransition.swift
// CustomTransitionDemo
//
// Created by 徐冉 on 2019/4/29.
// Copyright © 2019年 QK. All rights reserved.
//
/**
- Pop交互式转场
*/
import UIKit
class PopLeftToRightInteractiveTransition: UIPercentDrivenInteractiveTransition {
weak var transitionContext: UIViewControllerContextTransitioning?
var panGesture: UIScreenEdgePanGestureRecognizer?
var edge: UIRectEdge = UIRectEdge.left
private override init() {
super.init()
}
convenience init(panGesture: UIScreenEdgePanGestureRecognizer?) {
self.init()
self.panGesture = panGesture
self.panGesture?.addTarget(self, action: #selector(self.panGestureDidUpdate(panGes:)))
}
deinit {
self.panGesture?.removeTarget(self, action: #selector(self.panGestureDidUpdate(panGes:)))
}
// MARK: - Overrides
// 转场速度
override var completionSpeed: CGFloat {
get {
return 0.5 * 0.35
}
set {
super.completionSpeed = completionSpeed
}
}
override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
super.startInteractiveTransition(transitionContext)
}
// MARK: - Methods
// 百分比计算
func percentForPanGesture(panGes: UIScreenEdgePanGestureRecognizer) -> CGFloat {
let containerView = self.transitionContext?.containerView
let location = panGes.location(in: containerView)
if let width: CGFloat = containerView?.frame.size.width {
if self.edge == .left {
return location.x / width
}
}
else {
return 0
}
return 0
}
// MARK: - Action
@objc func panGestureDidUpdate(panGes: UIScreenEdgePanGestureRecognizer) {
switch panGes.state {
case .began:
break
case .changed:
// 更新转场进度
let percent = self.percentForPanGesture(panGes: panGes)
self.update(percent)
break
case .ended:
let percent = self.percentForPanGesture(panGes: panGes)
if percent >= 0.35 {
self.finish()
}
else {
self.cancel()
}
break
default:
// 其他情况发生
self.cancel()
break
}
}
}
| 25.009709 | 105 | 0.572981 |
c1c0324d052c750f269a7febb6bfadd50e3f6d37 | 12,154 |
//
// DoorsNLocksSubsystemCap.swift
//
// Generated on 20/09/18
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import RxSwift
import PromiseKit
// MARK: Constants
extension Constants {
public static var doorsNLocksSubsystemNamespace: String = "subdoorsnlocks"
public static var doorsNLocksSubsystemName: String = "DoorsNLocksSubsystem"
}
// MARK: Attributes
fileprivate struct Attributes {
static let doorsNLocksSubsystemLockDevices: String = "subdoorsnlocks:lockDevices"
static let doorsNLocksSubsystemMotorizedDoorDevices: String = "subdoorsnlocks:motorizedDoorDevices"
static let doorsNLocksSubsystemContactSensorDevices: String = "subdoorsnlocks:contactSensorDevices"
static let doorsNLocksSubsystemPetDoorDevices: String = "subdoorsnlocks:petDoorDevices"
static let doorsNLocksSubsystemWarnings: String = "subdoorsnlocks:warnings"
static let doorsNLocksSubsystemUnlockedLocks: String = "subdoorsnlocks:unlockedLocks"
static let doorsNLocksSubsystemOfflineLocks: String = "subdoorsnlocks:offlineLocks"
static let doorsNLocksSubsystemJammedLocks: String = "subdoorsnlocks:jammedLocks"
static let doorsNLocksSubsystemOpenMotorizedDoors: String = "subdoorsnlocks:openMotorizedDoors"
static let doorsNLocksSubsystemOfflineMotorizedDoors: String = "subdoorsnlocks:offlineMotorizedDoors"
static let doorsNLocksSubsystemObstructedMotorizedDoors: String = "subdoorsnlocks:obstructedMotorizedDoors"
static let doorsNLocksSubsystemOpenContactSensors: String = "subdoorsnlocks:openContactSensors"
static let doorsNLocksSubsystemOfflineContactSensors: String = "subdoorsnlocks:offlineContactSensors"
static let doorsNLocksSubsystemUnlockedPetDoors: String = "subdoorsnlocks:unlockedPetDoors"
static let doorsNLocksSubsystemAutoPetDoors: String = "subdoorsnlocks:autoPetDoors"
static let doorsNLocksSubsystemOfflinePetDoors: String = "subdoorsnlocks:offlinePetDoors"
static let doorsNLocksSubsystemAllPeople: String = "subdoorsnlocks:allPeople"
static let doorsNLocksSubsystemAuthorizationByLock: String = "subdoorsnlocks:authorizationByLock"
static let doorsNLocksSubsystemChimeConfig: String = "subdoorsnlocks:chimeConfig"
}
public protocol ArcusDoorsNLocksSubsystemCapability: class, RxArcusService {
/** The addresses of door locks defined at this place */
func getDoorsNLocksSubsystemLockDevices(_ model: SubsystemModel) -> [String]?
/** The addresses of motorized doors defined at this place */
func getDoorsNLocksSubsystemMotorizedDoorDevices(_ model: SubsystemModel) -> [String]?
/** The addresses of contact sensors defined at this place */
func getDoorsNLocksSubsystemContactSensorDevices(_ model: SubsystemModel) -> [String]?
/** The addresses of pet doors defined at this place */
func getDoorsNLocksSubsystemPetDoorDevices(_ model: SubsystemModel) -> [String]?
/** A set of warnings about devices which have potential issues that could cause an alarm to be missed. The key is the address of the device with a warning and the value is an I18N code with the description of the problem. */
func getDoorsNLocksSubsystemWarnings(_ model: SubsystemModel) -> [String: String]?
/** The addresses of door locks that are currently unlocked */
func getDoorsNLocksSubsystemUnlockedLocks(_ model: SubsystemModel) -> [String]?
/** The addresses of door locks that are currently offline */
func getDoorsNLocksSubsystemOfflineLocks(_ model: SubsystemModel) -> [String]?
/** The addresses of door locks that are currently jammed */
func getDoorsNLocksSubsystemJammedLocks(_ model: SubsystemModel) -> [String]?
/** The addresses of motorized doors that are currently open */
func getDoorsNLocksSubsystemOpenMotorizedDoors(_ model: SubsystemModel) -> [String]?
/** The addresses of motorized doors that are currently offline */
func getDoorsNLocksSubsystemOfflineMotorizedDoors(_ model: SubsystemModel) -> [String]?
/** The addresses of motorized doors that are currently obstructed */
func getDoorsNLocksSubsystemObstructedMotorizedDoors(_ model: SubsystemModel) -> [String]?
/** The addressees of currently open contact sensors */
func getDoorsNLocksSubsystemOpenContactSensors(_ model: SubsystemModel) -> [String]?
/** The addresses of currently offline contact sensors */
func getDoorsNLocksSubsystemOfflineContactSensors(_ model: SubsystemModel) -> [String]?
/** The addresses of currently locked pet doors */
func getDoorsNLocksSubsystemUnlockedPetDoors(_ model: SubsystemModel) -> [String]?
/** The addresses of pet doors in auto mode */
func getDoorsNLocksSubsystemAutoPetDoors(_ model: SubsystemModel) -> [String]?
/** The addresses of offline pet doors */
func getDoorsNLocksSubsystemOfflinePetDoors(_ model: SubsystemModel) -> [String]?
/** The set of all people at the place that could be assigned to a lock (those with access and a pin) */
func getDoorsNLocksSubsystemAllPeople(_ model: SubsystemModel) -> [String]?
/** A between a door lock and the people that currently have access to that lock */
func getDoorsNLocksSubsystemAuthorizationByLock(_ model: SubsystemModel) -> [String: [Any]]?
/** The set of all that could have a chiming enabled/disabled. */
func getDoorsNLocksSubsystemChimeConfig(_ model: SubsystemModel) -> [Any]?
/** The set of all that could have a chiming enabled/disabled. */
func setDoorsNLocksSubsystemChimeConfig(_ chimeConfig: [Any], model: SubsystemModel)
/** Authorizes the given people on the lock. Any people that previously existed on the lock not in this set will be deauthorized */
func requestDoorsNLocksSubsystemAuthorizePeople(_ model: SubsystemModel, device: String, operations: [Any])
throws -> Observable<ArcusSessionEvent>/** Synchronizes the access on the device and the service, by clearing all pins and reassociating people that should have access */
func requestDoorsNLocksSubsystemSynchAuthorization(_ model: SubsystemModel, device: String)
throws -> Observable<ArcusSessionEvent>
}
extension ArcusDoorsNLocksSubsystemCapability {
public func getDoorsNLocksSubsystemLockDevices(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemLockDevices] as? [String]
}
public func getDoorsNLocksSubsystemMotorizedDoorDevices(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemMotorizedDoorDevices] as? [String]
}
public func getDoorsNLocksSubsystemContactSensorDevices(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemContactSensorDevices] as? [String]
}
public func getDoorsNLocksSubsystemPetDoorDevices(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemPetDoorDevices] as? [String]
}
public func getDoorsNLocksSubsystemWarnings(_ model: SubsystemModel) -> [String: String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemWarnings] as? [String: String]
}
public func getDoorsNLocksSubsystemUnlockedLocks(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemUnlockedLocks] as? [String]
}
public func getDoorsNLocksSubsystemOfflineLocks(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemOfflineLocks] as? [String]
}
public func getDoorsNLocksSubsystemJammedLocks(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemJammedLocks] as? [String]
}
public func getDoorsNLocksSubsystemOpenMotorizedDoors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemOpenMotorizedDoors] as? [String]
}
public func getDoorsNLocksSubsystemOfflineMotorizedDoors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemOfflineMotorizedDoors] as? [String]
}
public func getDoorsNLocksSubsystemObstructedMotorizedDoors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemObstructedMotorizedDoors] as? [String]
}
public func getDoorsNLocksSubsystemOpenContactSensors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemOpenContactSensors] as? [String]
}
public func getDoorsNLocksSubsystemOfflineContactSensors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemOfflineContactSensors] as? [String]
}
public func getDoorsNLocksSubsystemUnlockedPetDoors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemUnlockedPetDoors] as? [String]
}
public func getDoorsNLocksSubsystemAutoPetDoors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemAutoPetDoors] as? [String]
}
public func getDoorsNLocksSubsystemOfflinePetDoors(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemOfflinePetDoors] as? [String]
}
public func getDoorsNLocksSubsystemAllPeople(_ model: SubsystemModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemAllPeople] as? [String]
}
public func getDoorsNLocksSubsystemAuthorizationByLock(_ model: SubsystemModel) -> [String: [Any]]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemAuthorizationByLock] as? [String: [Any]]
}
public func getDoorsNLocksSubsystemChimeConfig(_ model: SubsystemModel) -> [Any]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.doorsNLocksSubsystemChimeConfig] as? [Any]
}
public func setDoorsNLocksSubsystemChimeConfig(_ chimeConfig: [Any], model: SubsystemModel) {
model.set([Attributes.doorsNLocksSubsystemChimeConfig: chimeConfig as AnyObject])
}
public func requestDoorsNLocksSubsystemAuthorizePeople(_ model: SubsystemModel, device: String, operations: [Any])
throws -> Observable<ArcusSessionEvent> {
let request: DoorsNLocksSubsystemAuthorizePeopleRequest = DoorsNLocksSubsystemAuthorizePeopleRequest()
request.source = model.address
request.setDevice(device)
request.setOperations(operations)
return try sendRequest(request)
}
public func requestDoorsNLocksSubsystemSynchAuthorization(_ model: SubsystemModel, device: String)
throws -> Observable<ArcusSessionEvent> {
let request: DoorsNLocksSubsystemSynchAuthorizationRequest = DoorsNLocksSubsystemSynchAuthorizationRequest()
request.source = model.address
request.setDevice(device)
return try sendRequest(request)
}
}
| 52.16309 | 228 | 0.776452 |
d922cf613396ad3a578b130a79361b3675156428 | 707 | //
// GridConfiguration.swift
// Lecture12
//
// Created by Van Simmons on 11/27/17.
// Copyright © 2017 Harvard University. All rights reserved.
//
// http://benscheirman.com/2017/06/ultimate-guide-to-json-parsing-with-swift-4/
struct GridConfiguration: Codable {
var title: String
var contents: [[Int]]
// var description: String {
// var positionDesc = "[\n"
// (0 ..< contents.count).forEach {
// positionDesc += " [\(contents[$0][0]), \(contents[$0][1])]\($0 == contents.count - 1 ? "," : "")\($0 % 5 == 0 ? "\n" : "")"
// }
// positionDesc += "\n]\n"
// return "\(title):\n\(positionDesc)"
// }
var description: String = ""
}
| 28.28 | 137 | 0.551627 |
61a0b8264f706bc94a0e5d1a41f76ca9878e3890 | 16,797 | //
// PXLoginTextField.swift
// IFA-C
//
// Created by 侯佳男 on 2018/8/2.
// Copyright © 2018年 侯佳男. All rights reserved.
//
import UIKit
// 0-默认样式 1-密码样式 2-验证码样式
enum GATextFieldType: Int {
case normal = 0, passWord = 1, verificationCode = 2
}
class GATextField: UIView {
// 验证码按钮显示默认样式
private var kVerificationCodeTitleDefault: String = "获取验证码"
// 输入框内容
public var textString: String {
return self.textField.text ?? ""
}
// 根据键盘样式初始化UI布局 必须在xib中设置 0 1 2
@IBInspectable var textFieldType_yy: Int = -1 {
didSet {
if (textFieldType_yy == -1) {
print("error: GATextField 设置textFieldType_yy")
}
textField.frame = CGRect(x: icon.frame.origin.x + icon.frame.size.width + textFieldLeftSpace_yy + iconLeftSpace, y: textFeildTop, width: self.frame.size.width - icon.frame.width - textFieldLeftSpace_yy, height: self.frame.size.height - textFeildTop)
lineView.frame = CGRect(x: 0, y: self.frame.size.height - 1.0 / UIScreen.main.scale, width: self.frame.size.width, height: 1.0 / UIScreen.main.scale)
switch GATextFieldType(rawValue: textFieldType_yy) {
case .normal?:
let xW: CGFloat = 30
clearButton.frame = CGRect(x: self.frame.size.width - xW, y: 0, width: xW, height: self.frame.size.height)
break
case .passWord?:
let w: CGFloat = 30
clearButton.frame = CGRect(x: self.frame.size.width - w * 2, y: clearAndEyebuttonTop, width: w, height: self.frame.size.height - clearAndEyebuttonTop)
eyeButton.frame = CGRect(x: self.frame.size.width - w, y: clearAndEyebuttonTop, width: w, height: self.frame.size.height - clearAndEyebuttonTop)
break
case .verificationCode?:
setUpVerificationCodeFrame(title: verificationCodeTitle_yy)
// 验证码键盘样式
textField.keyboardType = .numberPad
break
default:
break
}
}
}
// icon图片名称
@IBInspectable var iconImageName_yy: String = "pxLoginTextfield_code_icon" {
didSet {
guard let img = UIImage(named: iconImageName_yy) else {
return
}
icon.image = img
icon.frame = CGRect(x: iconLeftSpace, y: self.frame.size.height / 2 - img.size.height / 2 + iconTop, width: img.size.width, height: img.size.height)
textField.frame = CGRect(x: icon.frame.origin.x + icon.frame.size.width + textFieldLeftSpace_yy + iconLeftSpace, y: textFeildTop, width: self.frame.size.width - icon.frame.width - textFieldLeftSpace_yy, height: self.frame.size.height - textFeildTop)
}
}
// icon距离控件左侧距离
@IBInspectable var iconLeftSpace: CGFloat = 5 {
didSet {
guard let image = icon.image else {
return
}
icon.frame = CGRect(x: iconLeftSpace, y: self.frame.size.height / 2 - image.size.height / 2 + iconTop, width: icon.image!.size.width, height: image.size.height)
}
}
// 输入框距离顶部距离
@IBInspectable var textFeildTop: CGFloat = 0 {
didSet {
textField.frame = CGRect(x: icon.frame.origin.x + icon.frame.size.width + textFieldLeftSpace_yy + iconLeftSpace, y: textFeildTop, width: self.frame.size.width - icon.frame.width - textFieldLeftSpace_yy, height: self.frame.size.height - textFeildTop)
}
}
// 输入框距离顶部距离
@IBInspectable var iconTop: CGFloat = 0 {
didSet {
guard let image = icon.image else {
return
}
icon.frame = CGRect(x: iconLeftSpace, y: self.frame.size.height / 2 - image.size.height / 2 + iconTop, width: image.size.width, height: image.size.height)
}
}
// 输入框距离顶部距离
@IBInspectable var verificationCodeIconTop: CGFloat = 0 {
didSet {
setUpVerificationCodeFrame(title: verificationCodeTitle_yy)
}
}
// 按钮距离顶部距离
@IBInspectable var clearAndEyebuttonTop: CGFloat = 0 {
didSet {
let w: CGFloat = 30
clearButton.frame = CGRect(x: self.frame.size.width - w * 2, y: clearAndEyebuttonTop, width: w, height: self.frame.size.height - clearAndEyebuttonTop)
eyeButton.frame = CGRect(x: self.frame.size.width - w, y: clearAndEyebuttonTop, width: w, height: self.frame.size.height - clearAndEyebuttonTop)
}
}
// 输入框占位内容
@IBInspectable var placeholderText_yy: String! {
didSet {
textField.placeholder = placeholderText_yy
}
}
// 验证码按钮标题
@IBInspectable var verificationCodeTitle_yy: String = "获取验证码" {
didSet {
if .verificationCode != GATextFieldType(rawValue: textFieldType_yy) {
return
}
verificationCodeButton.setTitle(verificationCodeTitle_yy, for: .normal)
setUpVerificationCodeFrame(title: verificationCodeTitle_yy)
kVerificationCodeTitleDefault = verificationCodeTitle_yy
}
}
// 倒计时结束 验证码按钮显示标题
@IBInspectable var repeatVerificationCodeTitle_yy: String = "重新获取"
// 输入内容必须为数字
@IBInspectable var isMustNumber: Bool = false
// 输入内容个数限制
@IBInspectable var textMaxCount: Int = 100
// 输入框字体大小
@IBInspectable var textFieldFont_yy: Int = 12 {
didSet {
textField.font = UIFont.systemFont(ofSize: CGFloat(textFieldFont_yy))
}
}
//键盘样式
@IBInspectable var keyboardType_yy: Int = 0 {
didSet {
textField.keyboardType = .numberPad
}
}
enum myKeyboardType: Int {
case `default` = 0, asciiCapable = 1, numbersAndPunctuation = 2, URL = 3, numberPad = 4, phonePad = 5, namePhonePad = 6, emailAddress = 7, decimalPad = 8, twitter = 9, webSearch = 10, asciiCapableNumberPad = 11
}
/*
case `default` // Default type for the current input method.
case asciiCapable // Displays a keyboard which can enter ASCII characters
case numbersAndPunctuation // Numbers and assorted punctuation.
case URL // A type optimized for URL entry (shows . / .com prominently).
case numberPad // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.
case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).
case namePhonePad // A type optimized for entering a person's name or phone number.
case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).
@available(iOS 4.1, *)
case decimalPad // A number pad with a decimal point.
@available(iOS 5.0, *)
case twitter // A type optimized for twitter text entry (easy access to @ #)
@available(iOS 7.0, *)
case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).
@available(iOS 10.0, *)
case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.
*/
// 输入框距离控件最左侧距离
@IBInspectable var textFieldLeftSpace_yy: CGFloat = 10 {
didSet {
textField.frame = CGRect(x: icon.frame.origin.x + icon.frame.size.width + textFieldLeftSpace_yy + iconLeftSpace, y: textFeildTop, width: self.frame.size.width - icon.frame.width - textFieldLeftSpace_yy, height: self.frame.size.height - textFeildTop)
}
}
// 验证码按钮圆角
@IBInspectable var verificationCodeCornerRadius_yy: CGFloat = 5 {
didSet {
if .verificationCode != GATextFieldType(rawValue: textFieldType_yy) {
return
}
verificationCodeButton.layer.cornerRadius = verificationCodeCornerRadius_yy
}
}
// 验证码按钮字体大小
@IBInspectable var verificationCodeFont_yy: CGFloat = 12 {
didSet {
if .verificationCode != GATextFieldType(rawValue: textFieldType_yy) {
return
}
verificationCodeButton.titleLabel?.font = UIFont.systemFont(ofSize: verificationCodeFont_yy)
setUpVerificationCodeFrame(title: verificationCodeTitle_yy)
}
}
// 验证码按钮高度
@IBInspectable var verificationCodeHeight_yy: CGFloat = 22
// 占位字体颜色
@IBInspectable var placeholderColor_yy: UIColor! {
didSet {
textField.setValue(placeholderColor_yy, forKeyPath: "_placeholderLabel.textColor")
}
}
// 输入内容字体颜色
@IBInspectable var textFieldColor_yy: UIColor! {
didSet {
textField.textColor = textFieldColor_yy
}
}
@IBInspectable var isShowVerificationCodeBorder_yy: Bool = false
// 验证码按钮
@IBInspectable var verificationCodeColor_yy: UIColor = UIColor.white {
didSet {
if .verificationCode != GATextFieldType(rawValue: textFieldType_yy) {
return
}
verificationCodeButton.setTitleColor(verificationCodeColor_yy, for: .normal)
if isShowVerificationCodeBorder_yy {
verificationCodeButton.layer.borderColor = verificationCodeColor_yy.cgColor
verificationCodeButton.layer.borderWidth = 0.5
verificationCodeButton.layer.masksToBounds = true
}
}
}
// 底线颜色
@IBInspectable var lineColor: UIColor = UIColor.white {
didSet {
lineView.backgroundColor = lineColor
}
}
// 底线
lazy var lineView: UIView = {
let v = UIView(frame: CGRect.zero)
v.backgroundColor = lineColor
v.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
self.addSubview(v)
return v
}()
// 左侧icon
lazy var icon: UIImageView = {
let v = UIImageView(frame: CGRect.zero)
self.addSubview(v)
// v.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
return v
}()
// 输入框
lazy var textField: UITextField = {
let v = UITextField(frame: CGRect.zero)
v.borderStyle = .none
v.delegate = self
v.addTarget(self, action: #selector(textFieldEditingChanged(sender: )), for: .editingChanged)
v.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
self.addSubview(v)
return v
}()
// 清空按钮
lazy var clearButton: UIButton = {
let v = UIButton()
v.setImage(UIImage(named: "pxLoginTextfield_clear_icon"), for: UIControl.State.normal)
v.addTarget(self, action: #selector(clearAction(sender:)), for: .touchUpInside)
v.isHidden = true
v.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
self.addSubview(v)
return v
}()
// 密码按钮
lazy var eyeButton: UIButton = {
let v = UIButton()
v.setImage(UIImage(named: "pxLoginTextfield_secret_open_icon"), for: UIControl.State.normal)
v.setImage(UIImage(named: "pxLoginTextfield_secret_closed_icon"), for: UIControl.State.selected)
v.addTarget(self, action: #selector(eyeAction(sender:)), for: .touchUpInside)
v.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
self.addSubview(v)
return v
}()
// 验证码按钮
lazy var verificationCodeButton: UIButton = {
let v = UIButton(type: UIButton.ButtonType.custom)
v.setTitle(kVerificationCodeTitleDefault, for: .normal)
v.titleLabel?.font = UIFont.systemFont(ofSize: verificationCodeFont_yy)
v.addTarget(self, action: #selector(verificationCodeAction(sender:)), for: .touchUpInside)
v.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
self.addSubview(v)
return v
}()
// 验证码按钮尺寸更改
func setUpVerificationCodeFrame(title: String) {
let cW: CGFloat = 30
let vW: CGFloat = CGFloat(title.count) * verificationCodeFont_yy + 10
clearButton.frame = CGRect(x: self.frame.size.width - cW - vW, y: clearAndEyebuttonTop, width: cW, height: self.frame.size.height - clearAndEyebuttonTop)
verificationCodeButton.frame = CGRect(x: self.frame.size.width - vW, y: self.frame.size.height / 2 - verificationCodeHeight_yy / 2 + verificationCodeIconTop, width: vW, height: verificationCodeHeight_yy)
}
// 输入框输入改变方法
@objc func textFieldEditingChanged(sender: UITextField) {
clearButton.isHidden = sender.text?.isEmpty ?? true
// 限制输入字数判断
guard let _: UITextRange = sender.markedTextRange else{
if (sender.text! as NSString).length > textMaxCount {
sender.text = (sender.text! as NSString).substring(to: textMaxCount)
}
return
}
}
// 清空按钮方法
@objc func clearAction(sender: UIButton) {
textField.text = ""
sender.isHidden = true
}
// 密码眼睛方法
@objc func eyeAction(sender: UIButton) {
sender.isSelected = !sender.isSelected
textField.isSecureTextEntry = sender.isSelected
}
// 验证码按钮方法
@objc func verificationCodeAction(sender: UIButton) {
// 防止正在倒计时进行中 连续添加timer
if (sender.titleLabel?.text != kVerificationCodeTitleDefault) {
return
}
addTimer()
}
// 定时器timer
private var timer: DispatchSourceTimer?
// 倒计时时间
@IBInspectable var sourceTimerCount_yy: Int = 60 {
didSet {
timerCount_yy = sourceTimerCount_yy
}
}
// 倒计时计数使用
var timerCount_yy: Int = -1
// 添加倒计时方法
func addTimer() {
// 子线程创建timer
timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
// let timer = DispatchSource.makeTimerSource()
/*
dealine: 开始执行时间
repeating: 重复时间间隔
leeway: 时间精度
*/
timer?.schedule(deadline: .now() + .seconds(0), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
// timer 添加事件
timer?.setEventHandler {
[weak self] in
if let weakSelf = self {
weakSelf.timerCount_yy -= 1
// 倒计时结束
if (weakSelf.timerCount_yy == 0) {
// 取消倒计时
weakSelf.cancleTimer()
DispatchQueue.main.async {
// 主线程更改验证码按钮
weakSelf.verificationCodeButton.setTitle(weakSelf.repeatVerificationCodeTitle_yy, for: .normal)
weakSelf.setUpVerificationCodeFrame(title: weakSelf.repeatVerificationCodeTitle_yy)
weakSelf.kVerificationCodeTitleDefault = weakSelf.repeatVerificationCodeTitle_yy
// 恢复倒计时时间
weakSelf.timerCount_yy = weakSelf.sourceTimerCount_yy
}
} else {
DispatchQueue.main.async {
// 倒计时更改UI
let title: String = "\(weakSelf.timerCount_yy)秒"
weakSelf.verificationCodeButton.setTitle(title, for: .normal)
weakSelf.setUpVerificationCodeFrame(title: title)
}
}
}
}
timer?.resume()
}
// timer暂停
func stopTimer() {
timer?.suspend()
}
// timer结束
func cancleTimer() {
guard let t = timer else {
return
}
t.cancel()
timer = nil
}
override func awakeFromNib() {
super.awakeFromNib()
}
deinit {
cancleTimer()
}
}
extension GATextField: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
clearButton.isHidden = true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if !textField.text!.isEmpty {
clearButton.isHidden = false
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// 限制输入数字
let cs = NSCharacterSet(charactersIn: "1234567890").inverted
let filtered = string.components(separatedBy: cs).joined(separator: "")
if string == filtered {
return true
} else {
if (isMustNumber) {
return false
}
}
return true
}
}
| 36.674672 | 261 | 0.608918 |
f7f76f8414ac2d95882297638c36ee1bd358c530 | 989 | import Foundation
public struct AccessingWeakObjectThroughWithExtendedLifetimeExample {
class Pilot {
var name: String
var f1Car: F1Car?
init(name: String) {
self.name = name
}
deinit {
print("\(#function): \(name)")
}
}
class F1Car {
var model: String
weak var pilot: Pilot?
init(model: String) {
self.model = model
}
deinit {
print("\(#function): \(model)")
}
func printSummary() {
print("Renault: Model - \(model), Pilot: \(pilot!.name)")
}
}
public static func run() {
var pilot = Pilot(name: "Alonso")
var f1Car = F1Car(model: "R2022")
pilot.f1Car = f1Car
f1Car.pilot = pilot
withExtendedLifetime(pilot) {
f1Car.printSummary()
}
// Here pilot can be released!
// f1Car.printSummary()
}
}
| 23 | 69 | 0.493428 |
217b78da889880690d12f643b9133c27808c8a8d | 1,617 | import UIKit
class TableViewCell<View: UIView, ViewModel>: UITableViewCell, Reusable where View: ViewModelOwner, View.ViewModel == ViewModel {
var customView: View
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
customView = View()
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(customView)
customView.setContentHuggingPriority(.required, for: .vertical)
customView.setContentCompressionResistancePriority(.required, for: .vertical)
customView.translatesAutoresizingMaskIntoConstraints = false
customView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
customView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
customView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
customView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
selectionStyle = .none
backgroundColor = .clear
contentView.backgroundColor = .clear
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
final var viewModel: ViewModel? {
get {
return customView.viewModel
}
set(newViewModel) {
customView.viewModel = newViewModel
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
customView.isSelected = selected
}
}
| 33 | 129 | 0.697588 |
e48554ce8b11e359b6388b790cdf3f54716a0ae1 | 2,451 | //
// UserInteractionSelectionTableViewCell.swift
// Core-Sample
//
// Created by Elias Abel on 4/25/18.
// Copyright (c) 2018 Meniny Lab. All rights reserved.
//
import UIKit
import Pow
class UserInteractionSelectionTableViewCell: SelectionTableViewCell {
var focus: Focus = .pow
private var interactionAction: PowAttributes.UserInteraction.Default {
get {
switch focus {
case .pow:
return attributesWrapper.attributes.powInteraction.defaultAction
case .screen:
return attributesWrapper.attributes.screenInteraction.defaultAction
}
}
set {
switch focus {
case .pow:
attributesWrapper.attributes.powInteraction.defaultAction = newValue
case .screen:
attributesWrapper.attributes.screenInteraction.defaultAction = newValue
}
}
}
func configure(attributesWrapper: PowAttributeWrapper, focus: Focus) {
self.focus = focus
configure(attributesWrapper: attributesWrapper)
}
override func configure(attributesWrapper: PowAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "\(focus.rawValue.capitalized) User Interaction"
descriptionValue = "Describes what happens when the user taps the \(focus.rawValue). The touch can be absorbed, delay the exit, be forwarded to the window below, or dismiss the pow."
insertSegments(by: ["Absorb", "Delay", "Forward", "Dismiss"])
selectSegment()
}
private func selectSegment() {
switch interactionAction {
case .absorbTouches:
segmentedControl.selectedSegmentIndex = 0
case .delayExit(by: _):
segmentedControl.selectedSegmentIndex = 1
case .forward:
segmentedControl.selectedSegmentIndex = 2
case .dismissEntry:
segmentedControl.selectedSegmentIndex = 3
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
interactionAction = .absorbTouches
case 1:
interactionAction = .delayExit(by: 4)
case 2:
interactionAction = .forward
case 3:
interactionAction = .dismissEntry
default:
break
}
}
}
| 31.831169 | 190 | 0.623419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.