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
|
---|---|---|---|---|---|
edaf1a8b885d515d8c2fee5f99ea85e5caf33994 | 2,256 | /*
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose">
* Copyright (c) 2020 Aspose.Slides for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
import Foundation
/** Represents image DTO. */
public struct Image: Codable {
/** Gets or sets the link to this resource. */
public var selfUri: ResourceUri?
/** List of alternate links. */
public var alternateLinks: [ResourceUri]?
/** Get or sets the width of an image. */
public var width: Int?
/** Get or sets the height of an image. */
public var height: Int?
/** Get or sets the content type of an image. */
public var contentType: String?
public init(selfUri: ResourceUri?, alternateLinks: [ResourceUri]?, width: Int?, height: Int?, contentType: String?) {
self.selfUri = selfUri
self.alternateLinks = alternateLinks
self.width = width
self.height = height
self.contentType = contentType
}
}
| 38.896552 | 121 | 0.626773 |
f8dae2473d217753bdb2ba03c0a45253612b91fb | 248 | //
// TopStateEventTypeProtocol.swift
// HSM
//
// Created by Serge Bouts on 2/01/20.
// Copyright © 2020 iRiZen.com. All rights reserved.
//
public protocol TopStateEventTypeProtocol: AnyObject {
associatedtype EventType: EventProtocol
}
| 20.666667 | 54 | 0.733871 |
1e38314fdec880a1b0ec32a1649f23c62fee66b9 | 939 | //
// MediumScrollFullScreenTests.swift
// MediumScrollFullScreenTests
//
// Created by pixyzehn on 2/16/15.
// Copyright (c) 2015 pixyzehn. All rights reserved.
//
import UIKit
import XCTest
class MediumScrollFullScreenTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.378378 | 111 | 0.631523 |
dec29d698a0945fc69312108ad101633daf7f561 | 5,395 | import Foundation
import Future
class RuuviTagTankCoordinator: RuuviTagTank {
var sqlite: RuuviTagPersistence!
var realm: RuuviTagPersistence!
var idPersistence: IDPersistence!
var settings: Settings!
var backgroundPersistence: BackgroundPersistence!
var connectionPersistence: ConnectionPersistence!
func create(_ ruuviTag: RuuviTagSensor) -> Future<Bool, RUError> {
let promise = Promise<Bool, RUError>()
if let macId = ruuviTag.macId,
let luid = ruuviTag.luid {
idPersistence.set(mac: macId, for: luid)
}
if ruuviTag.macId != nil,
ruuviTag.macId?.value.isEmpty == false {
sqlite.create(ruuviTag).on(success: { [weak self] (result) in
self?.settings.tagsSorting.append(ruuviTag.id)
promise.succeed(value: result)
}, failure: { (error) in
promise.fail(error: error)
})
} else {
realm.create(ruuviTag).on(success: { [weak self] (result) in
self?.settings.tagsSorting.append(ruuviTag.id)
promise.succeed(value: result)
}, failure: { (error) in
promise.fail(error: error)
})
}
return promise.future
}
func update(_ ruuviTag: RuuviTagSensor) -> Future<Bool, RUError> {
if ruuviTag.macId != nil {
return sqlite.update(ruuviTag)
} else {
return realm.update(ruuviTag)
}
}
func delete(_ ruuviTag: RuuviTagSensor) -> Future<Bool, RUError> {
let promise = Promise<Bool, RUError>()
if ruuviTag.macId != nil {
sqlite.delete(ruuviTag).on(success: { [weak self] success in
if let luid = ruuviTag.luid {
self?.backgroundPersistence.deleteCustomBackground(for: luid)
self?.connectionPersistence.setKeepConnection(false, for: luid)
} else if let macId = ruuviTag.macId {
// FIXME:
// self?.backgroundPersistence.deleteCustomBackground(for: macId)
// self?.connectionPersistence.setKeepConnection(false, for: macId)
} else {
assertionFailure()
}
self?.settings.tagsSorting.removeAll(where: {$0 == ruuviTag.id})
promise.succeed(value: success)
}, failure: { error in
promise.fail(error: error)
})
} else {
realm.delete(ruuviTag).on(success: { [weak self] success in
if let luid = ruuviTag.luid {
self?.backgroundPersistence.deleteCustomBackground(for: luid)
self?.connectionPersistence.setKeepConnection(false, for: luid)
} else if let macId = ruuviTag.macId {
// FIXME:
// self?.backgroundPersistence.deleteCustomBackground(for: macId)
// self?.connectionPersistence.setKeepConnection(false, for: macId)
} else {
assertionFailure()
}
self?.settings.tagsSorting.removeAll(where: {$0 == ruuviTag.id})
promise.succeed(value: success)
}, failure: { error in
promise.fail(error: error)
})
}
return promise.future
}
func create(_ record: RuuviTagSensorRecord) -> Future<Bool, RUError> {
if record.macId != nil {
return sqlite.create(record)
} else if let macId = idPersistence.mac(for: record.ruuviTagId.luid) {
return sqlite.create(record.with(macId: macId))
} else {
return realm.create(record)
}
}
func create(_ records: [RuuviTagSensorRecord]) -> Future<Bool, RUError> {
let promise = Promise<Bool, RUError>()
let sqliteRecords = records.filter({ $0.macId != nil })
let realmRecords = records.filter({ $0.macId == nil })
let sqliteOperation = sqlite.create(sqliteRecords)
let realmOpearion = realm.create(realmRecords)
Future.zip(sqliteOperation, realmOpearion).on(success: { _ in
promise.succeed(value: true)
}, failure: { error in
promise.fail(error: error)
})
return promise.future
}
func deleteAllRecords(_ ruuviTagId: String) -> Future<Bool, RUError> {
let promise = Promise<Bool, RUError>()
let sqliteOperation = sqlite.deleteAllRecords(ruuviTagId)
let realmOpearion = realm.deleteAllRecords(ruuviTagId)
Future.zip(sqliteOperation, realmOpearion).on(success: { _ in
promise.succeed(value: true)
}, failure: { error in
promise.fail(error: error)
})
return promise.future
}
func deleteAllRecords(_ ruuviTagId: String, before date: Date) -> Future<Bool, RUError> {
let promise = Promise<Bool, RUError>()
let sqliteOperation = sqlite.deleteAllRecords(ruuviTagId, before: date)
let realmOpearion = realm.deleteAllRecords(ruuviTagId, before: date)
Future.zip(sqliteOperation, realmOpearion).on(success: { _ in
promise.succeed(value: true)
}, failure: { error in
promise.fail(error: error)
})
return promise.future
}
}
| 39.962963 | 94 | 0.57924 |
0a3e126b357b1532def845c6e89472801ad998ab | 2,726 | //
// LoginViewController.swift
// jphacks
//
// Created by sekiya on 2019/10/19.
// Copyright © 2019 sekiya. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var emailInput: UITextField!
@IBOutlet weak var passwordInput: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
emailInput.delegate = self
passwordInput.delegate = self
// プレースホルダの文字色を変更
emailInput.attributedPlaceholder = NSAttributedString(string: emailInput.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
passwordInput.attributedPlaceholder = NSAttributedString(string: passwordInput.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
// パスワードを伏せ字にする
passwordInput.isSecureTextEntry = true
}
/*
* ログイン処理
*/
@IBAction func signInButton(_ sender: Any) {
// 遷移
let storyboard: UIStoryboard = self.storyboard!
let second = storyboard.instantiateViewController(withIdentifier: "barRoot")
second.modalPresentationStyle = .fullScreen
self.present(second, animated: false, completion: nil)
}
/*
* SignUpViewControllerに遷移
*/
@IBAction func moveRegisterButton(_ sender: Any) {
let storyboard: UIStoryboard = self.storyboard!
let second = storyboard.instantiateViewController(withIdentifier: "signupScene")
second.modalPresentationStyle = .fullScreen
self.present(second, animated: false, completion: nil)
}
/*
* テキスト入力時に他の場所を押したらキーボードを閉じる
*/
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension LoginViewController: UITextFieldDelegate {
// Doneボタン押下でキーボードを閉じる
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField.tag {
case 0:
// タグが0ならpasswordInputにフォーカスを当てる
passwordInput.becomeFirstResponder()
break
case 1:
// タグが1ならキーボードを閉じる
self.view.endEditing(true)
break
default:
break
}
return true
}
}
| 30.629213 | 178 | 0.653705 |
76c5896847387548d50fd4e8fa171f850f06c570 | 42,462 | /****************************************************************************
* Copyright 2019-2021, Optimizely, Inc. and contributors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
***************************************************************************/
import Foundation
public typealias OptimizelyAttributes = [String: Any?]
public typealias OptimizelyEventTags = [String: Any]
open class OptimizelyClient: NSObject {
// MARK: - Properties
var sdkKey: String
private var atomicConfig = AtomicProperty<ProjectConfig>()
var config: ProjectConfig? {
get {
return atomicConfig.property
}
set {
atomicConfig.property = newValue
}
}
var defaultDecideOptions: [OptimizelyDecideOption]
public var version: String {
return Utils.sdkVersion
}
let eventLock = DispatchQueue(label: "com.optimizely.client")
// MARK: - Customizable Services
lazy var logger = OPTLoggerFactory.getLogger()
var eventDispatcher: OPTEventDispatcher? {
return HandlerRegistryService.shared.injectEventDispatcher(sdkKey: self.sdkKey)
}
// MARK: - Default Services
var decisionService: OPTDecisionService {
return HandlerRegistryService.shared.injectDecisionService(sdkKey: self.sdkKey)!
}
public var datafileHandler: OPTDatafileHandler? {
return HandlerRegistryService.shared.injectDatafileHandler(sdkKey: self.sdkKey)
}
lazy var currentDatafileHandler = datafileHandler
public var notificationCenter: OPTNotificationCenter? {
return HandlerRegistryService.shared.injectNotificationCenter(sdkKey: self.sdkKey)
}
// MARK: - Public interfaces
/// OptimizelyClient init
///
/// - Parameters:
/// - sdkKey: sdk key
/// - logger: custom Logger
/// - eventDispatcher: custom EventDispatcher (optional)
/// - datafileHandler: custom datafile handler (optional)
/// - userProfileService: custom UserProfileService (optional)
/// - defaultLogLevel: default log level (optional. default = .info)
/// - defaultDecisionOptions: default decision optiopns (optional)
public init(sdkKey: String,
logger: OPTLogger? = nil,
eventDispatcher: OPTEventDispatcher? = nil,
datafileHandler: OPTDatafileHandler? = nil,
userProfileService: OPTUserProfileService? = nil,
defaultLogLevel: OptimizelyLogLevel? = nil,
defaultDecideOptions: [OptimizelyDecideOption]? = nil) {
self.sdkKey = sdkKey
self.defaultDecideOptions = defaultDecideOptions ?? []
super.init()
let userProfileService = userProfileService ?? DefaultUserProfileService()
let logger = logger ?? DefaultLogger()
type(of: logger).logLevel = defaultLogLevel ?? .info
self.registerServices(sdkKey: sdkKey,
logger: logger,
eventDispatcher: eventDispatcher ?? DefaultEventDispatcher.sharedInstance,
datafileHandler: datafileHandler ?? DefaultDatafileHandler(),
decisionService: DefaultDecisionService(userProfileService: userProfileService),
notificationCenter: DefaultNotificationCenter())
logger.d("SDK Version: \(version)")
}
/// Start Optimizely SDK (Asynchronous)
///
/// If an updated datafile is available in the server, it's downloaded and the SDK is configured with
/// the updated datafile.
///
/// - Parameters:
/// - resourceTimeout: timeout for datafile download (optional)
/// - completion: callback when initialization is completed
public func start(resourceTimeout: Double? = nil, completion: ((OptimizelyResult<Data>) -> Void)? = nil) {
datafileHandler?.downloadDatafile(sdkKey: sdkKey,
returnCacheIfNoChange: true,
resourceTimeoutInterval: resourceTimeout) { [weak self] result in
guard let self = self else {
completion?(.failure(.sdkNotReady))
return
}
switch result {
case .success(let datafile):
guard let datafile = datafile else {
completion?(.failure(.datafileLoadingFailed(self.sdkKey)))
return
}
do {
try self.configSDK(datafile: datafile)
completion?(.success(datafile))
} catch {
completion?(.failure(error as! OptimizelyError))
}
case .failure(let error):
completion?(.failure(error))
}
}
}
/// Start Optimizely SDK (Synchronous)
///
/// - Parameters:
/// - datafile: This datafile will be used when cached copy is not available (fresh start).
/// A cached copy from previous download is used if it's available.
/// The datafile will be updated from the server in the background thread.
public func start(datafile: String) throws {
let datafileData = Data(datafile.utf8)
try start(datafile: datafileData)
}
/// Start Optimizely SDK (Synchronous)
///
/// - Parameters:
/// - datafile: This datafile will be used when cached copy is not available (fresh start)
/// A cached copy from previous download is used if it's available.
/// The datafile will be updated from the server in the background thread.
/// - doUpdateConfigOnNewDatafile: When a new datafile is fetched from the server in the background thread,
/// the SDK will be updated with the new datafile immediately if this value is set to true.
/// When it's set to false (default), the new datafile is cached and will be used when the SDK is started again.
/// - doFetchDatafileBackground: This is for debugging purposes when
/// you don't want to download the datafile. In practice, you should allow the
/// background thread to update the cache copy (optional)
public func start(datafile: Data,
doUpdateConfigOnNewDatafile: Bool = false,
doFetchDatafileBackground: Bool = true) throws {
let cachedDatafile = self.sdkKey.isEmpty ? nil :datafileHandler?.loadSavedDatafile(sdkKey: self.sdkKey)
let selectedDatafile = cachedDatafile ?? datafile
try configSDK(datafile: selectedDatafile)
// continue to fetch updated datafile from the server in background and cache it for next sessions
if !doFetchDatafileBackground { return }
guard let datafileHandler = datafileHandler else { return }
datafileHandler.downloadDatafile(sdkKey: sdkKey, returnCacheIfNoChange: false) { [weak self] result in
guard let self = self else { return }
// override to update always if periodic datafile polling is enabled
// this is necessary for the case that the first cache download gets the updated datafile
guard doUpdateConfigOnNewDatafile || datafileHandler.hasPeriodicInterval(sdkKey: self.sdkKey) else { return }
if case .success(let data) = result, let datafile = data {
// new datafile came in
self.updateConfigFromBackgroundFetch(data: datafile)
}
}
}
func configSDK(datafile: Data) throws {
do {
self.config = try ProjectConfig(datafile: datafile)
datafileHandler?.startUpdates(sdkKey: self.sdkKey) { data in
// new datafile came in
self.updateConfigFromBackgroundFetch(data: data)
}
} catch let error as OptimizelyError {
// .datafileInvalid
// .datafaileVersionInvalid
// .datafaileLoadingFailed
self.logger.e(error)
throw error
} catch {
self.logger.e(error.localizedDescription)
throw error
}
}
func updateConfigFromBackgroundFetch(data: Data) {
guard let config = try? ProjectConfig(datafile: data) else {
return
}
// if a download fails for any reason, the cached datafile is returned
// check and see if the revisions are the same and don't update if they are
guard config.project.revision != self.config?.project.revision else {
return
}
if let users = self.config?.whitelistUsers {
config.whitelistUsers = users
}
self.config = config
// call reinit on the services we know we are reinitializing.
for component in HandlerRegistryService.shared.lookupComponents(sdkKey: self.sdkKey) ?? [] {
HandlerRegistryService.shared.reInitializeComponent(service: component, sdkKey: self.sdkKey)
}
self.sendDatafileChangeNotification(data: data)
}
/**
* Use the activate method to start an experiment.
*
* The activate call will conditionally activate an experiment for a user based on the provided experiment key and a randomized hash of the provided user ID.
* If the user satisfies audience conditions for the experiment and the experiment is valid and running, the function returns the variation the user is bucketed into.
* Otherwise, activate returns nil. Make sure that your code adequately deals with the case when the experiment is not activated (e.g. execute the default variation).
*/
/// Try to activate an experiment based on the experiment key and user ID with user attributes.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - attributes: A map of attribute names to current user attribute values.
/// - Returns: The variation key the user was bucketed into
/// - Throws: `OptimizelyError` if error is detected
public func activate(experimentKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> String {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
guard let experiment = config.getExperiment(key: experimentKey) else {
throw OptimizelyError.experimentKeyInvalid(experimentKey)
}
let variation = try getVariation(experimentKey: experimentKey, userId: userId, attributes: attributes)
sendImpressionEvent(experiment: experiment,
variation: variation,
userId: userId,
attributes: attributes,
flagKey: "",
ruleType: Constants.DecisionSource.experiment.rawValue,
enabled: true)
return variation.key
}
/// Get variation for experiment and user ID with user attributes.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - attributes: A map of attribute names to current user attribute values.
/// - Returns: The variation key the user was bucketed into
/// - Throws: `OptimizelyError` if error is detected
public func getVariationKey(experimentKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> String {
let variation = try getVariation(experimentKey: experimentKey, userId: userId, attributes: attributes)
return variation.key
}
func getVariation(experimentKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Variation {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
guard let experiment = config.getExperiment(key: experimentKey) else {
throw OptimizelyError.experimentKeyInvalid(experimentKey)
}
let variation = decisionService.getVariation(config: config,
experiment: experiment,
userId: userId,
attributes: attributes ?? OptimizelyAttributes(),
options: nil).result
let decisionType: Constants.DecisionType = config.isFeatureExperiment(id: experiment.id) ? .featureTest : .abTest
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: decisionType,
experiment: experiment,
variation: variation))
if let variation = variation {
return variation
} else {
throw OptimizelyError.variationUnknown(userId, experimentKey)
}
}
/**
* Use the setForcedVariation method to force an experimentKey-userId
* pair into a specific variation for QA purposes.
* The forced bucketing feature allows customers to force users into
* variations in real time for QA purposes without requiring datafile
* downloads from the network. Methods activate and track are called
* as usual after the variation is set, but the user will be bucketed
* into the forced variation overriding any variation which would be
* computed via the network datafile.
*/
/// Get forced variation for experiment and user ID.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - Returns: forced variation key if it exists, otherwise return nil.
public func getForcedVariation(experimentKey: String, userId: String) -> String? {
guard let config = self.config else { return nil }
let variaion = config.getForcedVariation(experimentKey: experimentKey, userId: userId).result
return variaion?.key
}
/// Set forced variation for experiment and user ID to variationKey.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - variationKey: The variation the user should be forced into.
/// This value can be nil, in which case, the forced variation is cleared.
/// - Returns: true if forced variation set successfully
public func setForcedVariation(experimentKey: String,
userId: String,
variationKey: String?) -> Bool {
guard let config = self.config else { return false }
return config.setForcedVariation(experimentKey: experimentKey,
userId: userId,
variationKey: variationKey)
}
/// Determine whether a feature is enabled.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: true if feature is enabled, false otherwise.
public func isFeatureEnabled(featureKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) -> Bool {
guard let config = self.config else {
logger.e(.sdkNotReady)
return false
}
guard let featureFlag = config.getFeatureFlag(key: featureKey) else {
logger.e(.featureKeyInvalid(featureKey))
return false
}
let pair = decisionService.getVariationForFeature(config: config,
featureFlag: featureFlag,
userId: userId,
attributes: attributes ?? OptimizelyAttributes(),
options: nil).result
let source = pair?.source ?? Constants.DecisionSource.rollout.rawValue
let featureEnabled = pair?.variation.featureEnabled ?? false
if featureEnabled {
logger.i(.featureEnabledForUser(featureKey, userId))
} else {
logger.i(.featureNotEnabledForUser(featureKey, userId))
}
if shouldSendDecisionEvent(source: source, decision: pair) {
sendImpressionEvent(experiment: pair?.experiment,
variation: pair?.variation,
userId: userId,
attributes: attributes,
flagKey: featureKey,
ruleType: source,
enabled: featureEnabled)
}
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: .feature,
experiment: pair?.experiment,
variation: pair?.variation,
source: source,
feature: featureFlag,
featureEnabled: featureEnabled))
return featureEnabled
}
/// Gets boolean feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type boolean.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableBoolean(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Bool {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets double feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type double.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableDouble(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Double {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets integer feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type integer.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableInteger(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Int {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets string feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type string.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableString(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> String {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets json feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type OptimizelyJSON.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableJSON(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> OptimizelyJSON {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
func getFeatureVariable<T>(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> T {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
guard let featureFlag = config.getFeatureFlag(key: featureKey) else {
throw OptimizelyError.featureKeyInvalid(featureKey)
}
guard let variable = featureFlag.getVariable(key: variableKey) else {
throw OptimizelyError.variableKeyInvalid(variableKey, featureKey)
}
var featureValue = variable.defaultValue ?? ""
let decision = decisionService.getVariationForFeature(config: config,
featureFlag: featureFlag,
userId: userId,
attributes: attributes ?? OptimizelyAttributes(),
options: nil).result
if let decision = decision {
if let featureVariable = decision.variation.variables?.filter({$0.id == variable.id}).first {
if let featureEnabled = decision.variation.featureEnabled, featureEnabled {
featureValue = featureVariable.value
logger.i(.userReceivedVariableValue(featureValue, variableKey, featureKey))
} else {
logger.i(.featureNotEnabledReturnDefaultVariableValue(userId, featureKey, variableKey))
}
}
} else {
logger.i(.userReceivedDefaultVariableValue(userId, featureKey, variableKey))
}
var type: Constants.VariableValueType?
var valueParsed: T?
var notificationValue: Any? = featureValue
switch T.self {
case is String.Type:
type = .string
valueParsed = featureValue as? T
notificationValue = valueParsed
case is Int.Type:
type = .integer
valueParsed = Int(featureValue) as? T
notificationValue = valueParsed
case is Double.Type:
type = .double
valueParsed = Double(featureValue) as? T
notificationValue = valueParsed
case is Bool.Type:
type = .boolean
valueParsed = Bool(featureValue) as? T
notificationValue = valueParsed
case is OptimizelyJSON.Type:
type = .json
let jsonValue = OptimizelyJSON(payload: featureValue)
valueParsed = jsonValue as? T
notificationValue = jsonValue?.toMap()
default:
break
}
guard let value = valueParsed,
type?.rawValue == variable.type else {
throw OptimizelyError.variableValueInvalid(variableKey)
}
// Decision Notification
let experiment = decision?.experiment
let variation = decision?.variation
let featureEnabled = variation?.featureEnabled ?? false
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: .featureVariable,
experiment: experiment,
variation: variation,
source: decision?.source,
feature: featureFlag,
featureEnabled: featureEnabled,
variableKey: variableKey,
variableType: variable.type,
variableValue: notificationValue))
return value
}
/// Gets all the variables for a given feature.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: all the variables for a given feature.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getAllFeatureVariables(featureKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> OptimizelyJSON {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
var variableMap = [String: Any]()
var enabled = false
guard let featureFlag = config.getFeatureFlag(key: featureKey) else {
throw OptimizelyError.featureKeyInvalid(featureKey)
}
let decision = decisionService.getVariationForFeature(config: config,
featureFlag: featureFlag,
userId: userId,
attributes: attributes ?? OptimizelyAttributes(),
options: nil).result
if let featureEnabled = decision?.variation.featureEnabled {
enabled = featureEnabled
if featureEnabled {
logger.i(.featureEnabledForUser(featureKey, userId))
} else {
logger.i(.featureNotEnabledForUser(featureKey, userId))
}
} else {
logger.i(.userReceivedAllDefaultVariableValues(userId, featureKey))
}
for (_, v) in featureFlag.variablesMap {
var featureValue = v.value
if enabled, let variable = decision?.variation.getVariable(id: v.id) {
featureValue = variable.value
}
var valueParsed: Any? = featureValue
if let valueType = Constants.VariableValueType(rawValue: v.type) {
switch valueType {
case .string:
break
case .integer:
valueParsed = Int(featureValue)
case .double:
valueParsed = Double(featureValue)
case .boolean:
valueParsed = Bool(featureValue)
case .json:
valueParsed = OptimizelyJSON(payload: featureValue)?.toMap()
}
}
if let value = valueParsed {
variableMap[v.key] = value
} else {
logger.e(OptimizelyError.variableValueInvalid(v.key))
}
}
guard let optimizelyJSON = OptimizelyJSON(map: variableMap) else {
throw OptimizelyError.invalidJSONVariable
}
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: .allFeatureVariables,
experiment: decision?.experiment,
variation: decision?.variation,
source: decision?.source,
feature: featureFlag,
featureEnabled: enabled,
variableValues: variableMap))
return optimizelyJSON
}
/// Get array of features that are enabled for the user.
///
/// - Parameters:
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: Array of feature keys that are enabled for the user.
public func getEnabledFeatures(userId: String,
attributes: OptimizelyAttributes? = nil) -> [String] {
var enabledFeatures = [String]()
guard let config = self.config else {
logger.e(.sdkNotReady)
return enabledFeatures
}
enabledFeatures = config.getFeatureFlags().filter {
isFeatureEnabled(featureKey: $0.key, userId: userId, attributes: attributes)
}.map { $0.key }
return enabledFeatures
}
/// Track an event
///
/// - Parameters:
/// - eventKey: The event name
/// - userId: The user ID associated with the event to track
/// - attributes: The user's attributes.
/// - eventTags: A map of event tag names to event tag values (NSString or NSNumber containing float, double, integer, or boolean)
/// - Throws: `OptimizelyError` if error is detected
public func track(eventKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil,
eventTags: OptimizelyEventTags? = nil) throws {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
if config.getEvent(key: eventKey) == nil {
throw OptimizelyError.eventKeyInvalid(eventKey)
}
sendConversionEvent(eventKey: eventKey, userId: userId, attributes: attributes, eventTags: eventTags)
}
/// Read a copy of project configuration data model.
///
/// This call returns a snapshot of the current project configuration.
///
/// When the caller keeps a copy of the return value, note that this data can be stale when a new datafile is downloaded (it's possible only when background datafile polling is enabled).
///
/// If a datafile change is notified (NotificationType.datafileChange), this method should be called again to get the updated configuration data.
///
/// - Returns: a snapshot of public project configuration data model
/// - Throws: `OptimizelyError` if SDK is not ready
public func getOptimizelyConfig() throws -> OptimizelyConfig {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
return OptimizelyConfigImp(projectConfig: config)
}
}
// MARK: - Send Events
extension OptimizelyClient {
func shouldSendDecisionEvent(source: String, decision: FeatureDecision?) -> Bool {
guard let config = self.config else { return false }
return (source == Constants.DecisionSource.featureTest.rawValue && decision?.variation != nil) || config.sendFlagDecisions
}
func sendImpressionEvent(experiment: Experiment?,
variation: Variation?,
userId: String,
attributes: OptimizelyAttributes? = nil,
flagKey: String,
ruleType: String,
enabled: Bool) {
// non-blocking (event data serialization takes time)
eventLock.async {
guard let config = self.config else { return }
guard let body = BatchEventBuilder.createImpressionEvent(config: config,
experiment: experiment,
variation: variation,
userId: userId,
attributes: attributes,
flagKey: flagKey,
ruleType: ruleType,
enabled: enabled) else {
self.logger.e(OptimizelyError.eventBuildFailure(DispatchEvent.activateEventKey))
return
}
let event = EventForDispatch(body: body)
self.sendEventToDispatcher(event: event, completionHandler: nil)
// send notification in sync mode (functionally same as async here since it's already in background thread),
// but this will make testing simpler (timing control)
if let tmpExperiment = experiment, let tmpVariation = variation {
self.sendActivateNotification(experiment: tmpExperiment,
variation: tmpVariation,
userId: userId,
attributes: attributes,
event: event,
async: false)
}
}
}
func sendConversionEvent(eventKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil,
eventTags: OptimizelyEventTags? = nil) {
// non-blocking (event data serialization takes time)
eventLock.async {
guard let config = self.config else { return }
guard let body = BatchEventBuilder.createConversionEvent(config: config,
eventKey: eventKey,
userId: userId,
attributes: attributes,
eventTags: eventTags) else {
self.logger.e(OptimizelyError.eventBuildFailure(eventKey))
return
}
let event = EventForDispatch(body: body)
self.sendEventToDispatcher(event: event, completionHandler: nil)
// send notification in sync mode (functionally same as async here since it's already in background thread),
// but this will make testing simpler (timing control)
self.sendTrackNotification(eventKey: eventKey,
userId: userId,
attributes: attributes,
eventTags: eventTags,
event: event,
async: false)
}
}
func sendEventToDispatcher(event: EventForDispatch, completionHandler: DispatchCompletionHandler?) {
// The event is queued in the dispatcher, batched, and sent out later.
// make sure that eventDispatcher is not-nil (still registered when async dispatchEvent is called)
self.eventDispatcher?.dispatchEvent(event: event, completionHandler: completionHandler)
}
}
// MARK: - Notifications
extension OptimizelyClient {
func sendActivateNotification(experiment: Experiment,
variation: Variation,
userId: String,
attributes: OptimizelyAttributes?,
event: EventForDispatch,
async: Bool = true) {
self.sendNotification(type: .activate,
args: [experiment,
userId,
attributes,
variation,
["url": event.url as Any, "body": event.body as Any]],
async: async)
}
func sendTrackNotification(eventKey: String,
userId: String,
attributes: OptimizelyAttributes?,
eventTags: OptimizelyEventTags?,
event: EventForDispatch,
async: Bool = true) {
self.sendNotification(type: .track,
args: [eventKey,
userId,
attributes,
eventTags,
["url": event.url as Any, "body": event.body as Any]],
async: async)
}
func sendDecisionNotification(userId: String,
attributes: OptimizelyAttributes?,
decisionInfo: DecisionInfo,
async: Bool = true) {
self.sendNotification(type: .decision,
args: [decisionInfo.decisionType.rawValue,
userId,
attributes ?? OptimizelyAttributes(),
decisionInfo.toMap],
async: async)
}
func sendDatafileChangeNotification(data: Data, async: Bool = true) {
self.sendNotification(type: .datafileChange, args: [data], async: async)
}
func sendNotification(type: NotificationType, args: [Any?], async: Bool = true) {
let notify = {
// make sure that notificationCenter is not-nil (still registered when async notification is called)
self.notificationCenter?.sendNotifications(type: type.rawValue, args: args)
}
if async {
eventLock.async {
notify()
}
} else {
notify()
}
}
}
// MARK: - For test support
extension OptimizelyClient {
public func close() {
datafileHandler?.stopUpdates(sdkKey: sdkKey)
eventLock.sync {}
eventDispatcher?.close()
}
}
| 45.658065 | 190 | 0.524822 |
8f3c19d4e017dabacca886c863bbc7746c3385c5 | 1,459 | // The MIT License (MIT)
//
// Copyright (c) 2016 Caleb Kleveter
//
// 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.
/// Designates an object as capable of being rendered into HTML.
public protocol ElementRenderable {
/// The element the is at the top level for the object. Example: If there is a form, the top level element would be the `UIElement` that is form.
var topLevelElement: UIElement { get }
}
| 50.310345 | 149 | 0.745716 |
3a857b6ca3dd08f698fdcead864537d3b0013ba4 | 822 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "trials",
products: [
.library(name: "App", targets: ["App"]),
.executable(name: "Run", targets: ["Run"])
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")),
.package(url: "https://github.com/vapor/leaf-provider.git", .upToNextMajor(from: "1.1.0")),
.package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.3.0"))
],
targets: [
.target(name: "App", dependencies: ["Vapor", "LeafProvider", "FluentProvider"],
exclude: [
"Config",
"Public",
"Resources",
]
),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App", "Testing"])
]
)
| 27.4 | 96 | 0.597324 |
75da4ba961ad6f7bd5faa88038977624d356b283 | 2,377 | //
// ConnectionDataTest.swift
// Smartpad-iOSTests
//
// Created by Alireza Azimi on 2022-03-13.
//
import XCTest
@testable import Smartpad_iOS
class ConnectionDataTest: XCTestCase {
override func tearDown() {
super.tearDown()
resetDefaults()
}
func resetDefaults() {
let defaults = UserDefaults.standard
let dictionary = defaults.dictionaryRepresentation()
dictionary.keys.forEach { key in
defaults.removeObject(forKey: key)
}
}
func testSetCurrentDeviceName() {
// Arrange
let data = ConnectionData()
// Act
let name = "my iPhone"
data.setDeviceName(name: name)
//Assert
XCTAssertEqual(UserDefaults.standard.string(forKey: ConnectionKeys.currDeviceName), "my iPhone")
}
func testGetCurrentDeviceName() {
//Arrange
resetDefaults()
let data = ConnectionData()
// Act
let name = "my iPhone"
data.setDeviceName(name: name)
//Assert
XCTAssertEqual(data.getDeviceName(), "my iPhone")
}
func testSetCurrentDeviceUUID() {
// Arrange
resetDefaults()
let uuidString = UUID().uuidString
let data = ConnectionData()
// Act
data.setCurrentDeviceUUID(uuid: uuidString)
// Assert
XCTAssertEqual(UserDefaults.standard.string(forKey: ConnectionKeys.currDeviceUUID), uuidString)
}
func testGetCurrentDeviceUUID() {
// Arrange
resetDefaults()
let uuidString = UUID().uuidString
let data = ConnectionData()
// Act
data.setCurrentDeviceUUID(uuid: uuidString)
// Assert
XCTAssertEqual(data.getCurrentDeviceUUID(), uuidString)
}
func testSetPeerName() {
// Arrange
resetDefaults()
let data = ConnectionData()
// Act
data.setSelectedPeer(name: "Ali's macbook")
// Assert
XCTAssertEqual(UserDefaults.standard.string(forKey: ConnectionKeys.selectedPeerName), "Ali's macbook")
}
func testGetPeerName() {
// Arrange
resetDefaults()
let data = ConnectionData()
// Act
data.setSelectedPeer(name: "Ali's macbook")
// Assert
XCTAssertEqual(data.getSelectedPeer(), "Ali's macbook")
}
}
| 26.707865 | 110 | 0.603281 |
9126463c74ecdd2dde4ebd53a35523fedad6149a | 2,233 | //
// UIView.swift
// ios-calendar-clone-uikit
//
// Created by Chandan Karmakar on 17/09/21.
//
import UIKit
public extension UIView {
func addPinConstraints(_ val: CGFloat = 0) {
guard let parent = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
leadingAnchor.constraint(equalTo: parent.leadingAnchor, constant: val).isActive = true
trailingAnchor.constraint(equalTo: parent.trailingAnchor, constant: -val).isActive = true
topAnchor.constraint(equalTo: parent.topAnchor, constant: val).isActive = true
bottomAnchor.constraint(equalTo: parent.bottomAnchor, constant: -val).isActive = true
}
func addPinConstraints(top: CGFloat? = nil, left: CGFloat? = nil, bottom: CGFloat? = nil, right: CGFloat? = nil) {
guard let parent = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
if let left = left {
leadingAnchor.constraint(equalTo: parent.leadingAnchor, constant: left).isActive = true
}
if let right = right {
trailingAnchor.constraint(equalTo: parent.trailingAnchor, constant: -right).isActive = true
}
if let top = top {
topAnchor.constraint(equalTo: parent.topAnchor, constant: top).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: parent.bottomAnchor, constant: -bottom).isActive = true
}
}
var isPortrait: Bool {
switch UIDevice.current.orientation {
case .unknown, .portrait, .portraitUpsideDown, .faceUp, .faceDown:
return true
case .landscapeLeft, .landscapeRight:
return false
@unknown default:
return true
}
}
var pixelSize: CGFloat {
return 1 / UIScreen.main.scale
}
}
#if canImport(SwiftUI) && DEBUG
import SwiftUI
extension UIView {
func swiftUIView() -> SwiftUIView {
return SwiftUIView(view: self)
}
}
struct SwiftUIView: UIViewRepresentable {
let view: UIView
func makeUIView(context: Context) -> UIView {
return view
}
func updateUIView(_ view: UIView, context: Context) {}
}
#endif
| 31.450704 | 118 | 0.648455 |
e6190f9cac84a0851f33ede9a33e698fd3859aee | 4,217 | import CryptoSwift
import secp256k1
public class EllipticCurveEncrypterSecp256k1 {
// holds internal state of the c library
private let context: OpaquePointer
public init() {
context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))!
}
deinit {
secp256k1_context_destroy(context)
}
/// Signs the hash with the private key. Produces signature data structure that can be exported with
/// export(signature:) method.
///
/// - Parameters:
/// - hash: 32-byte (256-bit) hash of the message
/// - privateKey: 32-byte private key
/// - Returns: signature data structure if signing succeeded, otherwise nil.
public func sign(hash: Data, privateKey: Data) -> secp256k1_ecdsa_recoverable_signature? {
precondition(hash.count == 32, "Hash must be 32 bytes size")
var signature = secp256k1_ecdsa_recoverable_signature()
let status = SecpResult(privateKey.withUnsafeBytes { (key: UnsafePointer<UInt8>) in
hash.withUnsafeBytes { secp256k1_ecdsa_sign_recoverable(context, &signature, $0, key, nil, nil) }
})
return status == .success ? signature : nil
}
/// Converts signature data structure to 65 bytes.
///
/// - Parameter signature: signature data structure
/// - Returns: 65 byte exported signature data.
public func export(signature: inout secp256k1_ecdsa_recoverable_signature) -> Data {
var output = Data(count: 65)
var recId = 0 as Int32
_ = output.withUnsafeMutableBytes { (output: UnsafeMutablePointer<UInt8>) in
secp256k1_ecdsa_recoverable_signature_serialize_compact(context, output, &recId, &signature)
}
output[64] = UInt8(recId)
return output
}
/// Converts serialized signature into library's signature format. Use it to supply signature to
/// the publicKey(signature:hash:) method.
///
/// - Parameter signature: serialized 65-byte signature
/// - Returns: signature structure
public func `import`(signature: Data) -> secp256k1_ecdsa_recoverable_signature {
precondition(signature.count == 65, "Signature must be 65 byte size")
var sig = secp256k1_ecdsa_recoverable_signature()
let recId = Int32(signature[64])
signature.withUnsafeBytes { (input: UnsafePointer<UInt8>) -> Void in
secp256k1_ecdsa_recoverable_signature_parse_compact(context, &sig, input, recId)
}
return sig
}
/// Recovers public key from the signature and the hash. Use import(signature:) to convert signature from bytes.
/// Use export(publicKey:compressed) to convert recovered public key into bytes.
///
/// - Parameters:
/// - signature: signature structure
/// - hash: 32-byte (256-bit) hash of a message
/// - Returns: public key structure or nil, if signature invalid
public func publicKey(signature: inout secp256k1_ecdsa_recoverable_signature, hash: Data) -> secp256k1_pubkey? {
precondition(hash.count == 32, "Hash must be 32 bytes size")
let hash = hash.bytes
var outPubKey = secp256k1_pubkey()
let status = SecpResult(secp256k1_ecdsa_recover(context, &outPubKey, &signature, hash))
return status == .success ? outPubKey : nil
}
/// Converts public key from library's data structure to bytes
///
/// - Parameters:
/// - publicKey: public key structure to convert.
/// - compressed: whether public key should be compressed.
/// - Returns: If compression enabled, public key is 33 bytes size, otherwise it is 65 bytes.
public func export(publicKey: inout secp256k1_pubkey, compressed: Bool) -> Data {
var output = Data(count: compressed ? 33 : 65)
var outputLen: Int = output.count
let compressedFlags = compressed ? UInt32(SECP256K1_EC_COMPRESSED) : UInt32(SECP256K1_EC_UNCOMPRESSED)
output.withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) -> Void in
secp256k1_ec_pubkey_serialize(context, pointer, &outputLen, &publicKey, compressedFlags)
}
return output
}
}
| 45.344086 | 116 | 0.675362 |
205423a7dfb77d29f3505b6217e505fff92c5e17 | 420 | extension Dictionary {
mutating func merge<S: Sequence>(contentsOf other: S) where S.Iterator.Element == (key: Key, value: Value) {
for (key, value) in other {
self[key] = value
}
}
func merged<S: Sequence>(with other: S) -> [Key: Value] where S.Iterator.Element == (key: Key, value: Value) {
var dic = self
dic.merge(contentsOf: other)
return dic
}
} | 32.307692 | 114 | 0.580952 |
22b207412db069f38cae772decaa0dc6c632ad81 | 7,893 | //
// MapViewDelegate.swift
// SmartGPSTracker
//
// Created by Mosquito1123 on 11/07/2019.
// Copyright © 2019 Cranberry. All rights reserved.
//
import MapKit
import CoreGPX
/// Handles all delegate functions of the GPX Mapview
///
class MapViewDelegate: NSObject, MKMapViewDelegate, UIAlertViewDelegate {
/// The Waypoint is being edited (if there is any)
var waypointBeingEdited: GPXWaypoint = GPXWaypoint()
/// Displays a pin with whose annotation (bubble) will include delete and edit buttons.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKind(of: MKUserLocation.self) {
return nil
}
let annotationView: MKPinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "PinView")
annotationView.canShowCallout = true
annotationView.isDraggable = true
//let detailButton: UIButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton
let deleteButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
deleteButton.setImage(UIImage(named: "delete"), for: UIControl.State())
deleteButton.setImage(UIImage(named: "deleteHigh"), for: .highlighted)
deleteButton.tag = kDeleteWaypointAccesoryButtonTag
annotationView.rightCalloutAccessoryView = deleteButton
let editButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
editButton.setImage(UIImage(named: "edit"), for: UIControl.State())
editButton.setImage(UIImage(named: "editHigh"), for: .highlighted)
editButton.tag = kEditWaypointAccesoryButtonTag
annotationView.leftCalloutAccessoryView = editButton
return annotationView
}
/// Displays the line for each segment
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay.isKind(of: MKTileOverlay.self) {
return MKTileOverlayRenderer(overlay: overlay)
}
if overlay is MKPolyline {
let pr = MKPolylineRenderer(overlay: overlay)
pr.strokeColor = UIColor.blue.withAlphaComponent(0.5)
pr.lineWidth = 3
return pr
}
return MKOverlayRenderer()
}
/// Handles the actions of delete and edit button
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
print("calloutAccesoryControlTapped ")
guard let waypoint = view.annotation as? GPXWaypoint else {
return
}
guard let button = control as? UIButton else {
return
}
guard let map = mapView as? GPXMapView else {
return
}
switch button.tag {
case kDeleteWaypointAccesoryButtonTag:
print("[calloutAccesoryControlTapped: DELETE button] deleting waypoint with name \(waypoint.name ?? "''")")
map.removeWaypoint(waypoint)
case kEditWaypointAccesoryButtonTag:
print("[calloutAccesoryControlTapped: EDIT] editing waypoint with name \(waypoint.name ?? "''")")
let alertController = UIAlertController(title: "Edit waypoint name", message: "Hint: To change the waypoint location drag and drop the pin", preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.text = waypoint.title
textField.clearButtonMode = .always
}
let saveAction = UIAlertAction(title: "Save", style: .default) { (action) in
print("Edit waypoint alert view")
self.waypointBeingEdited.title = alertController.textFields?[0].text
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in }
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true)
self.waypointBeingEdited = waypoint
default:
print("[calloutAccesoryControlTapped ERROR] unknown control")
}
}
/// Handles the change of the coordinates when a pin is dropped.
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
didChange newState: MKAnnotationView.DragState, fromOldState oldState: MKAnnotationView.DragState) {
if newState == MKAnnotationView.DragState.ending {
if let point = view.annotation as? GPXWaypoint {
point.elevation = nil
print("Annotation name: \(String(describing: point.title)) lat:\(String(describing:point.latitude)) lon \(String(describing:point.longitude))")
}
}
}
/// Adds the pin to the map with an animation (comes from the top of the screen)
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
var i = 0
let gpxMapView = mapView as! GPXMapView
//adds the pins with an animation
for object in views {
i += 1
let annotationView = object as MKAnnotationView
//The only exception is the user location, we add to this the heading icon.
if annotationView.annotation!.isKind(of: MKUserLocation.self) {
if gpxMapView.headingImageView == nil {
let image = UIImage(named: "heading")!
gpxMapView.headingImageView = UIImageView(image: image)
gpxMapView.headingImageView!.frame = CGRect(x: (annotationView.frame.size.width - image.size.width)/2, y: (annotationView.frame.size.height - image.size.height)/2, width: image.size.width, height: image.size.height)
annotationView.insertSubview(gpxMapView.headingImageView!, at: 0)
gpxMapView.headingImageView!.isHidden = true
}
continue
}
let point: MKMapPoint = MKMapPoint.init(annotationView.annotation!.coordinate)
if !mapView.visibleMapRect.contains(point) { continue }
let endFrame: CGRect = annotationView.frame
annotationView.frame = CGRect(x: annotationView.frame.origin.x, y: annotationView.frame.origin.y - mapView.superview!.frame.size.height,
width: annotationView.frame.size.width, height:annotationView.frame.size.height)
let interval: TimeInterval = 0.04 * 1.1
UIView.animate(withDuration: 0.5, delay: interval, options: UIView.AnimationOptions.curveLinear, animations: { () -> Void in
annotationView.frame = endFrame
}, completion: { (finished) -> Void in
if finished {
UIView.animate(withDuration: 0.05, animations: { () -> Void in
//aV.transform = CGAffineTransformMakeScale(1.0, 0.8)
annotationView.transform = CGAffineTransform(a: 1.0, b: 0, c: 0, d: 0.8, tx: 0, ty: annotationView.frame.size.height*0.1)
}, completion: { (finished: Bool) -> Void in
UIView.animate(withDuration: 0.1, animations: { () -> Void in
annotationView.transform = CGAffineTransform.identity
})
})
}
})
}
}
///
/// Adds a small arrow image to the annotationView.
/// This annotationView should be the MKUserLocation
///
func addHeadingView(toAnnotationView annotationView: MKAnnotationView) {
}
}
| 46.982143 | 235 | 0.62245 |
de5bc80ec0388b17b937f87c91bab0778e7e3961 | 670 | import Cocoa
import FlutterMacOS
public class ImageCompressionPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "image_compression", binaryMessenger: registrar.messenger)
let instance = ImageCompressionPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getPlatformVersion":
result("macOS " + ProcessInfo.processInfo.operatingSystemVersionString)
default:
result(FlutterMethodNotImplemented)
}
}
}
| 33.5 | 103 | 0.768657 |
e56bfd582d31c6c2f197481c8127d8ab3f102cd8 | 1,467 | //
// DYZBUITests.swift
// DYZBUITests
//
// Created by Vickey Feng on 2020/6/14.
// Copyright © 2020 Vickey Feng. All rights reserved.
//
import XCTest
class DYZBUITests: 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: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 33.340909 | 182 | 0.658487 |
38d15dbbea8a24199d2ec582cbb525aae9010ddb | 241 | import Core
extension Cookies: BytesConvertible {
public init(bytes: Bytes) throws {
try self.init(bytes, for: .request)
}
public func makeBytes() throws -> Bytes {
return serialize(for: .request).bytes
}
}
| 20.083333 | 45 | 0.639004 |
673b5de7603bf17d79cf67aec7c7b1023dca9cc1 | 298 | //
// MenuInfo.swift
// BaeMinApp
//
// Created by KEEN on 2021/09/29.
//
import Foundation
import UIKit
class MenuInfo {
var name: String
var image: UIImage
init(name: String) {
self.name = name
self.image = UIImage(named: name) ?? UIImage(systemName: "square.slash")!
}
}
| 14.9 | 77 | 0.644295 |
5b636b3753b4efad55c5087d4c5d01243197c7ab | 255 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for in {
class r {
func f {
return ( ) .m( ) {
struct d {
var a {
init {
class
case ,
| 18.214286 | 87 | 0.698039 |
1ce0645fc8d0f57826ef1f312e0c81f0331c9118 | 276 | //
// CalendarCollectionViewCell.swift
// T-Helper
//
// Created by zjajgyy on 2016/11/28.
// Copyright © 2016年 thelper. All rights reserved.
//
import UIKit
class CalendarCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var timeLabel: UILabel!
}
| 17.25 | 56 | 0.706522 |
082143a59aee88005e029efce1ce982341380e28 | 7,206 | //
// RecordButtonKit.swift
// RecordButtonText
//
// Created by Mark Alldritt on 2016-12-20.
// Copyright © 2016 Late Night Software Ltd.. All rights reserved.
//
// Generated by PaintCode
// http://www.paintcodeapp.com
//
import UIKit
public class RecordButtonKit : NSObject {
//// Cache
private struct Cache {
static let recordButtonColor: UIColor = UIColor(red: 1.000, green: 0.000, blue: 0.000, alpha: 1.000)
static let recordButtonHighlightedColor: UIColor = RecordButtonKit.recordButtonColor.withBrightness(0.3)
static let recordFrameColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
static let recordButtonNormalColor: UIColor = RecordButtonKit.recordButtonColor
}
//// Colors
public dynamic class var recordButtonColor: UIColor { return Cache.recordButtonColor }
public dynamic class var recordButtonHighlightedColor: UIColor { return Cache.recordButtonHighlightedColor }
public dynamic class var recordFrameColor: UIColor { return Cache.recordFrameColor }
public dynamic class var recordButtonNormalColor: UIColor { return Cache.recordButtonNormalColor }
//// Drawing Methods
public dynamic class func drawRecordButton(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, recordButtonFrameColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000), isRecording: CGFloat = 1, isPressed: Bool = false) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
//// Variable Declarations
let radius: CGFloat = 10 + 37 * min(isRecording * 1.88, 1)
let buttonScale: CGFloat = 1 - (1 - isRecording) * 0.45
let buttonFillColor = isPressed ? RecordButtonKit.recordButtonHighlightedColor : RecordButtonKit.recordButtonNormalColor
//// Oval Drawing
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 4, y: 4, width: 92, height: 92))
recordButtonFrameColor.setStroke()
ovalPath.lineWidth = 8
ovalPath.stroke()
//// Rectangle Drawing
context.saveGState()
context.translateBy(x: 50, y: 50)
context.scaleBy(x: buttonScale, y: buttonScale)
let rectanglePath = UIBezierPath(roundedRect: CGRect(x: -39, y: -39, width: 78, height: 78), cornerRadius: radius)
buttonFillColor.setFill()
rectanglePath.fill()
context.restoreGState()
context.restoreGState()
}
//// Generated Images
public dynamic class func imageOfRecordButton(recordButtonFrameColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000), isRecording: CGFloat = 1, isPressed: Bool = false) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 100, height: 100), false, 0)
RecordButtonKit.drawRecordButton(recordButtonFrameColor: recordButtonFrameColor, isRecording: isRecording, isPressed: isPressed)
let imageOfRecordButton = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return imageOfRecordButton
}
@objc public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: CGRect, target: CGRect) -> CGRect {
if rect == target || target == CGRect.zero {
return rect
}
var scales = CGSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
extension UIColor {
func withHue(_ newHue: CGFloat) -> UIColor {
var saturation: CGFloat = 1, brightness: CGFloat = 1, alpha: CGFloat = 1
self.getHue(nil, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return UIColor(hue: newHue, saturation: saturation, brightness: brightness, alpha: alpha)
}
func withSaturation(_ newSaturation: CGFloat) -> UIColor {
var hue: CGFloat = 1, brightness: CGFloat = 1, alpha: CGFloat = 1
self.getHue(&hue, saturation: nil, brightness: &brightness, alpha: &alpha)
return UIColor(hue: hue, saturation: newSaturation, brightness: brightness, alpha: alpha)
}
func withBrightness(_ newBrightness: CGFloat) -> UIColor {
var hue: CGFloat = 1, saturation: CGFloat = 1, alpha: CGFloat = 1
self.getHue(&hue, saturation: &saturation, brightness: nil, alpha: &alpha)
return UIColor(hue: hue, saturation: saturation, brightness: newBrightness, alpha: alpha)
}
func withAlpha(_ newAlpha: CGFloat) -> UIColor {
var hue: CGFloat = 1, saturation: CGFloat = 1, brightness: CGFloat = 1
self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: nil)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: newAlpha)
}
func highlight(withLevel highlight: CGFloat) -> UIColor {
var red: CGFloat = 1, green: CGFloat = 1, blue: CGFloat = 1, alpha: CGFloat = 1
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return UIColor(red: red * (1-highlight) + highlight, green: green * (1-highlight) + highlight, blue: blue * (1-highlight) + highlight, alpha: alpha * (1-highlight) + highlight)
}
func shadow(withLevel shadow: CGFloat) -> UIColor {
var red: CGFloat = 1, green: CGFloat = 1, blue: CGFloat = 1, alpha: CGFloat = 1
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return UIColor(red: red * (1-shadow), green: green * (1-shadow), blue: blue * (1-shadow), alpha: alpha * (1-shadow) + shadow)
}
}
| 44.208589 | 309 | 0.650569 |
3832680971b25583dd07e2f62032eef078151a98 | 6,882 | //
// Line.swift
// LineChart
//
// Created by András Samu on 2019. 08. 30..
// Copyright © 2019. András Samu. All rights reserved.
//
import SwiftUI
public struct Line: View {
@ObservedObject var data: ChartData
@Binding var frame: CGRect
@Binding var touchLocation: CGPoint
@Binding var showIndicator: Bool
@State private var showFull: Bool = false
@State var showBackground: Bool = true
public init(data: ChartData, frame: CGRect, touchLocation: CGPoint, showIndicator: Bool) {
self.data = data
self.frame = frame
self.touchLocation = touchLocation
self.showIndicator = showIndicator
}
let padding:CGFloat = 30
var stepWidth: CGFloat {
if data.points.count < 2 {
return 0
}
return frame.size.width / CGFloat(data.points.count-1)
}
var stepHeight: CGFloat {
let points = self.data.onlyPoints()
if let min = points.min(), let max = points.max(), min != max {
if (min <= 0){
return (frame.size.height-padding) / CGFloat(points.max()! - points.min()!)
}else{
return (frame.size.height-padding) / CGFloat(points.max()! + points.min()!)
}
}
return 0
}
var path: Path {
let points = self.data.onlyPoints()
return Path.quadCurvedPathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight))
}
var closedPath: Path {
let points = self.data.onlyPoints()
return Path.quadClosedCurvedPathWithPoints(points: points, step: CGPoint(x: stepWidth, y: stepHeight))
}
public var body: some View {
ZStack {
if(self.showFull && self.showBackground){
self.closedPath
.fill(LinearGradient(gradient: Gradient(colors: [Colors.GradientUpperBlue, .white]), startPoint: .bottom, endPoint: .top))
.rotationEffect(.degrees(180), anchor: .center)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
.transition(.opacity)
.animation(.easeIn(duration: 1.6))
}
self.path
.trim(from: 0, to: self.showFull ? 1:0)
.stroke(LinearGradient(gradient: Gradient(colors: [Colors.GradientPurple, Colors.GradientNeonBlue]), startPoint: .leading, endPoint: .trailing) ,style: StrokeStyle(lineWidth: 3))
.rotationEffect(.degrees(180), anchor: .center)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
.animation(.easeOut(duration: 1.2))
.onAppear(){
self.showFull.toggle()
}.drawingGroup()
if(self.showIndicator) {
IndicatorPoint()
.position(self.getClosestPointOnPath(touchLocation: self.touchLocation))
.rotationEffect(.degrees(180), anchor: .center)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
}
}
}
func getClosestPointOnPath(touchLocation: CGPoint) -> CGPoint {
let percentage:CGFloat = min(max(touchLocation.x,0)/self.frame.width,1)
let closest = self.path.percentPoint(percentage)
return closest
}
}
extension CGPoint {
static func getMidPoint(point1: CGPoint, point2: CGPoint) -> CGPoint {
return CGPoint(
x: point1.x + (point2.x - point1.x) / 2,
y: point1.y + (point2.y - point1.y) / 2
)
}
func dist(to: CGPoint) -> CGFloat {
return sqrt((pow(self.x - to.x, 2) + pow(self.y - to.y, 2)))
}
static func midPointForPoints(p1:CGPoint, p2:CGPoint) -> CGPoint {
return CGPoint(x:(p1.x + p2.x) / 2,y: (p1.y + p2.y) / 2)
}
static func controlPointForPoints(p1:CGPoint, p2:CGPoint) -> CGPoint {
var controlPoint = CGPoint.midPointForPoints(p1:p1, p2:p2)
let diffY = abs(p2.y - controlPoint.y)
if (p1.y < p2.y){
controlPoint.y += diffY
} else if (p1.y > p2.y) {
controlPoint.y -= diffY
}
return controlPoint
}
}
extension Path {
static func quadCurvedPathWithPoints(points:[Double], step:CGPoint) -> Path {
var path = Path()
if (points.count < 2){
return path
}
guard var offset = points.min() else { return path }
offset -= 3
var p1 = CGPoint(x: 0, y: CGFloat(points[0]-offset)*step.y)
path.move(to: p1)
for pointIndex in 1..<points.count {
let p2 = CGPoint(x: step.x * CGFloat(pointIndex), y: step.y*CGFloat(points[pointIndex]-offset))
let midPoint = CGPoint.midPointForPoints(p1: p1, p2: p2)
path.addQuadCurve(to: midPoint, control: CGPoint.controlPointForPoints(p1: midPoint, p2: p1))
path.addQuadCurve(to: p2, control: CGPoint.controlPointForPoints(p1: midPoint, p2: p2))
p1 = p2
}
return path
}
static func quadClosedCurvedPathWithPoints(points:[Double], step:CGPoint) -> Path {
var path = Path()
if (points.count < 2){
return path
}
guard var offset = points.min() else { return path }
offset -= 3
path.move(to: .zero)
var p1 = CGPoint(x: 0, y: CGFloat(points[0]-offset)*step.y)
path.addLine(to: p1)
for pointIndex in 1..<points.count {
let p2 = CGPoint(x: step.x * CGFloat(pointIndex), y: step.y*CGFloat(points[pointIndex]-offset))
let midPoint = CGPoint.midPointForPoints(p1: p1, p2: p2)
path.addQuadCurve(to: midPoint, control: CGPoint.controlPointForPoints(p1: midPoint, p2: p1))
path.addQuadCurve(to: p2, control: CGPoint.controlPointForPoints(p1: midPoint, p2: p2))
p1 = p2
}
path.addLine(to: CGPoint(x: p1.x, y: 0))
path.closeSubpath()
return path
}
func percentPoint(_ percent: CGFloat) -> CGPoint {
// percent difference between points
let diff: CGFloat = 0.001
let comp: CGFloat = 1 - diff
// handle limits
let pct = percent > 1 ? 0 : (percent < 0 ? 1 : percent)
let f = pct > comp ? comp : pct
let t = pct > comp ? 1 : pct + diff
let tp = self.trimmedPath(from: f, to: t)
return CGPoint(x: tp.boundingRect.midX, y: tp.boundingRect.midY)
}
}
struct Line_Previews: PreviewProvider {
static var previews: some View {
GeometryReader{ geometry in
Line(data: ChartData(points: [12,-230,10,54]), frame: .constant(geometry.frame(in: .local)), touchLocation: .constant(CGPoint(x: 100, y: 12)), showIndicator: .constant(true))
}.frame(width: 320, height: 160)
}
}
| 37.606557 | 194 | 0.574252 |
62823a7d3ac3c8cd269dfb245d2140c2814594bc | 6,560 | extension Model {
public typealias OptionalChild<To> = OptionalChildProperty<Self, To>
where To: FluentKit.Model
}
// MARK: Type
@propertyWrapper
public final class OptionalChildProperty<From, To>
where From: Model, To: Model
{
public enum Key {
case required(KeyPath<To, To.Parent<From>>)
case optional(KeyPath<To, To.OptionalParent<From>>)
}
public let parentKey: Key
var idValue: From.IDValue?
public var value: To??
public init(for parent: KeyPath<To, To.Parent<From>>) {
self.parentKey = .required(parent)
}
public init(for optionalParent: KeyPath<To, To.OptionalParent<From>>) {
self.parentKey = .optional(optionalParent)
}
public var wrappedValue: To? {
get {
guard let value = self.value else {
fatalError("Child relation not eager loaded, use $ prefix to access: \(name)")
}
return value
}
set {
fatalError("Child relation is get-only.")
}
}
public var projectedValue: OptionalChildProperty<From, To> {
return self
}
public var fromId: From.IDValue? {
return self.idValue
}
public func query(on database: Database) -> QueryBuilder<To> {
guard let id = self.idValue else {
fatalError("Cannot query child relation from unsaved model.")
}
let builder = To.query(on: database)
switch self.parentKey {
case .optional(let optional):
builder.filter(optional.appending(path: \.$id) == id)
case .required(let required):
builder.filter(required.appending(path: \.$id) == id)
}
return builder
}
public func create(_ to: To, on database: Database) -> EventLoopFuture<Void> {
guard let id = self.idValue else {
fatalError("Cannot save child to unsaved model.")
}
switch self.parentKey {
case .required(let keyPath):
to[keyPath: keyPath].id = id
case .optional(let keyPath):
to[keyPath: keyPath].id = id
}
return to.create(on: database)
}
}
extension OptionalChildProperty: CustomStringConvertible {
public var description: String {
self.name
}
}
// MARK: Property
extension OptionalChildProperty: AnyProperty { }
extension OptionalChildProperty: Property {
public typealias Model = From
public typealias Value = To?
}
// MARK: Database
extension OptionalChildProperty: AnyDatabaseProperty {
public var keys: [FieldKey] {
[]
}
public func input(to input: DatabaseInput) {
// child never has input
}
public func output(from output: DatabaseOutput) throws {
let key = From()._$id.field.key
if output.contains(key) {
self.idValue = try output.decode(key, as: From.IDValue.self)
}
}
}
// MARK: Codable
extension OptionalChildProperty: AnyCodableProperty {
public func encode(to encoder: Encoder) throws {
if let child = self.value {
var container = encoder.singleValueContainer()
try container.encode(child)
}
}
public func decode(from decoder: Decoder) throws {
// don't decode
}
}
// MARK: Relation
extension OptionalChildProperty: Relation {
public var name: String {
"Child<\(From.self), \(To.self)>(for: \(self.parentKey))"
}
public func load(on database: Database) -> EventLoopFuture<Void> {
self.query(on: database).first().map {
self.value = $0
}
}
}
extension OptionalChildProperty.Key: CustomStringConvertible {
public var description: String {
switch self {
case .optional(let keyPath):
return To.path(for: keyPath.appending(path: \.$id)).description
case .required(let keyPath):
return To.path(for: keyPath.appending(path: \.$id)).description
}
}
}
// MARK: Eager Loadable
extension OptionalChildProperty: EagerLoadable {
public static func eagerLoad<Builder>(
_ relationKey: KeyPath<From, From.OptionalChild<To>>,
to builder: Builder
)
where Builder: EagerLoadBuilder, Builder.Model == From
{
let loader = OptionalChildEagerLoader(relationKey: relationKey)
builder.add(loader: loader)
}
public static func eagerLoad<Loader, Builder>(
_ loader: Loader,
through: KeyPath<From, From.OptionalChild<To>>,
to builder: Builder
) where
Loader: EagerLoader,
Loader.Model == To,
Builder: EagerLoadBuilder,
Builder.Model == From
{
let loader = ThroughChildEagerLoader(relationKey: through, loader: loader)
builder.add(loader: loader)
}
}
private struct OptionalChildEagerLoader<From, To>: EagerLoader
where From: Model, To: Model
{
let relationKey: KeyPath<From, From.OptionalChild<To>>
func run(models: [From], on database: Database) -> EventLoopFuture<Void> {
let ids = models.compactMap { $0.id! }
let builder = To.query(on: database)
let parentKey = From()[keyPath: self.relationKey].parentKey
switch parentKey {
case .optional(let optional):
builder.filter(optional.appending(path: \.$id) ~~ Set(ids))
case .required(let required):
builder.filter(required.appending(path: \.$id) ~~ Set(ids))
}
return builder.all().map {
for model in models {
let id = model[keyPath: self.relationKey].idValue!
let children = $0.filter { child in
switch parentKey {
case .optional(let optional):
return child[keyPath: optional].id == id
case .required(let required):
return child[keyPath: required].id == id
}
}
model[keyPath: self.relationKey].value = children.first
}
}
}
}
private struct ThroughChildEagerLoader<From, Through, Loader>: EagerLoader
where From: Model, Loader: EagerLoader, Loader.Model == Through
{
let relationKey: KeyPath<From, From.OptionalChild<Through>>
let loader: Loader
func run(models: [From], on database: Database) -> EventLoopFuture<Void> {
let throughs = models.compactMap {
$0[keyPath: self.relationKey].value!
}
return self.loader.run(models: throughs, on: database)
}
}
| 28.898678 | 94 | 0.606707 |
1dc2b8d5f333ba827bebb64dd0f16b0a0f4d18c5 | 5,489 | //
// ViewController.swift
// IdentifySample
//
// Copyright © 2559 Globtech. All rights reserved.
//
import UIKit
import NOSTRASDK
import ArcGIS
class IdentifyViewController: UIViewController, AGSMapViewLayerDelegate, AGSMapViewTouchDelegate, AGSLayerDelegate, AGSCalloutDelegate {
@IBOutlet weak var mapView: AGSMapView!
let referrer = ""
let graphicLayer = AGSGraphicsLayer();
var idenResult: NTIdentifyResult?;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initializeMap();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailSegue" {
let detailViewController = segue.destination as! DetailViewController;
detailViewController.idenResult = idenResult;
}
}
func initializeMap() {
mapView.layerDelegate = self;
mapView.touchDelegate = self;
mapView.callout.delegate = self;
do {
// Get map permisson.
let resultSet = try NTMapPermissionService.execute();
// Get Street map HD (service id: 2)
if resultSet.results != nil && resultSet.results.count > 0 {
let filtered = resultSet.results.filter({ (mp) -> Bool in
return mp.serviceId == 2;
})
if filtered.count > 0 {
let mapPermisson = filtered.first;
let url = URL(string: mapPermisson!.serviceUrl_L);
let cred = AGSCredential(token: mapPermisson?.serviceToken_L, referer: referrer);
let tiledLayer = AGSTiledMapServiceLayer(url: url, credential: cred)
tiledLayer?.renderNativeResolution = true;
tiledLayer?.delegate = self;
mapView.addMapLayer(tiledLayer, withName: mapPermisson!.serviceName);
}
}
}
catch let error as NSError {
print("error: \(error)");
}
}
@IBAction func btnCurrentLocation_Clicked(_ btn: UIButton) {
btn.isSelected = !btn.isSelected;
mapView.locationDisplay.autoPanMode = btn.isSelected ? .default : .off;
}
//MARK: Touch Delegate
func mapView(_ mapView: AGSMapView!, didTapAndHoldAt screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [AnyHashable: Any]!) {
if graphicLayer.graphicsCount > 0 {
graphicLayer.removeAllGraphics();
}
let symbol = AGSSimpleMarkerSymbol(color: UIColor.red);
symbol?.style = .X;
symbol?.size = CGSize(width: 15, height: 15);
let graphic = AGSGraphic(geometry: mappoint, symbol: symbol, attributes: nil);
graphicLayer.addGraphic(graphic);
}
//MARK: Callout delegate
func callout(_ callout: AGSCallout!, willShowFor feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
var show = false;
do {
let point = AGSPoint(fromDecimalDegreesString: mapPoint.decimalDegreesString(withNumDigits: 7),
with: AGSSpatialReference.wgs84());
let idenParam = NTIdentifyParameter(lat: (point?.y)!, lon: (point?.x)!);
idenResult = try NTIdentifyService.execute(idenParam);
callout.title = idenResult!.name_L;
callout.detail = "\(idenResult!.adminLevel3_L), \(idenResult!.adminLevel2_L), \(idenResult!.adminLevel1_L)"
if idenResult?.nostraId != nil && idenResult?.nostraId != "" {
callout.accessoryButtonType = .detailDisclosure
callout.isAccessoryButtonHidden = false;
}
else {
callout.isAccessoryButtonHidden = true;
}
show = true;
}
catch let error as NSError {
print("error: \(error.description)")
}
return show;
}
func didClickAccessoryButton(for callout: AGSCallout!) {
self.performSegue(withIdentifier: "detailSegue", sender: nil);
}
//MARK: Map view and Layer delegate
func mapViewDidLoad(_ mapView: AGSMapView!) {
mapView.locationDisplay.startDataSource()
let env = AGSEnvelope(xmin: 10458701.000000, ymin: 542977.875000,
xmax: 11986879.000000, ymax: 2498290.000000,
spatialReference: AGSSpatialReference.webMercator());
mapView.zoom(to: env, animated: true);
mapView.addMapLayer(graphicLayer, withName: "GraphicLyaer");
}
func layerDidLoad(_ layer: AGSLayer!) {
print("\(layer.name) was loaded");
}
func layer(_ layer: AGSLayer!, didFailToLoadWithError error: Error!) {
print("\(layer.name) failed to load by reason: \(error.localizedDescription)");
}
}
| 32.288235 | 136 | 0.562033 |
d50c6a5d470d045944d2c25d90e7e6dbbf8fbc2d | 2,018 | //
// Utils.swift
// Dribbbler
//
// Created by 林達也 on 2017/05/19.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
import RealmSwift
func reference<Confined: ThreadConfined>(_ data: Confined?) -> ThreadSafeReference<Confined>? {
return data.map(ThreadSafeReference.init(to:))
}
extension Int {
var min: TimeInterval {
return TimeInterval(self) * 60
}
}
extension Realm {
func recreate<T: Cache>(_ object: T, of predicateFormat: String, _ args: Any...) {
recreate(object, of: NSPredicate(format: predicateFormat, argumentArray: args))
}
func recreate<T: Cache>(_ object: T, of predicate: NSPredicate) {
delete(objects(T.self).filter(predicate))
add(object)
}
func write<T: Object>(_ block: () -> T) -> T {
beginWrite()
let ret = block()
add(ret)
try! commitWrite() // swiftlint:disable:this force_try
return ret
}
}
extension Date {
var dateWithoutTime: Date {
let timeZone = TimeZone.current
let timeIntervalWithTimeZone = timeIntervalSinceReferenceDate + Double(timeZone.secondsFromGMT())
let timeInterval = floor(timeIntervalWithTimeZone / 86400) * 86400
return Date(timeIntervalSinceReferenceDate: timeInterval)
}
}
extension List {
func distinctAppend<S: Sequence>(contentsOf elements: S) where S.Iterator.Element == T {
var set = OrderedSet(self)
set.append(contentsOf: elements)
append(objectsIn: set.appendings)
}
}
private struct OrderedSet<Element: Hashable> {
private var set: Set<Element> = []
private(set) var appendings: [Element] = []
init<S: Sequence>(_ elements: S) where S.Iterator.Element == Element {
set = Set(elements)
}
mutating func append<S: Sequence>(contentsOf elements: S) where S.Iterator.Element == Element {
for e in elements where !set.contains(e) {
set.insert(e)
appendings.append(e)
}
}
}
| 27.643836 | 105 | 0.647175 |
08309ce4e3c106153ef35238b39c5df1d9f0640c | 4,157 | import SourceKittenFramework
private extension SwiftLintFile {
func missingDocOffsets(in dictionary: SourceKittenDictionary,
acls: [AccessControlLevel]) -> [(ByteCount, AccessControlLevel)] {
if dictionary.enclosedSwiftAttributes.contains(.override) ||
!dictionary.inheritedTypes.isEmpty {
return []
}
let substructureOffsets = dictionary.substructure.flatMap {
missingDocOffsets(in: $0, acls: acls)
}
let extensionKinds: Set<SwiftDeclarationKind> = [.extension, .extensionEnum, .extensionClass,
.extensionStruct, .extensionProtocol]
guard let kind = dictionary.declarationKind,
!extensionKinds.contains(kind),
case let isDeinit = kind == .functionMethodInstance && dictionary.name == "deinit",
!isDeinit,
let offset = dictionary.offset,
let acl = dictionary.accessibility,
acls.contains(acl) else {
return substructureOffsets
}
if dictionary.docLength != nil {
return substructureOffsets
}
return substructureOffsets + [(offset, acl)]
}
}
public struct MissingDocsRule: OptInRule, ConfigurationProviderRule, AutomaticTestableRule {
public init() {
configuration = MissingDocsRuleConfiguration(
parameters: [RuleParameter<AccessControlLevel>(severity: .warning, value: .open),
RuleParameter<AccessControlLevel>(severity: .warning, value: .public)])
}
public typealias ConfigurationType = MissingDocsRuleConfiguration
public var configuration: MissingDocsRuleConfiguration
public static let description = RuleDescription(
identifier: "missing_docs",
name: "Missing Docs",
description: "Declarations should be documented.",
kind: .lint,
minSwiftVersion: .fourDotOne,
nonTriggeringExamples: [
// locally-defined superclass member is documented, but subclass member is not
Example("""
/// docs
public class A {
/// docs
public func b() {}
}
/// docs
public class B: A { override public func b() {} }
"""),
// externally-defined superclass member is documented, but subclass member is not
Example("""
import Foundation
/// docs
public class B: NSObject {
// no docs
override public var description: String { fatalError() } }
"""),
Example("""
/// docs
public class A {
deinit {}
}
"""),
Example("""
public extension A {}
""")
],
triggeringExamples: [
// public, undocumented
Example("public func a() {}\n"),
// public, undocumented
Example("// regular comment\npublic func a() {}\n"),
// public, undocumented
Example("/* regular comment */\npublic func a() {}\n"),
// protocol member and inherited member are both undocumented
Example("""
/// docs
public protocol A {
// no docs
var b: Int { get } }
/// docs
public struct C: A {
public let b: Int
}
""")
]
)
public func validate(file: SwiftLintFile) -> [StyleViolation] {
let acls = configuration.parameters.map { $0.value }
let dict = file.structureDictionary
return file.missingDocOffsets(in: dict, acls: acls).map { offset, acl in
StyleViolation(ruleDescription: Self.description,
severity: configuration.parameters.first { $0.value == acl }?.severity ?? .warning,
location: Location(file: file, byteOffset: offset),
reason: "\(acl.description) declarations should be documented.")
}
}
}
| 38.137615 | 110 | 0.550878 |
67aa0a22692d7e2d79a3e4f0230ba06ffe4e4ca5 | 450 | //
// AppDelegate.swift
// WeatherApp
//
// Created by Renzo Crisostomo on 12/08/14.
// Copyright (c) 2014 Renzo Crisóstomo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
return true
}
}
| 19.565217 | 119 | 0.675556 |
71ae5a839e139104be8af578c4814868693ab255 | 3,169 | import AudioKit
import AudioKitUI
import AVFoundation
import SwiftUI
struct RolandTB303FilterData {
var cutoffFrequency: AUValue = 500
var resonance: AUValue = 0.5
var distortion: AUValue = 2.0
var resonanceAsymmetry: AUValue = 0.5
var rampDuration: AUValue = 0.02
var balance: AUValue = 0.5
}
class RolandTB303FilterConductor: ObservableObject, ProcessesPlayerInput {
let engine = AudioEngine()
let player = AudioPlayer()
let filter: RolandTB303Filter
let dryWetMixer: DryWetMixer
let buffer: AVAudioPCMBuffer
init() {
buffer = Cookbook.sourceBuffer
player.buffer = buffer
player.isLooping = true
filter = RolandTB303Filter(player)
dryWetMixer = DryWetMixer(player, filter)
engine.output = dryWetMixer
}
@Published var data = RolandTB303FilterData() {
didSet {
filter.$cutoffFrequency.ramp(to: data.cutoffFrequency, duration: data.rampDuration)
filter.$resonance.ramp(to: data.resonance, duration: data.rampDuration)
filter.$distortion.ramp(to: data.distortion, duration: data.rampDuration)
filter.$resonanceAsymmetry.ramp(to: data.resonanceAsymmetry, duration: data.rampDuration)
dryWetMixer.balance = data.balance
}
}
func start() {
do { try engine.start() } catch let err { Log(err) }
}
func stop() {
engine.stop()
}
}
struct RolandTB303FilterView: View {
@StateObject var conductor = RolandTB303FilterConductor()
var body: some View {
ScrollView {
PlayerControls(conductor: conductor)
ParameterSlider(text: "Cutoff Frequency",
parameter: self.$conductor.data.cutoffFrequency,
range: 12.0...20_000.0,
units: "Hertz")
ParameterSlider(text: "Resonance",
parameter: self.$conductor.data.resonance,
range: 0.0...2.0,
units: "Generic")
ParameterSlider(text: "Distortion",
parameter: self.$conductor.data.distortion,
range: 0.0...4.0,
units: "Generic")
ParameterSlider(text: "Resonance Asymmetry",
parameter: self.$conductor.data.resonanceAsymmetry,
range: 0.0...1.0,
units: "Percent")
ParameterSlider(text: "Mix",
parameter: self.$conductor.data.balance,
range: 0...1,
units: "%")
DryWetMixView(dry: conductor.player, wet: conductor.filter, mix: conductor.dryWetMixer)
}
.padding()
.navigationBarTitle(Text("Roland Tb303 Filter"))
.onAppear {
self.conductor.start()
}
.onDisappear {
self.conductor.stop()
}
}
}
struct RolandTB303Filter_Previews: PreviewProvider {
static var previews: some View {
RolandTB303FilterView()
}
}
| 33.357895 | 101 | 0.569896 |
f794424ca9264345163feec2bbab025552d046b5 | 11,928 | //
// ADDatePicker.swift
// horizontal-date-picker
//
// Created by SOTSYS027 on 20/04/18.
// Copyright © 2018 SOTSYS027. All rights reserved.
//
import UIKit
public protocol ADDatePickerDelegate {
func ADDatePicker(didChange date: Date)
}
open class ADDatePicker: UIView {
@IBOutlet weak var dateRow: UICollectionView!
@IBOutlet weak var monthRow: UICollectionView!
@IBOutlet weak var yearRow: UICollectionView!
@IBOutlet weak var calendarView: UIView!
@IBOutlet weak var selectionView: UIView!
private var years = ModelDate.getYears()
private let Months = ModelDate.getMonths()
private var currentDay = "31"
private var days:[ModelDate] = []
var infiniteScrollingBehaviourForYears: InfiniteScrollingBehaviour!
var infiniteScrollingBehaviourForDays: InfiniteScrollingBehaviour!
var infiniteScrollingBehaviourForMonths: InfiniteScrollingBehaviour!
// Accessible Properties
public var bgColor: UIColor = #colorLiteral(red: 0.5564764738, green: 0.754239738, blue: 0.6585322022, alpha: 1)
public var selectedBgColor: UIColor = .white
public var selectedTextColor: UIColor = .white
public var deselectedBgColor: UIColor = .clear
public var deselectTextColor: UIColor = UIColor.init(white: 1.0, alpha: 0.7)
public var fontFamily: UIFont = UIFont(name: "GillSans-SemiBold", size: 20)!
public var selectionType: SelectionType = .roundedsquare
public var intialDate:Date = Date()
public var delegate:ADDatePickerDelegate?
public init() {
super.init(frame: .zero)
loadinit()
registerCell()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
days = ModelDate.getDays(years, Months)
if let _ = infiniteScrollingBehaviourForDays {}
else {
let configuration = CollectionViewConfiguration(layoutType: .fixedSize(sizeValue: 60, lineSpacing: 10), scrollingDirection: .horizontal)
infiniteScrollingBehaviourForMonths = InfiniteScrollingBehaviour(withCollectionView: monthRow, andData: Months, delegate: self, configuration: configuration)
infiniteScrollingBehaviourForDays = InfiniteScrollingBehaviour(withCollectionView: dateRow, andData: days, delegate: self, configuration: configuration)
infiniteScrollingBehaviourForYears = InfiniteScrollingBehaviour(withCollectionView: yearRow, andData: years, delegate: self, configuration: configuration)
}
}
private func loadinit(){
let bundle = Bundle(for: self.classForCoder)
bundle.loadNibNamed("ADDatePicker", owner: self, options: nil)
addSubview(calendarView)
calendarView.frame = self.bounds
delay(0.1){
self.selectionView.backgroundColor = self.selectedBgColor
self.selectionView.selectSelectionType(selectionType: self.selectionType)
self.initialDate(date: self.intialDate)
self.calendarView.backgroundColor = self.bgColor
}
}
func initialDate(date: Date){
let (mm,dd,yyyy) = date.seprateDateInDDMMYY
let y = years.index { (modelObj) -> Bool in
return modelObj.type == yyyy
}
let d = days.index { (modelObj) -> Bool in
return Int(modelObj.type) == Int(dd)
}
let m = Int(mm)! - 1
years[y!].isSelected = true
Months[m].isSelected = true
days[d!].isSelected = true
collectionState(infiniteScrollingBehaviourForYears, y!)
collectionState(infiniteScrollingBehaviourForMonths, m)
collectionState(infiniteScrollingBehaviourForDays, d!)
}
private func collectionState(_ collectionView: InfiniteScrollingBehaviour, _ index: Int) {
let indexPathForFirstRow = IndexPath(row: index, section: 0)
switch collectionView.collectionView.tag {
case 0:
self.days[indexPathForFirstRow.row].isSelected = true
infiniteScrollingBehaviourForDays.reload(withData: days)
break
case 1:
self.Months[indexPathForFirstRow.row].isSelected = true
infiniteScrollingBehaviourForMonths.reload(withData: Months)
break
case 2:
self.years[indexPathForFirstRow.row].isSelected = true
infiniteScrollingBehaviourForYears.reload(withData: years)
break
default:
break
}
collectionView.scroll(toElementAtIndex: index)
}
private func registerCell(){
let bundle = Bundle(for: self.classForCoder)
let nibName = UINib(nibName: "ADDatePickerCell", bundle:bundle)
dateRow.register(nibName, forCellWithReuseIdentifier: "cell")
monthRow.register(nibName, forCellWithReuseIdentifier: "cell")
yearRow.register(nibName, forCellWithReuseIdentifier: "cell")
}
}
extension ADDatePicker: UICollectionViewDelegate {
public func didEndScrolling(inInfiniteScrollingBehaviour behaviour: InfiniteScrollingBehaviour) {
selectMiddleRow(collectionView: behaviour.collectionView, data: behaviour.dataSetWithBoundary as! [ModelDate])
switch behaviour.collectionView.tag {
case 0:
behaviour.reload(withData: days)
case 1:
behaviour.reload(withData: Months)
break
case 2:
behaviour.reload(withData: years)
default:
break
}
let date = CalendarHelper.getThatDate(days, Months, years)
delegate?.ADDatePicker(didChange: date)
}
func selectMiddleRow(collectionView: UICollectionView, data: [ModelDate]){
let Row = calculateMedian(array: collectionView.indexPathsForVisibleItems)
let selectedIndexPath = IndexPath(row: Int(Row), section: 0)
for i in 0..<data.count {
if i != selectedIndexPath.row {
data[i].isSelected = false
}
}
if let cell = collectionView.cellForItem(at: selectedIndexPath) as? ADDatePickerCell {
cell.selectedCell(textColor: self.selectedTextColor)
data[Int(Row)].isSelected = true
if collectionView.tag != 0{
compareDays()
}
}
collectionView.scrollToItem(at: selectedIndexPath, at: .centeredHorizontally, animated: true)
}
}
extension ADDatePicker {
private func compareDays(){
let newDays = ModelDate.getDays(years, Months)
if let selectedDay = days.filter({ (modelObject) -> Bool in
return modelObject.isSelected
}).first {
newDays.selectDay(selectedDay: selectedDay)
}
days = newDays
// infiniteScrollingBehaviourForDays.collectionView.reloadSections(IndexSet(integer: 0))
infiniteScrollingBehaviourForDays.reload(withData: days)
if Int(currentDay)! > days.count{
let index = days.count - 1
days[index].isSelected = true
currentDay = "\(days.count)"
}
}
}
extension ADDatePicker : InfiniteScrollingBehaviourDelegate {
public func configuredCell(collectionView: UICollectionView, forItemAtIndexPath indexPath: IndexPath, originalIndex: Int, andData data: InfiniteScollingData, forInfiniteScrollingBehaviour behaviour: InfiniteScrollingBehaviour) -> UICollectionViewCell {
let cell = behaviour.collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ADDatePickerCell
cell.dateLbl.font = fontFamily
switch behaviour.collectionView.tag {
case 0:
if let day = data as? ModelDate {
if day.isSelected {
cell.selectedCell(textColor: selectedTextColor)
}else {
cell.deSelectCell(bgColor: deselectedBgColor, textColor: deselectTextColor)
}
cell.dateLbl.text = day.type
}
case 1:
if let month = data as? ModelDate {
cell.dateLbl.text = month.type
if month.isSelected {
cell.selectedCell(textColor: selectedTextColor)
}else {
cell.deSelectCell(bgColor: deselectedBgColor, textColor: deselectTextColor)
}
}
case 2:
if let year = data as? ModelDate {
cell.dateLbl.text = year.type
if year.isSelected {
cell.selectedCell(textColor: selectedTextColor)
}else {
cell.deSelectCell(bgColor: deselectedBgColor, textColor: deselectTextColor)
}
}
default:
return cell
}
return cell
}
public func didSelectItem(collectionView: UICollectionView,atIndexPath indexPath: IndexPath, originalIndex: Int, andData data: InfiniteScollingData, inInfiniteScrollingBehaviour behaviour: InfiniteScrollingBehaviour) {
if let cell = behaviour.collectionView.cellForItem(at: indexPath) as? ADDatePickerCell {
cell.dateLbl.font = fontFamily
if behaviour.collectionView.tag == 0 {
for i in 0..<days.count {
if i != originalIndex {
currentDay = days[i].type
days[i].isSelected = false
}
}
days[originalIndex].isSelected = true
compareDays()
cell.selectedCell(textColor: selectedTextColor)
} else if behaviour.collectionView.tag == 1 {
for i in 0..<Months.count {
if i != originalIndex {
Months[i].isSelected = false
}
}
Months[originalIndex].isSelected = true
cell.selectedCell(textColor: selectedTextColor)
compareDays()
infiniteScrollingBehaviourForMonths.reload(withData: Months)
} else {
for i in 0..<years.count {
if i != originalIndex {
years[i].isSelected = false
}
}
years[originalIndex].isSelected = true
cell.selectedCell(textColor: selectedTextColor)
compareDays()
infiniteScrollingBehaviourForYears.reload(withData: years)
}
}
let date = CalendarHelper.getThatDate(days, Months, years)
delegate?.ADDatePicker(didChange: date)
behaviour.scroll(toElementAtIndex: originalIndex)
}
}
extension ADDatePicker {
public func yearRange(inBetween start: Int, end: Int) {
years = ModelDate.getYears(startYear: start, endYear: end)
infiniteScrollingBehaviourForYears.reload(withData: years)
//yearRow.reloadData()
}
public func getSelectedDate() -> Date{
let date = CalendarHelper.getThatDate(days, Months, years)
return date
}
}
extension ADDatePicker {
func delay(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
func calculateMedian(array: [IndexPath]) -> Float {
let sorted = array.sorted()
if sorted.count % 2 == 0 {
return Float((sorted[(sorted.count / 2)].row + sorted[(sorted.count / 2) - 1].row)) / 2
} else {
return Float(sorted[(sorted.count - 1) / 2].row)
}
}
}
| 38.353698 | 256 | 0.620221 |
ddd742b9319c199d41fc5beae6b848070619af50 | 7,473 | //
// Fire.swift
// Fire
//
// Created by 虚幻 on 2019/9/15.
// Copyright © 2019 qwertyyb. All rights reserved.
//
import Cocoa
import InputMethodKit
import SQLite3
import Sparkle
import Defaults
let kConnectionName = "Fire_1_Connection"
extension UserDefaults {
@objc dynamic var codeMode: Int {
get {
return integer(forKey: "codeMode")
}
set {
set(newValue, forKey: "codeMode")
}
}
}
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
class Fire: NSObject {
static let candidateSelected = Notification.Name("Fire.candidateSelected")
static let candidateListUpdated = Notification.Name("Fire.candidateListUpdated")
static let nextPageBtnTapped = Notification.Name("Fire.nextPageBtnTapped")
static let prevPageBtnTapped = Notification.Name("Fire.prevPageBtnTapped")
private var database: OpaquePointer?
private var queryStatement: OpaquePointer?
private var preferencesObserver: Defaults.Observation!
let appSettingCache = ApplicationSettingCache()
var inputMode: InputMode = .zhhans
override init() {
super.init()
preferencesObserver = Defaults.observe(keys: .codeMode, .candidateCount) { () in
self.prepareStatement()
}
}
deinit {
preferencesObserver.invalidate()
close()
}
private func getStatementSql() -> String {
let candidateCount = Defaults[.candidateCount]
// 比显示的候选词数量多查一个,以此判断有没有下一页
var sql = """
select
max(wbcode), text, type, min(query) as query
from wb_py_dict
where query like :query
group by text
order by query, id
limit :offset, \(candidateCount + 1)
"""
let codeMode = Defaults[.codeMode]
if codeMode != .wubiPinyin {
sql = """
select
min(code) as wbcode,
text,
'\(codeMode == .wubi ? "wb" : "py")' as type,
min(code) as query
from \(codeMode == .wubi ? "wb_dict" : "py_dict")
where code like :query
group by text
order by query, id
limit :offset, \(candidateCount + 1)
"""
}
print(sql)
return sql
}
func close() {
queryStatement = nil
sqlite3_close_v2(database)
sqlite3_shutdown()
database = nil
}
func prepareStatement() {
sqlite3_open_v2(getDatabaseURL().path, &database, SQLITE_OPEN_READWRITE, nil)
if sqlite3_prepare_v2(database, getStatementSql(), -1, &queryStatement, nil) == SQLITE_OK {
print("prepare ok")
print(sqlite3_bind_parameter_index(queryStatement, ":code"))
print(sqlite3_bind_parameter_count(queryStatement))
} else if let err = sqlite3_errmsg(database) {
print("prepare fail: \(err)")
}
}
private func getQueryFromOrigin(_ origin: String) -> String {
if origin.isEmpty {
return origin
}
if !Defaults[.zKeyQuery] {
return origin
}
// z键查询,z不能放在首位
let first = origin.first!
return String(first) + (String(origin.suffix(origin.count - 1))
.replacingOccurrences(of: "z", with: "_"))
}
var server: IMKServer = IMKServer.init(name: kConnectionName, bundleIdentifier: Bundle.main.bundleIdentifier)
func getCandidates(origin: String = String(), page: Int = 1) -> (candidates: [Candidate], hasNext: Bool) {
if origin.count <= 0 {
return ([], false)
}
let query = getQueryFromOrigin(origin)
NSLog("get local candidate, origin: \(origin), query: ", query)
var candidates: [Candidate] = []
sqlite3_reset(queryStatement)
sqlite3_clear_bindings(queryStatement)
sqlite3_bind_text(queryStatement,
sqlite3_bind_parameter_index(queryStatement, ":code"),
origin, -1,
SQLITE_TRANSIENT
)
sqlite3_bind_text(queryStatement,
sqlite3_bind_parameter_index(queryStatement, ":query"),
"\(query)%", -1,
SQLITE_TRANSIENT
)
sqlite3_bind_int(queryStatement,
sqlite3_bind_parameter_index(queryStatement, ":offset"),
Int32((page - 1) * Defaults[.candidateCount])
)
let strp = sqlite3_expanded_sql(queryStatement)!
print(String(cString: strp))
while sqlite3_step(queryStatement) == SQLITE_ROW {
let code = String.init(cString: sqlite3_column_text(queryStatement, 0))
let text = String.init(cString: sqlite3_column_text(queryStatement, 1))
let type = String.init(cString: sqlite3_column_text(queryStatement, 2))
let candidate = Candidate(code: code, text: text, type: type)
candidates.append(candidate)
}
let count = Defaults[.candidateCount]
let allCount = candidates.count
candidates = Array(candidates.prefix(count))
if candidates.isEmpty {
candidates.append(Candidate(code: origin, text: origin, type: "wb"))
}
return (candidates, hasNext: allCount > count)
}
func setFirstCandidate(wbcode: String, candidate: Candidate) -> Bool {
var sql = """
insert into wb_py_dict(id, wbcode, text, type, query)
values (
(select MIN(id) - 1 from wb_py_dict), :code, :text, :type, :code
);
"""
let codeMode = Defaults[.codeMode]
if codeMode != .wubiPinyin {
sql = """
insert into \(codeMode == .wubi ? "wb_dict" : "py_dict")(id, code, text)
values(
(select MIN(id) - 1 from \(codeMode == .wubi ? "wb_dict" : "py_dict")),
:code,
:text
);
"""
}
var insertStatement: OpaquePointer?
if sqlite3_prepare_v2(database, sql, -1, &insertStatement, nil) == SQLITE_OK {
sqlite3_bind_text(insertStatement,
sqlite3_bind_parameter_index(insertStatement, ":code"),
wbcode, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(insertStatement,
sqlite3_bind_parameter_index(insertStatement, ":text"),
candidate.text, -1, SQLITE_TRANSIENT)
sqlite3_bind_text(insertStatement,
sqlite3_bind_parameter_index(insertStatement, ":type"),
"wb", -1, SQLITE_TRANSIENT)
let strp = sqlite3_expanded_sql(queryStatement)!
print(String(cString: strp))
if sqlite3_step(insertStatement) == SQLITE_DONE {
sqlite3_finalize(insertStatement)
insertStatement = nil
return true
} else {
print("errmsg: \(String(cString: sqlite3_errmsg(database)!))")
return false
}
} else {
print("prepare_errmsg: \(String(cString: sqlite3_errmsg(database)!))")
}
return false
}
static let shared = Fire()
}
| 35.25 | 113 | 0.565904 |
f4b798baa0bdd1aac527e7181ff9d1d953b75dc0 | 1,762 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
Not related to any feature.
*/
public
struct TriggerGlobal: ActionKind
{
/**
This type is not supposed to be instantiated at all.
*/
private
init() { }
}
//===
public
extension ActionContext
{
static
func trigger(
scope: String = #file,
context: String = #function,
body: @escaping (GlobalModel, @escaping SubmitAction) throws -> Void
) -> Action
{
return Action(scope, context, TriggerGlobal.self) { model, submit in
try body(model, submit)
//---
return nil
}
}
}
| 28.419355 | 79 | 0.688422 |
c1a7edc488610f4b69400a7867d6a876a893ea48 | 1,815 | //: Playground - noun: a place where people can play
import UIKit
//Si vas a tener una funcion y esa funcion va a recibir closures las buenas practicas dicen que los closures van al final
//Firma del closure
var miClosure: (Int, Int) -> Int
var miClosure2: (Int, Int) -> Int
miClosure={(a: Int, b:Int) -> Int in
return a + b
}
miClosure2={(a: Int, b:Int) -> Int in
return a * b
}
let resultado = miClosure(3, 2)
func ejecutaOperacion(_ closure:(Int, Int) -> Int, a:Int, b:Int){
let resultado = closure(a, b)
print(resultado)
}
ejecutaOperacion(miClosure, a:10, b:20)
ejecutaOperacion(miClosure2, a:10, b:20)
var numero = 0
func incrementa(variable: inout Int){
variable += 1
}
incrementa(variable: &numero)
let incrementaV2 = {
numero+=1
}
incrementaV2()
incrementaV2()
incrementaV2()
incrementaV2()
func incrementaClosure() -> () -> Int{
var contador = 0
let incrementa: () -> Int = {
contador+=1
return contador
}
return incrementa
}
let contador1 = incrementaClosure()
let contador2 = incrementaClosure()
let letras = ["aaa","aaaaa","aaaaaaa","hiiijd","hiii"]
letras.sorted()
letras.sorted{
$0.count > $1.count
}
print(letras.sorted{
$0.count > $1.count
})
letras.forEach{
print($0)
}
let numeros = [1,2,3,4,5,6,7,8,9]
let filtrados = numeros.filter{
return $0 > 5
}
print("Filtrados: \(filtrados)")
let mapeados = numeros.map{
return $0 * 10
}
print("Mapeados: \(mapeados)")
let letrasYNumeros = ["Hola","2","adios","1","3"]
let numerosUsuario = letrasYNumeros.flatMap{
Int($0)
}
print(numerosUsuario)
let total = numeros.reduce(0){ //Suma todos los elementos del array el numero entre () es la variable inicializadora
return $0 + $1
}
print(total)
//dump para vaciar todo lo que trae una variable
| 18.15 | 121 | 0.66281 |
db30505cbee9d9af0cfdd6be3aee9f7ab0f46845 | 2,660 | import Cocoa
/// Window controller for the Caffeinator preferences window.
class PreferencesWindowController: NSWindowController {
// MARK: - Properties
/// Checkbox corresponding to the start at login preference
@IBOutlet weak var startAtLoginOption: NSButton!
/// Checkbox corresponding to the activate at application launch preference
@IBOutlet weak var activateOnLaunchOption: NSButton!
/// Checkbox corresponding to the show preferences window at application launch preference
@IBOutlet weak var showPreferencesOnLaunchOption: NSButton!
/// Dropdown listing possible default durations for the `caffeinate` task
@IBOutlet weak var defaultDurationOption: NSPopUpButton!
/// The preferences object for interacting with user preferences.
let preferences = Preferences()
// MARK: - Setup
/// Called once the `PreferencesWindowController`'s window has been loaded. Sets up
/// the UI's initial state based on values in NSUserDefaults.
override func windowDidLoad() {
super.windowDidLoad()
startAtLoginOption.state = preferences.shouldStartAtLogin() ? NSOnState : NSOffState
activateOnLaunchOption.state = preferences.shouldActivateOnLaunch() ? NSOnState : NSOffState
showPreferencesOnLaunchOption.state = preferences.shouldShowPreferencesOnLaunch() ? NSOnState : NSOffState
let tag = preferences.defaultDuration()
if !defaultDurationOption.selectItemWithTag(tag) {
defaultDurationOption.selectItemAtIndex(0)
}
}
// MARK: - IBActions
/// IBAction attached to `startAtLoginOption`.
/// - Postcondition: Updates the user preference.
@IBAction func updateStartAtLoginState(sender: NSButton) {
preferences.setStartAtLogin(sender.state == NSOnState)
}
/// IBAction attached to `activateOnLaunchOption`.
/// - Postcondition: Updates the user preference.
@IBAction func updateActivateOnLaunchState(sender: NSButton) {
preferences.setShouldActivateOnLaunch(sender.state == NSOnState)
}
/// IBAction attached to `showPreferencesOnLaunchOption`.
/// - Postcondition: Updates the user preference.
@IBAction func updateShowPreferencesAtLaunchState(sender: NSButton) {
preferences.setShouldShowPreferencesOnLaunch(sender.state == NSOnState)
}
/// IBAction attached to `defaultDurationOption`.
/// - Postcondition: Updates the user preference.
@IBAction func updateDefaultDurationState(sender: NSPopUpButton) {
preferences.setDefaultDuration(sender.selectedTag())
}
}
| 40.30303 | 114 | 0.718421 |
0362b6b135e662458b028b44ea810bc652022277 | 3,129 | //
// ProfileHeader.swift
// FireChat
//
// Created by 윤병일 on 2021/07/19.
//
import UIKit
protocol ProfileHeaderDelegate : AnyObject {
func dismissController()
}
class ProfileHeader : UIView {
//MARK: - Properties
weak var delegate : ProfileHeaderDelegate?
var user : User? {
didSet {
populateUserData()
}
}
private let dismissButton : UIButton = {
let button = UIButton(type: .system)
button.setImage(UIImage(systemName: "xmark"), for: .normal)
button.addTarget(self, action: #selector(handleDismissal), for: .touchUpInside)
button.tintColor = .white
button.imageView?.snp.makeConstraints {
$0.width.height.equalTo(22)
}
return button
}()
private let profileImageView : UIImageView = {
let iv = UIImageView()
iv.clipsToBounds = true
iv.contentMode = .scaleAspectFill
iv.layer.borderColor = UIColor.white.cgColor
iv.layer.borderWidth = 4.0
return iv
}()
private let fullnameLabel : UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 20)
label.textColor = .white
label.textAlignment = .center
label.text = "Eddie Brock"
return label
}()
private let usernameLabel : UILabel = {
let label = UILabel()
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 16)
label.textAlignment = .center
label.text = "@venom"
return label
}()
//MARK: - init
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .systemPink
configureUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Functions
func configureGradientLayer() {
let gradient = CAGradientLayer()
gradient.colors = [UIColor.systemPurple.cgColor, UIColor.systemPink.cgColor]
gradient.locations = [0, 1]
layer.addSublayer(gradient)
gradient.frame = bounds
}
func configureUI() {
configureGradientLayer()
let stack = UIStackView(arrangedSubviews: [fullnameLabel, usernameLabel])
stack.axis = .vertical
stack.spacing = 4
[profileImageView, stack, dismissButton].forEach {
addSubview($0)
}
profileImageView.snp.makeConstraints {
$0.width.height.equalTo(200)
$0.centerX.equalToSuperview()
$0.top.equalToSuperview().offset(96)
}
profileImageView.layer.cornerRadius = 200 / 2
stack.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.top.equalTo(profileImageView.snp.bottom).offset(16)
}
dismissButton.snp.makeConstraints {
$0.top.equalToSuperview().offset(44)
$0.leading.equalToSuperview().offset(12)
$0.width.height.equalTo(48)
}
}
func populateUserData() {
guard let user = user else {return}
fullnameLabel.text = user.fullname
usernameLabel.text = "@" + user.username
guard let url = URL(string: user.profileImageUrl) else {return}
profileImageView.sd_setImage(with: url)
}
//MARK: - @objc func
@objc func handleDismissal() {
delegate?.dismissController()
}
}
| 24.445313 | 83 | 0.658357 |
0a515ddb2311a2bce33cca692644f74c094f1f4d | 1,197 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
extension UIViewController {
@objc open var topMostViewController: UIViewController {
if presentedViewController == nil {
return self
}
if let navigation = presentedViewController as? UINavigationController {
if let visible = navigation.visibleViewController {
return visible.topMostViewController
}
if let top = navigation.topViewController {
return top.topMostViewController
}
return navigation.topMostViewController
}
if let tab = presentedViewController as? UITabBarController {
if let selectedTab = tab.selectedViewController {
return selectedTab.topMostViewController
}
return tab.topMostViewController
}
return presentedViewController!.topMostViewController
}
}
public extension UIApplication {
public var topMostViewController: UIViewController? {
return keyWindow?.rootViewController?.topMostViewController
}
}
| 27.837209 | 80 | 0.593985 |
46d78515becf9e66554b2e5a4a159a4950964d71 | 2,169 | //
// AppDelegate.swift
// PhotoPickerDemo
//
// Created by DangGu on 16/2/25.
// Copyright © 2016年 StormXX. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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:.
}
}
| 46.148936 | 285 | 0.754265 |
1d2473c537fec8e96e4d2b65d1dffe44fa7e7564 | 2,705 | //
// SwiftDocs.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-03.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
#if SWIFT_PACKAGE
import SourceKit
#endif
/// Represents docs for a Swift file.
public struct SwiftDocs {
/// Documented File.
public let file: File
/// Docs information as an [String: SourceKitRepresentable].
public let docsDictionary: [String: SourceKitRepresentable]
/**
Create docs for the specified Swift file and compiler arguments.
- parameter file: Swift file to document.
- parameter arguments: compiler arguments to pass to SourceKit.
*/
public init?(file: File, arguments: [String]) {
do {
self.init(
file: file,
dictionary: try Request.editorOpen(file: file).send(),
cursorInfoRequest: Request.cursorInfoRequest(filePath: file.path, arguments: arguments)
)
} catch let error as Request.Error {
fputs(error.description, stderr)
return nil
} catch {
return nil
}
}
/**
Create docs for the specified Swift file, editor.open SourceKit response and cursor info request.
- parameter file: Swift file to document.
- parameter dictionary: editor.open response from SourceKit.
- parameter cursorInfoRequest: SourceKit dictionary to use to send cursorinfo request.
*/
public init(file: File, dictionary: [String: SourceKitRepresentable], cursorInfoRequest: SourceKitObject?) {
self.file = file
var dictionary = dictionary
let syntaxMapData = dictionary.removeValue(forKey: SwiftDocKey.syntaxMap.rawValue) as! [SourceKitRepresentable]
let syntaxMap = SyntaxMap(data: syntaxMapData)
dictionary = file.process(dictionary: dictionary, cursorInfoRequest: cursorInfoRequest, syntaxMap: syntaxMap)
if let cursorInfoRequest = cursorInfoRequest {
let documentedTokenOffsets = file.stringView.documentedTokenOffsets(syntaxMap: syntaxMap)
dictionary = file.furtherProcess(
dictionary: dictionary,
documentedTokenOffsets: documentedTokenOffsets,
cursorInfoRequest: cursorInfoRequest,
syntaxMap: syntaxMap
)
}
docsDictionary = file.addDocComments(dictionary: dictionary, syntaxMap: syntaxMap)
}
}
// MARK: CustomStringConvertible
extension SwiftDocs: CustomStringConvertible {
/// A textual JSON representation of `SwiftDocs`.
public var description: String {
return toJSON(toNSDictionary([file.path ?? "<No File>": docsDictionary]))
}
}
| 35.592105 | 119 | 0.662847 |
039d7dc57299de414b016d86afd57aeb98bf63f9 | 474 | //
// Copyright © 2017 Nikita Ermolenko. All rights reserved.
// Copyright © 2019 Rosberry. All rights reserved.
//
protocol ConfigurationDelegate: class {
func configuration(_ sender: Configuration, didRequest childConfiguration: Configuration, withTitle title: String?)
}
protocol Configuration: UITableViewDataSource, UITableViewDelegate {
var delegate: ConfigurationDelegate? { get set }
var tableView: UITableView? { get set }
func configure()
}
| 27.882353 | 119 | 0.751055 |
096480f390ea0c584faead497c2252bf24af7bdf | 811 | // Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
func sayHello(name: String) {
print("Hello \(name)")
}
func sayHello2(name: String) ->String {
let retString = "Hello " + name
return retString
}
func test(name: String, greeting: String) ->Void {
print("\(greeting) \(name)")
}
func sayHello3(name: String, greeting: String = "Bonjour") {
print("\(greeting) \(name)")
}
func sayHello4(name: String, name2: String = "Kim", greeting: String = "Bonjour") {
print("\(greeting) \(name) and \(name2)")
}
sayHello(name: "Jon")
var message = sayHello2(name: "Jon")
_ = sayHello2(name:"Jon")
test(name: "Jon", greeting: "Hello")
sayHello3(name: "Jon")
sayHello3(name: "Jon", greeting: "Hello")
sayHello4(name: "Jon", greeting:"Hello")
| 18.860465 | 83 | 0.646116 |
4888ff8822cba7d45638c90ee34de572ef0ce9fe | 4,995 | //
// SwifterMessages.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/**
GET direct_messages/events/show
Returns a single Direct Message event by the given id.
*/
func getDirectMessage(for messageId: String,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "direct_messages/events/show.json"
let parameters = ["id": messageId]
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET direct_messages/events/list
Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order.
*/
func getDirectMessages(count: Int? = nil,
cursor: String? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "direct_messages/events/list.json"
var parameters: [String: Any] = [:]
parameters["count"] ??= count
parameters["cursor"] ??= cursor
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
DELETE direct_messages/events/destroy
Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order.
*/
func destroyDirectMessage(for messageId: String,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "direct_messages/events/destroy.json"
let parameters = ["id": messageId]
self.deleteJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST direct_messages/events/new
Publishes a new message_create event resulting in a Direct Message sent to a specified user from the authenticating user. Returns an event if successful. Supports publishing Direct Messages with optional Quick Reply and media attachment. Replaces behavior currently provided by POST direct_messages/new.
Requires a JSON POST body and Content-Type header to be set to application/json. Setting Content-Length may also be required if it is not automatically.
# Direct Message Rate Limiting
When a message is received from a user you may send up to 5 messages in response within a 24 hour window. Each message received resets the 24 hour window and the 5 allotted messages. Sending a 6th message within a 24 hour window or sending a message outside of a 24 hour window will count towards rate-limiting. This behavior only applies when using the POST direct_messages/events/new endpoint.
*/
func postDirectMessage(to recipientUserId: String,
message: String,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "direct_messages/events/new.json"
var parameters: [String: Any] = [:]
parameters[Swifter.DataParameters.jsonDataKey] = "json-body"
parameters["json-body"] = [
"event": [
"type": "message_create",
"message_create": [
"target": [ "recipient_id": recipientUserId ],
"message_data": ["text": message ]
]
]
]
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
}
| 44.20354 | 400 | 0.636436 |
2182151c9f17254b10160fc9fa729b7092b583c6 | 1,295 | #if canImport(CoreGraphics)
import CoreGraphics
extension CGRect {
// MARK: - Instance Properties
public var adjusted: CGRect {
return CGRect(
x: minX.rounded(.down),
y: minY.rounded(.down),
width: abs(width.rounded(.awayFromZero)),
height: abs(height.rounded(.awayFromZero))
)
}
// MARK: - Initializers
public init(x: CGFloat, y: CGFloat, size: CGSize) {
self.init(x: x, y: y, width: size.width, height: size.height)
}
public init(x: Double, y: Double, size: CGSize) {
self.init(x: CGFloat(x), y: CGFloat(y), width: size.width, height: size.height)
}
public init(x: Int, y: Int, size: CGSize) {
self.init(x: CGFloat(x), y: CGFloat(y), width: size.width, height: size.height)
}
public init(origin: CGPoint, width: CGFloat, height: CGFloat) {
self.init(x: origin.x, y: origin.y, width: width, height: height)
}
public init(origin: CGPoint, width: Double, height: Double) {
self.init(x: origin.x, y: origin.y, width: CGFloat(width), height: CGFloat(height))
}
public init(origin: CGPoint, width: Int, height: Int) {
self.init(x: origin.x, y: origin.y, width: CGFloat(width), height: CGFloat(height))
}
}
#endif
| 29.431818 | 91 | 0.605405 |
e58a7eb69e9e50189b8932a54d5bd64fcaa31569 | 2,812 | //
// File.swift
//
//
// Created by Fernando Moya de Rivas on 14/1/21.
//
import XCTest
@testable import SwiftUIPager
final class Page_Tests: XCTestCase {
func test_WhenFirst_ThenIndexZero() {
let page: Page = .first()
XCTAssertEqual(page.index, 0)
}
func test_WhenWithIndex_ThenSelectedIndex() {
let page: Page = .withIndex(3)
XCTAssertEqual(page.index, 3)
}
func test_GivenPage_WhenNegativeIndex_ThenZero() {
let page: Page = .first()
page.totalPages = 10
page.index = -4
XCTAssertEqual(page.index, 0)
}
func test_GivenPage_WhenIndexTooBig_ThenLastIndex() {
let page: Page = .first()
page.totalPages = 10
page.index = 10
XCTAssertEqual(page.index, 9)
}
func test_GivenPage_WhenUpdateNext_ThenNextIndex() {
let page: Page = .first()
page.totalPages = 10
page.update(.next)
XCTAssertEqual(page.index, 1)
}
func test_GivenPage_WhenUpdatePrevious_ThenPreviousIndex() {
let page: Page = .withIndex(1)
page.totalPages = 10
page.update(.previous)
XCTAssertEqual(page.index, 0)
}
func test_GivenPage_WhenUpdateMoveToFirst_ThenIndexZero() {
let page: Page = .withIndex(4)
page.totalPages = 10
page.update(.moveToFirst)
XCTAssertEqual(page.index, 0)
}
func test_GivenPage_WhenUpdateMoveToLast_ThenLastIndex() {
let page: Page = .withIndex(4)
page.totalPages = 10
page.update(.moveToLast)
XCTAssertEqual(page.index, 9)
}
func test_GivenPage_WhenUpdateNewIndex_ThenSelectedIndex() {
let page: Page = .withIndex(4)
page.totalPages = 10
page.update(.new(index: 1))
XCTAssertEqual(page.index, 1)
}
static var allTests = [
("test_WhenFirst_ThenIndexZero", test_WhenFirst_ThenIndexZero),
("test_WhenWithIndex_ThenSelectedIndex", test_WhenWithIndex_ThenSelectedIndex),
("test_GivenPage_WhenNegativeIndex_ThenZero", test_GivenPage_WhenNegativeIndex_ThenZero),
("test_GivenPage_WhenIndexTooBig_ThenLastIndex", test_GivenPage_WhenIndexTooBig_ThenLastIndex),
("test_GivenPage_WhenUpdateNext_ThenNextIndex", test_GivenPage_WhenUpdateNext_ThenNextIndex),
("test_GivenPage_WhenUpdatePrevious_ThenPreviousIndex", test_GivenPage_WhenUpdatePrevious_ThenPreviousIndex),
("test_GivenPage_WhenUpdateMoveToFirst_ThenIndexZero", test_GivenPage_WhenUpdateMoveToFirst_ThenIndexZero),
("test_GivenPage_WhenUpdateMoveToLast_ThenLastIndex", test_GivenPage_WhenUpdateMoveToLast_ThenLastIndex),
("test_GivenPage_WhenUpdateNewIndex_ThenSelectedIndex", test_GivenPage_WhenUpdateNewIndex_ThenSelectedIndex)
]
}
| 30.565217 | 117 | 0.694879 |
76f887d9fc28b0f019f2ae18f54f7f678fb34083 | 3,204 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t %S/Inputs/def_transparent_std.swift
// RUN: llvm-bcanalyzer %t/def_transparent_std.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-sil -sil-debug-serialization -parse-stdlib -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: UnknownCode
import def_transparent_std
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std3foo1x1yBi1_Bi1__Bi1_tF : $@convention(thin) (Builtin.Int1, Builtin.Int1) -> Builtin.Int1 {
// SIL: = builtin "cmp_eq_Int1"(%0 : $Builtin.Int1, %1 : $Builtin.Int1) : $Builtin.Int1
func test_foo(x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 {
var a = foo(x: x, y: y)
return a
}
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std12assign_tuple1x1yyBi64__Bot_BptF : $@convention(thin) (Builtin.Int64, @owned Builtin.NativeObject, Builtin.RawPointer) -> () {
// SIL: = tuple (%0 : $Builtin.Int64, %1 : $Builtin.NativeObject)
// SIL: retain_value
// SIL: = tuple_extract
// SIL: = tuple_extract
// SIL: = pointer_to_address
// SIL: = tuple
// SIL: = load
func test_tuple(x: (Builtin.Int64, Builtin.NativeObject),
y: Builtin.RawPointer) {
assign_tuple(x: x, y: y)
}
func test_conversion(c: C, t32: Builtin.Int32) {
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std22class_to_native_object1cBoAA1CC_tF : $@convention(thin) (@owned C) -> @owned Builtin.NativeObject {
// SIL: bb0(%0 : $C):
// SIL: unchecked_ref_cast %0 : $C to $Builtin.NativeObject
// SIL-NEXT: return
var b = class_to_native_object(c: c)
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std24class_from_native_object1pAA1CCBo_tF : $@convention(thin) (@owned Builtin.NativeObject) -> @owned C {
// SIL: unchecked_ref_cast %0 : $Builtin.NativeObject to $C
var c = class_from_native_object(p: b)
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std20class_to_raw_pointer1cBpAA1CC_tF : $@convention(thin) (@owned C) -> Builtin.RawPointer {
// SIL: ref_to_raw_pointer %0 : $C to $Builtin.RawPointer
var d = class_to_raw_pointer(c: c)
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std22class_from_raw_pointer1pAA1CCBp_tF : $@convention(thin) (Builtin.RawPointer) -> @owned C {
// SIL: raw_pointer_to_ref %0 : $Builtin.RawPointer to $C
var e = class_from_raw_pointer(p: d)
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std5gep321p1iBpBp_Bi32_tF : $@convention(thin) (Builtin.RawPointer, Builtin.Int32) -> Builtin.RawPointer {
// SIL: index_raw_pointer %0 : $Builtin.RawPointer, %1 : $Builtin.Int32
var f = gep32(p: d, i: t32)
// SIL-LABEL: sil public_external [transparent] [serialized] [canonical] @$S19def_transparent_std11destroy_obj1xyBp_tF : $@convention(thin) (Builtin.RawPointer) -> () {
// SIL: pointer_to_address %0 : $Builtin.RawPointer to [strict] $*Builtin.NativeObject
destroy_obj(x: d)
}
| 56.210526 | 224 | 0.73814 |
d54d1cc9bc0dc1e07bf210fd6600c549ebb7c09c | 2,188 | //
// UploadFile.swift
// Chat
//
// Created by Mahyar Zhiani on 8/5/1397 AP.
// Copyright © 1397 Mahyar Zhiani. All rights reserved.
//
import Foundation
import SwiftyJSON
open class FileObject {
public var hashCode: String
// public var id: Int
public var name: String?
public var size: Int?
public var type: String?
@available(*,deprecated , message:"Removed in 0.10.5.0 version")
public init(messageContent: JSON) {
self.hashCode = messageContent["hashCode"].stringValue
// self.id = messageContent["id"].intValue
self.name = messageContent["name"].string
self.size = messageContent["size"].int
self.type = messageContent["type"].string
}
public init(hashCode: String,
// id: Int,
name: String?,
size: Int?,
type: String?) {
self.hashCode = hashCode
// self.id = id
self.name = name
self.size = size
self.type = type
}
@available(*,deprecated , message:"Removed in 0.10.5.0 version")
public init(theUploadFile: FileObject) {
self.hashCode = theUploadFile.hashCode
// self.id = theUploadFile.id
self.name = theUploadFile.name
self.size = theUploadFile.size
self.type = theUploadFile.type
}
@available(*,deprecated , message:"Removed in 0.10.5.0 version")
public func formatDataToMakeUploadImage() -> FileObject {
return self
}
@available(*,deprecated , message:"Removed in 0.10.5.0 version")
public func formatToJSON() -> JSON {
let result: JSON = ["hashCode": hashCode,
// "id": id,
"name": name ?? NSNull(),
"size": size ?? NSNull(),
"type": type ?? NSNull()]
return result
}
}
| 31.257143 | 68 | 0.489031 |
f89d0a68cfe49d21e8b88112e7115e876fdcc9ef | 151 | //
// SectionTests.swift
// Listable-Unit-Tests
//
// Created by Kyle Van Essen on 11/27/19.
//
import XCTest
class SectionTests: XCTestCase
{
}
| 10.785714 | 42 | 0.675497 |
fca8f9aec6e7649d5ecbe3adc67b2d230e1f74b8 | 1,635 | import UIKit
extension UIStackView {
static func make(
_ axis: NSLayoutConstraint.Axis,
spacing: CGFloat = 0,
distribution: UIStackView.Distribution = .fill,
alignment: UIStackView.Alignment = .fill
) -> (UIView...) -> UIStackView {
return { (views: UIView...) -> UIStackView in
createStackView(
axis,
spacing: spacing,
distribution: distribution,
alignment: alignment,
subviews: views
)
}
}
static func make(
_ axis: NSLayoutConstraint.Axis,
spacing: CGFloat = 0,
distribution: UIStackView.Distribution = .fill,
alignment: UIStackView.Alignment = .fill
) -> ([UIView]) -> UIStackView {
return { (views: [UIView]) -> UIStackView in
createStackView(
axis,
spacing: spacing,
distribution: distribution,
alignment: alignment,
subviews: views
)
}
}
private static func createStackView(
_ axis: NSLayoutConstraint.Axis,
spacing: CGFloat = 0,
distribution: UIStackView.Distribution = .fill,
alignment: UIStackView.Alignment = .fill,
subviews: [UIView]
) -> UIStackView {
let stack = UIStackView(arrangedSubviews: subviews)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = axis
stack.spacing = spacing
stack.distribution = distribution
stack.alignment = alignment
return stack
}
}
| 29.196429 | 63 | 0.560856 |
9bf2dec555c3a68cf86e3789dc0519bffc1afbb9 | 10,593 | //
// ElevationScene.swift
// FogViewshed
//
import Foundation
import SceneKit
import MapKit
class ElevationScene: SCNNode {
// MARK: Variables
var elevation:[[Int]]
var vertexSource:SCNGeometrySource
var maxScaledElevation:Float
var image:UIImage?
let cellSize:Float = 1.0
// MARK: Initializer
init(elevation: [[Int]], viewshedImage: UIImage?) {
self.elevation = elevation
self.vertexSource = SCNGeometrySource()
self.maxScaledElevation = 1.0
self.image = viewshedImage
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Process Functions
func generateScene() {
self.addChildNode(SCNNode(geometry: createGeometry()))
}
func drawVertices() {
self.addChildNode(generateLineNode(vertexSource, vertexCount: vertexSource.vectorCount))
}
func addObserver(location: (Int, Int), altitude: Double) {
self.addChildNode(generateObserverNode(location, altitude: altitude))
}
func addCamera() {
self.addChildNode(generateCameraNode())
}
// MARK: Private Functions
private func createGeometry() -> SCNGeometry {
let geometry:SCNGeometry = calculateGeometry()
addImageToGeometry(geometry)
return geometry
}
private func calculateGeometry() -> SCNGeometry {
let maxRows = elevation.count
let maxColumns = elevation[0].count
var vertices:[SCNVector3] = []
var textures:[(x:Float, y:Float)] = []
for row in 0..<(maxRows - 1) {
for column in 0..<(maxColumns - 1) {
let topLeftZ = getElevationAtLocation(row, column: column)
let topRightZ = getElevationAtLocation(row, column: column + 1)
let bottomLeftZ = getElevationAtLocation(row + 1, column: column)
let bottomRightZ = getElevationAtLocation(row + 1, column: column + 1)
let coordX = Float(column)
let coordY = Float(row)
let topLeft = SCNVector3Make(Float(coordX),
Float(-coordY),
Float(topLeftZ))
let topRight = SCNVector3Make(Float(coordX) + cellSize,
Float(-coordY),
Float(topRightZ))
let bottomLeft = SCNVector3Make(Float(coordX),
Float(-coordY) - cellSize,
Float(bottomLeftZ))
let bottomRight = SCNVector3Make(Float(coordX) + cellSize,
Float(-coordY) - cellSize,
Float(bottomRightZ))
vertices.append(topLeft)
vertices.append(topRight)
vertices.append(bottomRight)
vertices.append(bottomLeft)
let columnScale = Float(maxColumns) - 1
let rowScale = Float(maxRows) - 1
let topLeftTexture = (x:Float(coordX / columnScale), y:Float(coordY / rowScale))
let bottomLeftTexture = (x:Float((coordX + 1) / columnScale), y:Float(coordY / rowScale))
let topRightTexture = (x:Float(coordX / columnScale), y:Float((coordY + 1) / rowScale))
let bottomRightTexture = (x:Float((coordX + 1) / columnScale), y:Float((coordY + 1) / rowScale))
textures.append(topLeftTexture)
textures.append(bottomLeftTexture)
textures.append(bottomRightTexture)
textures.append(topRightTexture)
}
}
var geometrySources:[SCNGeometrySource] = []
//Add vertex
vertexSource = SCNGeometrySource(vertices: vertices, count: vertices.count)
geometrySources.append(vertexSource)
//Add normal
let normal = SCNVector3(0, 0, 1)
var normals:[SCNVector3] = []
for _ in 0..<vertexSource.vectorCount {
normals.append(normal)
}
let normalSource:SCNGeometrySource = SCNGeometrySource(vertices: normals, count: normals.count)
geometrySources.append(normalSource)
//Add textures
let textureData = NSData(bytes: textures, length: (sizeof((x:Float, y:Float)) * textures.count))
let textureSource = SCNGeometrySource(data: textureData,
semantic: SCNGeometrySourceSemanticTexcoord,
vectorCount: textures.count,
floatComponents: true,
componentsPerVector: 2,
bytesPerComponent: sizeof(Float),
dataOffset: 0,
dataStride: sizeof((x:Float, y:Float)))
geometrySources.append(textureSource)
//Create Indices
var geometryData:[CInt] = []
var geometryCount: CInt = 0
while (geometryCount < CInt(vertexSource.vectorCount)) {
geometryData.append(geometryCount)
geometryData.append(geometryCount + 2)
geometryData.append(geometryCount + 1)
geometryData.append(geometryCount)
geometryData.append(geometryCount + 3)
geometryData.append(geometryCount + 2)
geometryCount += 4
}
let element:SCNGeometryElement = SCNGeometryElement(indices: geometryData, primitiveType: .Triangles)
//Create SCNGeometry
let geometry:SCNGeometry = SCNGeometry(sources: geometrySources, elements: [element])
return geometry
}
private func addImageToGeometry(geometry: SCNGeometry) -> SCNGeometry {
let imageMaterial = SCNMaterial()
if let viewshedImage = self.image {
imageMaterial.diffuse.contents = viewshedImage
} else {
imageMaterial.diffuse.contents = UIColor.darkGrayColor()
}
imageMaterial.doubleSided = true
geometry.materials = [imageMaterial]
return geometry
}
private func generateObserverNode(location: (Int, Int), altitude: Double) -> SCNNode {
let observerCapsule = SCNCapsule(capRadius: 0.125, height: 0.5)
let capsuleSizeFactor:Float = 0.25
let observerNode = SCNNode(geometry: observerCapsule)
let row: Int = location.1
let column: Int = location.0
let observerY:Float = -Float(row)
let observerX:Float = Float(column)
let boundedElevation:Float = getElevationAtLocation(row - 1, column: column - 1, additionalAltitude: Float(altitude))
let observerZ: Float = Float(boundedElevation) + capsuleSizeFactor
observerNode.position = SCNVector3Make(observerX, observerY, observerZ)
observerNode.eulerAngles = SCNVector3Make(Float(M_PI_2), 0, 0)
return observerNode
}
private func generateLineNode(vertexSource: SCNGeometrySource, vertexCount: Int) -> SCNNode {
var lineData:[CInt] = []
var lineCount: CInt = 0
while (lineCount < CInt(vertexCount)) {
lineData.append(lineCount)
lineData.append(lineCount + 1)
lineData.append(lineCount + 1)
lineData.append(lineCount + 2)
lineData.append(lineCount + 2)
lineData.append(lineCount + 3)
lineData.append(lineCount + 3)
lineData.append(lineCount)
lineData.append(lineCount + 0)
lineData.append(lineCount + 2)
lineCount = lineCount + 4
}
let lineEle = SCNGeometryElement(indices: lineData, primitiveType: .Line)
let lineGeo = SCNGeometry(sources: [vertexSource], elements: [lineEle])
let whiteMaterial = SCNMaterial()
if self.image != nil {
whiteMaterial.diffuse.contents = UIColor.darkGrayColor()
} else {
whiteMaterial.diffuse.contents = UIColor.whiteColor()
}
lineGeo.materials = [whiteMaterial]
return SCNNode(geometry: lineGeo)
}
private func generateCameraNode() -> SCNNode {
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
// Add an additional 20 cellSize units to set the camera above the scene
let cameraFactor:Float = self.cellSize * 20
let cameraZ = maxScaledElevation + cameraFactor
let cameraX:Float = Float(elevation[0].count / 2)
let cameraY:Float = -Float(elevation.count / 2)
cameraNode.position = SCNVector3Make(cameraX, cameraY, cameraZ)
return cameraNode
}
private func getElevationAtLocation(row: Int, column: Int, additionalAltitude:Float = 0.0) -> Float {
let maxRows:Int = elevation.count - 1
let actualRow:Int = maxRows - row
let elevationValue: Float = boundElevation(elevation[actualRow][column])
return elevationValue
}
// Bound elevation to remove data voids and unknown values
private func boundElevation(unboundElevation:Int, altitude:Float = 0.0) -> Float {
var boundedElevation:Float = Float(unboundElevation)
// Remove data voids and invalid elevations
if (unboundElevation < Elevation.MIN_BOUND) {
boundedElevation = Float(Elevation.MIN_BOUND)
} else if (unboundElevation > Elevation.MAX_BOUND) {
boundedElevation = Float(Elevation.MAX_BOUND)
}
// Scale elevation by 99.7% to render in the Scene
let scaleFactor:Float = 0.997
let elevationRange:Float = Float(Elevation.MAX_BOUND - Elevation.MIN_BOUND)
let sizeFactor:Float = elevationRange - elevationRange * scaleFactor
boundedElevation = (boundedElevation + altitude) / sizeFactor
//While checking each elevation, record the maxScaledElevation
if (maxScaledElevation < boundedElevation) {
maxScaledElevation = boundedElevation
}
return boundedElevation
}
} | 39.526119 | 125 | 0.578778 |
22ecf0b73e6ed683999f91962ff285cce4caf232 | 553 | //
// FlowCollector.swift
// CryptoCurrenciesApp
//
// Created by Алексей Рамашка on 12.04.21.
//
import Foundation
import CryptoCurrencySDK
class FlowCollector<T>: Kotlinx_coroutines_coreFlowCollector {
let callback:(T) -> Void
init(callback: @escaping (T) -> Void) {
self.callback = callback
}
func emit(value: Any?, completionHandler: @escaping (KotlinUnit?, Error?) -> Void) {
callback(value as! T)
completionHandler(KotlinUnit(), nil)
}
}
extension Kotlinx_coroutines_coreFlowCollector {
}
| 19.068966 | 88 | 0.676311 |
72ebcbda3ccdfe2508ec27f28c2296be8d8f8706 | 1,502 | //
// GestureViewController.swift
// GestureRecognizerExample
//
// Copyright © 2020 Giftbot. All rights reserved.
//
import UIKit
final class GestureViewController: UIViewController {
@IBOutlet private weak var imageView: UIImageView! {
didSet {
imageView.layer.cornerRadius = imageView.frame.width / 2
imageView.clipsToBounds = true
}
}
var tapped = false
@IBAction private func handleTapGesture(_ sender: UITapGestureRecognizer) {
guard sender.state == .ended else { return }
if tapped {
tapped = false
imageView.transform = .identity
}
else {
tapped = true
imageView.transform = imageView.transform.scaledBy(x: 2, y: 2)
}
}
@IBAction private func handleRoationGesture(_ sender: UIRotationGestureRecognizer) {
guard sender.state == .began || sender.state == .changed else { return }
imageView.transform = imageView.transform.rotated(by: sender.rotation)
sender.rotation = 0
}
@IBAction private func handleSwipeGesture(_ sender: UISwipeGestureRecognizer) {
guard sender.state == .ended else { return }
if sender.direction == .right {
print("right")
imageView.image = UIImage(named: "cat1")
}
else if sender.direction == .left {
print("left")
imageView.image = UIImage(named: "cat2")
}
}
}
| 28.884615 | 88 | 0.600533 |
de3c91ce7c6282778ebc2bfa3070b3cbb643ef93 | 3,776 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// ObjectProperties.swift
// Tracker
//
import Foundation
public class ECommerceCart: RequiredPropertiesDataObject {
@objc var version : String = ""
override init() {
super.init()
let id = Foundation.UUID().uuidString
self.version = String(id[..<id.index(id.startIndex, offsetBy: 8)])
propertiesPrefixMap["version"] = "s"
propertiesPrefixMap["id"] = "s"
propertiesPrefixMap["currency"] = "s"
propertiesPrefixMap["creation_utc"] = "d"
propertiesPrefixMap["turnovertaxincluded"] = "f"
propertiesPrefixMap["turnovertaxfree"] = "f"
propertiesPrefixMap["quantity"] = "n"
propertiesPrefixMap["nbdistinctproduct"] = "n"
}
}
public class ECommercePayment: RequiredPropertiesDataObject {
override init() {
super.init()
propertiesPrefixMap["mode"] = "s"
}
}
public class ECommerceProduct: RequiredPropertiesDataObject {
override init() {
super.init()
propertiesPrefixMap["id"] = "s"
propertiesPrefixMap["$"] = "s"
propertiesPrefixMap["brand"] = "s"
propertiesPrefixMap["currency"] = "s"
propertiesPrefixMap["variant"] = "s"
propertiesPrefixMap["category1"] = "s"
propertiesPrefixMap["category2"] = "s"
propertiesPrefixMap["category3"] = "s"
propertiesPrefixMap["category4"] = "s"
propertiesPrefixMap["category5"] = "s"
propertiesPrefixMap["category6"] = "s"
propertiesPrefixMap["discount"] = "b"
propertiesPrefixMap["stock"] = "b"
propertiesPrefixMap["cartcreation"] = "b"
propertiesPrefixMap["pricetaxincluded"] = "f"
propertiesPrefixMap["pricetaxfree"] = "f"
propertiesPrefixMap["quantity"] = "n"
}
@objc public convenience init(obj: [String : Any]) {
self.init()
for (k,v) in obj {
_ = self.set(key: k, value: v)
}
}
}
public class ECommerceShipping: RequiredPropertiesDataObject {
override init() {
super.init()
propertiesPrefixMap["delivery"] = "s"
propertiesPrefixMap["costtaxincluded"] = "f"
propertiesPrefixMap["costtaxfree"] = "f"
}
}
public class ECommerceTransaction: RequiredPropertiesDataObject {
override init() {
super.init()
propertiesPrefixMap["id"] = "s"
propertiesPrefixMap["promocode"] = "a:s"
propertiesPrefixMap["firstpurchase"] = "b"
}
}
| 34.962963 | 142 | 0.662076 |
5dccaffa978d1338fc0cf6228f8028776ddef032 | 3,992 | //
// RatingView.swift
// Movie DB
//
// Created by Jonas Frey on 23.11.19.
// Copyright © 2019 Jonas Frey. All rights reserved.
//
import SwiftUI
/// Provides a view that displays an editable star rating
struct RatingView: View {
@Binding var rating: StarRating
@Environment(\.editMode) private var editMode
var body: some View {
// Valid ratings are 0 to 10 stars (0 to 5 stars)
HStack {
self.stars(rating)
.padding(.vertical, 5)
.foregroundColor(Color.yellow)
if editMode?.wrappedValue.isEditing ?? false {
Stepper("", value: $rating, in: StarRating.noRating...StarRating.fiveStars)
}
}
}
private func stars(_ rating: StarRating) -> some View {
return HStack {
ForEach(Array(0..<(rating.integerRepresentation / 2)), id: \.self) { _ in
Image(systemName: "star.fill")
}
if rating.integerRepresentation % 2 == 1 {
Image(systemName: "star.lefthalf.fill")
}
// Only if there is at least one empty star
if rating.integerRepresentation < StarRating.fourAndAHalfStars.integerRepresentation {
ForEach(Array(0..<(10 - rating.integerRepresentation) / 2), id: \.self) { _ in
Image(systemName: "star")
}
}
}
}
}
struct RatingView_Previews: PreviewProvider {
static var previews: some View {
Group {
RatingView(rating: .constant(.noRating))
}
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("No Rating")
Group {
RatingView(rating: .constant(.halfStar))
}
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Half Star")
Group {
RatingView(rating: .constant(.oneStar))
}
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("One Star")
Group {
RatingView(rating: .constant(.twoAndAHalfStars))
}
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Two and a Half Stars")
Group {
RatingView(rating: .constant(.fourAndAHalfStars))
}
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Four and a Half Stars")
Group {
RatingView(rating: .constant(.fiveStars))
}
.previewLayout(.sizeThatFits)
.padding()
.previewDisplayName("Five Stars")
}
}
public enum StarRating: Int, Strideable, Codable {
public typealias Stride = Int
case noRating = 0
case halfStar
case oneStar
case oneAndAHalfStars
case twoStars
case twoAndAHalfStars
case threeStars
case threeAndAHalfStars
case fourStars
case fourAndAHalfStars
case fiveStars
init?(integerRepresentation: Int) {
guard let rating = StarRating(rawValue: integerRepresentation) else {
return nil
}
self = rating
}
/// The integer value of the rating (amount of half stars)
var integerRepresentation: Int {
return rawValue
}
/// The amount of full stars as a string with an optional fraction digit
var starAmount: String {
let formatter = NumberFormatter()
// Set the locale to the correct fraction symbol
formatter.locale = Locale.current
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 1
return formatter.string(from: Double(integerRepresentation) / 2)!
}
public func advanced(by n: Int) -> StarRating {
return StarRating(rawValue: self.rawValue + n)!
}
public func distance(to other: StarRating) -> Int {
return other.rawValue - self.rawValue
}
}
| 28.514286 | 98 | 0.58016 |
089412714ef33d12464165128c1bff7a75e6c474 | 6,227 | //
// TrackingLocation.swift
// SafeNights
//
// Created by Owen Khoury on 8/23/17.
// Copyright © 2017 SafeNights. All rights reserved.
//
import MapKit
import GoogleMaps
import CoreLocation
class TrackingLocation: UIViewController {
let API = MyAPI()
let preferences = UserDefaults.standard
let locationChecker = LocationSafetyChecker()
//let locManager = CLLocationManager()
//var coordinateTimer: Timer!
let TIME_INTERVAL:TimeInterval = 15.0*60 // in secs
var latLocations = Array(repeating: 0.0, count: 4)
var longLocations = Array(repeating: 0.0, count: 4)
public lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.pausesLocationUpdatesAutomatically = false
manager.allowsBackgroundLocationUpdates = true
manager.delegate = self as CLLocationManagerDelegate
manager.requestAlwaysAuthorization()
return manager
}()
var lastTime = Date()
// Function get user's current latitude and longitude
@objc func setCoordinates() {
locationManager.requestWhenInUseAuthorization()
var currentLocation = CLLocation()
if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {
currentLocation = locationManager.location ?? CLLocation()
// Set the global values for lat and lon
let latitude = currentLocation.coordinate.latitude
let longitude = currentLocation.coordinate.longitude
getAddress(lat: latitude, lon: longitude) { (returnAddress) in
_ = self.preferences.set("\(returnAddress)", forKey: "currentAddress")
}
// Store the
latLocations[3] = latLocations[2]
latLocations[2] = latLocations[1]
latLocations[1] = latLocations[0]
latLocations[0] = latitude
// Store the 4 most recent longitudes
longLocations[3] = longLocations[2]
longLocations[2] = longLocations[1]
longLocations[1] = longLocations[0]
longLocations[0] = longitude
// print("Latitudes:")
// print(latLocations)
//
// print("Longitudes")
// print(longLocations)
_ = self.preferences.set(latLocations, forKey: "latLocations")
_ = self.preferences.set(longLocations, forKey: "longLocations")
// Send these coordinates to the database
let resource = API.addLoc
var postData = Dictionary<String, String>()
let username = self.preferences.string(forKey: "username")!
let password = self.preferences.string(forKey: "password")!
let adventureID = self.preferences.string(forKey: "adventureID")!
postData = ["username": username, "pwd": password,
"id": adventureID, "xcord": String(latitude),
"ycord": String(longitude)]
//print(postData)
resource.request(.post, urlEncoded: postData ).onSuccess() { data in
// This code gets the response from the user in the form ["passed": 'y'/'n']
var response = data.jsonDict
let loginAnswer = response["passed"]
// If the response is a yes, allow access to the next page, otherwise deny access and give message to user
if let loginAnswer = loginAnswer as? String, loginAnswer == "y" {
//print("succesfully added location")
}
else if let loginAnswer = loginAnswer as? String, loginAnswer == "n" {
//print("Did not add location")
}
else {
//print(data.jsonDict)
}
}.onFailure{_ in
//print("failed")
}
}
}
// Background task to continually get latitude and longitude every 5 seconds
func performBackgroundTask() {
self.setCoordinates()
// Set up timing
lastTime = Date()
lastTime = Date(timeInterval: TIME_INTERVAL, since: lastTime)
locationManager.startUpdatingLocation()
}
// Stop collecting locations and checking for safety
func stopBackgroundTask() {
locationManager.stopUpdatingLocation()
}
func getAddress(lat: Double, lon: Double, currentAdd : @escaping ( _ returnAddress :String)->Void){
let geocoder = GMSGeocoder()
let coordinate = CLLocationCoordinate2DMake(lat, lon)
var currentAddress = String()
geocoder.reverseGeocodeCoordinate(coordinate) { response , error in
if let address = response?.firstResult() {
let lines = address.lines! as [String]
currentAddress = lines[0]
currentAdd(currentAddress)
}
}
}
}
extension TrackingLocation: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let now = Date()
if(now > lastTime) {
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.setCoordinates()
self.locationChecker.sendTextIfInTrouble()
lastTime = Date(timeInterval: TIME_INTERVAL, since: now)
} else {
self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
}
if UIApplication.shared.applicationState == .active {
//print("App is foreground. New location is %@", mostRecentLocation)
} else {
//print("App is backgrounded. New location is %@", mostRecentLocation)
}
}
}
| 36.415205 | 122 | 0.584391 |
1d8c2eabb431026b9b87122fbcc052de0e0fb9bc | 337 | import UIKit
import BlowMindStyle
struct AppEnvironment {
let theme: AppTheme
}
extension AppEnvironment: StyleEnvironmentConvertible {
func toStyleEnvironment(_ traitCollection: UITraitCollection) -> StyleEnvironment<AppTheme> {
StyleEnvironment(traitCollection: traitCollection, theme: theme, locale: locale)
}
}
| 25.923077 | 97 | 0.780415 |
089217e7b8ce4f2ab76bb8ec7fe0e25f73e9e3c6 | 5,073 | import XCTest
@testable import ParselyTracker
class SessionTests: ParselyTestCase {
var sessions: SessionManager!
let sessionStorageKey = "_parsely_session_identifier"
let testInitialUrl = "http://parsely-test.com/123"
let testSubsequentUrl = "http://parsely-test.com/"
let epochTimeInThePast = 1553459222
override func setUp() {
super.setUp()
sessions = SessionManager(trackerInstance: parselyTestTracker)
// XXX slight hack, ideally this functionality should be a method on SessionManager
Storage().expire(key: sessionStorageKey)
}
func testGet() {
let session = sessions.get(url: testInitialUrl, urlref: testSubsequentUrl)
XCTAssertGreaterThanOrEqual(session["session_id"] as! Int, 0,
"The session_id of a newly-created session should be greater than or equal to 0")
XCTAssertEqual(session["session_url"] as! String, testInitialUrl,
"The session_url of a newly-created session should be the url it was initialized with")
XCTAssertEqual(session["session_referrer"] as! String, testSubsequentUrl,
"The session_referrer of a newly-created session should be the urlref it was initialized with")
XCTAssertGreaterThan(session["session_ts"] as! UInt64, UInt64(epochTimeInThePast),
"The session_ts of a newly-created session should be non-ancient")
XCTAssertGreaterThan(session["last_session_ts"] as! UInt64, UInt64(epochTimeInThePast),
"The last_session_ts of a newly-created session should be non-ancient")
}
func testIDPersists() {
let session = sessions.get(url: testInitialUrl, urlref: "")
XCTAssertFalse(session.isEmpty, "The first call to SessionManager.get should create a session object")
let subsequentSession = sessions.get(url: testSubsequentUrl, urlref: testInitialUrl, shouldExtendExisting: true)
XCTAssertEqual(session["session_id"] as! Int, subsequentSession["session_id"] as! Int,
"Sequential calls to SessionManager.get within the session timeout that have " +
"shouldExtendExisting:true should return a session object with the same session ID as the " +
"preexisting session object")
XCTAssertEqual(session["session_url"] as! String, testInitialUrl,
"The url of a session that has been extended with a different url should not have changed")
}
func testGetCorrectlyMutatesVisitor() {
let visitorManager = VisitorManager()
let visitorInfo = visitorManager.getVisitorInfo()
let initialSessionCount: Int = visitorInfo["session_count"] as! Int
let session = sessions.get(url: testInitialUrl, urlref: testSubsequentUrl)
let mutatedVisitor = visitorManager.getVisitorInfo()
let expectedSessionCount = initialSessionCount + 1
let expectedLastSessionTs: UInt64 = session["session_ts"] as! UInt64
XCTAssertEqual(mutatedVisitor["session_count"] as! Int, expectedSessionCount,
"The visitor's session_count should have been incremented after a call to SessionManager.get")
XCTAssertEqual(mutatedVisitor["last_session_ts"] as! UInt64, UInt64(expectedLastSessionTs),
"The visitor's last_session_ts should have been set to the session's session_ts after a call to " +
"SessionManager.get")
}
func testShouldExtendExisting() {
let session = sessions.get(url: testInitialUrl, urlref: "")
let subsequentSession = sessions.get(url: testInitialUrl, urlref: "", shouldExtendExisting: true)
XCTAssert(subsequentSession["expires"] as! Date > session["expires"] as! Date,
"Sequential calls to SessionManager.get within the session timeout that have " +
"shouldExtendExisting:true should return a session object with an extended expiry value " +
"compared to the original expiry of the session")
}
func testExtendExpiry() {
let initialSession = sessions.get(url: testInitialUrl, urlref: "")
let initialSessionExpiry: Date = initialSession["expires"] as! Date
let extendSessionExpiryResult = sessions.extendExpiry()
let sessionUnderTest = sessions.get(url: testInitialUrl, urlref: "")
XCTAssertGreaterThan(extendSessionExpiryResult["expires"] as! Date, initialSessionExpiry,
"A call to extendSessionExpiry after a call to SessionManager.get should extend the session's " +
"expiry by the expected amount and return the corresponding value.")
XCTAssertGreaterThan(sessionUnderTest["expires"] as! Date, initialSessionExpiry,
"A call to extendSessionExpiry after a call to SessionManager.get should extend the session's " +
"expiry by the expected amount.")
}
}
| 62.62963 | 126 | 0.673566 |
4ac3397644ee282b53fb77d9f071ce67ff9d74aa | 823 | //
// ProfileTests.swift
// BankeyUnitTests
//
// Created by Archit Patel on 2022-03-11.
//
import Foundation
import XCTest
@testable import Bankey
class ProfileTests: XCTestCase {
override func setUp() {
super.setUp()
}
func testCanParse() throws {
func testCanParse() throws {
let json = """
{
"id": "1",
"first_name": "Kevin",
"last_name": "Flynn",
}
"""
let data = json.data(using: .utf8)!
let result = try! JSONDecoder().decode(Profile.self, from: data)
XCTAssertEqual(result.id, "1")
XCTAssertEqual(result.firstName, "Kevin")
XCTAssertEqual(result.lastName, "Flynn")
}
}
}
| 21.657895 | 76 | 0.496962 |
11d16f8b9b602fbc0456faccb9cbb587d02759a6 | 15,843 | import Flutter
import UIKit
import SystemConfiguration.CaptiveNetwork
import NetworkExtension
public class SwiftWifiIotPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "wifi_iot", binaryMessenger: registrar.messenger())
let instance = SwiftWifiIotPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch (call.method) {
/// Stand Alone
case "loadWifiList":
loadWifiList(result: result)
break;
case "forceWifiUsage":
forceWifiUsage(call: call, result: result)
break;
case "isEnabled":
isEnabled(result: result)
break;
case "setEnabled":
setEnabled(call: call, result: result)
break;
case "findAndConnect": // OK
findAndConnect(call: call, result: result)
break;
case "connect": // OK
connect(call: call, result: result)
break;
case "isConnected": // OK
isConnected(result: result)
break;
case "disconnect": // OK
disconnect(result: result)
break;
case "getSSID":
result(getSSID())
break;
case "getBSSID":
result(getBSSID())
break;
case "getCurrentSignalStrength":
getCurrentSignalStrength(result: result)
break;
case "getFrequency":
getFrequency(result: result)
break;
case "getIP":
getIP(result: result)
break;
case "removeWifiNetwork": // OK
removeWifiNetwork(call: call, result: result)
break;
case "isRegisteredWifiNetwork":
isRegisteredWifiNetwork(call: call, result: result)
break;
/// Access Point
case "isWiFiAPEnabled":
isWiFiAPEnabled(result: result)
break;
case "setWiFiAPEnabled":
setWiFiAPEnabled(call: call, result: result)
break;
case "getWiFiAPState":
getWiFiAPState(result: result)
break;
case "getClientList":
getClientList(result: result)
break;
case "getWiFiAPSSID":
getWiFiAPSSID(result: result)
break;
case "setWiFiAPSSID":
setWiFiAPSSID(call: call, result: result)
break;
case "isSSIDHidden":
isSSIDHidden(result: result)
break;
case "setSSIDHidden":
setSSIDHidden(call: call, result: result)
break;
case "getWiFiAPPreSharedKey":
getWiFiAPPreSharedKey(result: result)
break;
case "setWiFiAPPreSharedKey":
setWiFiAPPreSharedKey(call: call, result: result)
break;
case "setMACFiltering":
setMACFiltering(call: call, result: result)
break;
default:
result(FlutterMethodNotImplemented);
break;
}
}
private func loadWifiList(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func forceWifiUsage(call: FlutterMethodCall, result: FlutterResult) {
let arguments = call.arguments
let useWifi = (arguments as! [String : Bool])["useWifi"]
if (useWifi != nil) {
print("Forcing WiFi usage : %s", ((useWifi ?? false) ? "Use WiFi" : "Use 3G/4G Data"))
if #available(iOS 14.0, *) {
if(useWifi ?? false){
// trigger access for local network
triggerLocalNetworkPrivacyAlert();
}
}
result(FlutterMethodNotImplemented)
} else {
result(nil)
}
}
private func connect(call: FlutterMethodCall, result: @escaping FlutterResult) {
let sSSID = (call.arguments as? [String : AnyObject])?["ssid"] as! String
let sPassword = (call.arguments as? [String : AnyObject])?["password"] as! String?
let bJoinOnce = (call.arguments as? [String : AnyObject])?["join_once"] as! Bool?
let sSecurity = (call.arguments as? [String : AnyObject])?["security"] as! String?
// print("SSID : '\(sSSID)'")
// print("PASSWORD : '\(sPassword)'")
// print("JOIN_ONCE : '\(bJoinOnce)'")
// if (bJoinOnce) {
// print("The network will be forgotten!")
// }
// print("SECURITY : '\(sSecurity)'")
if #available(iOS 11.0, *) {
let configuration = initHotspotConfiguration(ssid: sSSID, passphrase: sPassword, security: sSecurity)
configuration.joinOnce = bJoinOnce ?? false
NEHotspotConfigurationManager.shared.apply(configuration) { [weak self] (error) in
if (error != nil) {
if (error?.localizedDescription == "already associated.") {
if let this = self, let ssid = this.getSSID() {
print("Connected to " + ssid)
}
result(true)
} else {
print("Not Connected")
result(false)
}
return
} else {
guard let this = self else {
print("WiFi network not found")
result(false)
return
}
if let ssid = this.getSSID() {
print("Connected to " + ssid)
// ssid check is required because if wifi not found (could not connect) there seems to be no error given
result(ssid == sSSID)
} else {
print("WiFi network not found")
result(false)
}
return
}
}
} else {
print("Not Connected")
result(nil)
return
}
}
private func findAndConnect(call: FlutterMethodCall, result: @escaping FlutterResult) {
result(FlutterMethodNotImplemented)
}
@available(iOS 11.0, *)
private func initHotspotConfiguration(ssid: String, passphrase: String?, security: String? = nil) -> NEHotspotConfiguration {
switch security?.uppercased() {
case "WPA":
return NEHotspotConfiguration.init(ssid: ssid, passphrase: passphrase!, isWEP: false)
case "WEP":
return NEHotspotConfiguration.init(ssid: ssid, passphrase: passphrase!, isWEP: true)
default:
return NEHotspotConfiguration.init(ssid: ssid)
}
}
private func isEnabled(result: FlutterResult) {
// For now..
let sSSID: String? = getSSID()
if (sSSID != nil) {
result(true)
} else {
result(nil)
}
}
private func setEnabled(call: FlutterMethodCall, result: FlutterResult) {
let arguments = call.arguments
let state = (arguments as! [String : Bool])["state"]
if (state != nil) {
print("Setting WiFi Enable : \(((state ?? false) ? "enable" : "disable"))")
result(FlutterMethodNotImplemented)
} else {
result(nil)
}
}
private func isConnected(result: FlutterResult) {
// For now..
let sSSID: String? = getSSID()
if (sSSID != nil) {
result(true)
} else {
result(false)
}
}
private func disconnect(result: FlutterResult) {
if #available(iOS 11.0, *) {
let sSSID: String? = getSSID()
if (sSSID != nil) {
print("trying to disconnect from '\(sSSID!)'")
NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: sSSID ?? "")
result(true)
} else {
print("SSID is null")
result(false)
}
} else {
print("Not disconnected")
result(nil)
}
}
private func getSSID() -> String? {
var ssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
break
}
}
}
return ssid
}
private func getBSSID() -> String? {
var bssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
bssid = interfaceInfo[kCNNetworkInfoKeyBSSID as String] as? String
break
}
}
}
return bssid
}
private func getCurrentSignalStrength(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func getFrequency(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func getIP(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func removeWifiNetwork(call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments
let sPrefixSSID = (arguments as! [String : String])["prefix_ssid"] ?? ""
if (sPrefixSSID == "") {
print("No prefix SSID was given!")
result(nil)
}
if #available(iOS 11.0, *) {
NEHotspotConfigurationManager.shared.getConfiguredSSIDs { (htSSID) in
for sIncSSID in htSSID {
if (sPrefixSSID != "" && sIncSSID.hasPrefix(sPrefixSSID)) {
NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: sIncSSID)
}
}
}
result(true)
} else {
print("Not removed")
result(nil)
}
}
private func isRegisteredWifiNetwork(call: FlutterMethodCall, result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func isWiFiAPEnabled(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func setWiFiAPEnabled(call: FlutterMethodCall, result: FlutterResult) {
let arguments = call.arguments
let state = (arguments as! [String : Bool])["state"]
if (state != nil) {
print("Setting AP WiFi Enable : \(state ?? false ? "enable" : "disable")")
result(FlutterMethodNotImplemented)
} else {
result(nil)
}
}
private func getWiFiAPState(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func getClientList(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func getWiFiAPSSID(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func setWiFiAPSSID(call: FlutterMethodCall, result: FlutterResult) {
let arguments = call.arguments
let ssid = (arguments as! [String : String])["ssid"]
if (ssid != nil) {
print("Setting AP WiFi SSID : '\(ssid ?? "")'")
result(FlutterMethodNotImplemented)
} else {
result(nil)
}
}
private func isSSIDHidden(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func setSSIDHidden(call: FlutterMethodCall, result: FlutterResult) {
let arguments = call.arguments
let hidden = (arguments as! [String : Bool])["hidden"]
if (hidden != nil) {
print("Setting AP WiFi Visibility : \(((hidden ?? false) ? "hidden" : "visible"))")
result(FlutterMethodNotImplemented)
} else {
result(nil)
}
}
private func getWiFiAPPreSharedKey(result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
private func setWiFiAPPreSharedKey(call: FlutterMethodCall, result: FlutterResult) {
let arguments = call.arguments
let preSharedKey = (arguments as! [String : String])["preSharedKey"]
if (preSharedKey != nil) {
print("Setting AP WiFi PreSharedKey : '\(preSharedKey ?? "")'")
result(FlutterMethodNotImplemented)
} else {
result(nil)
}
}
private func setMACFiltering(call: FlutterMethodCall, result: FlutterResult) {
result(FlutterMethodNotImplemented)
}
}
/// Used to enforce local network usage for iOSv14+
/// For more background on this, see [Triggering the Local Network Privacy Alert](https://developer.apple.com/forums/thread/663768).
func triggerLocalNetworkPrivacyAlert() {
let sock4 = socket(AF_INET, SOCK_DGRAM, 0)
guard sock4 >= 0 else { return }
defer { close(sock4) }
let sock6 = socket(AF_INET6, SOCK_DGRAM, 0)
guard sock6 >= 0 else { return }
defer { close(sock6) }
let addresses = addressesOfDiscardServiceOnBroadcastCapableInterfaces()
var message = [UInt8]("!".utf8)
for address in addresses {
address.withUnsafeBytes { buf in
let sa = buf.baseAddress!.assumingMemoryBound(to: sockaddr.self)
let saLen = socklen_t(buf.count)
let sock = sa.pointee.sa_family == AF_INET ? sock4 : sock6
_ = sendto(sock, &message, message.count, MSG_DONTWAIT, sa, saLen)
}
}
}
/// Returns the addresses of the discard service (port 9) on every
/// broadcast-capable interface.
///
/// Each array entry is contains either a `sockaddr_in` or `sockaddr_in6`.
private func addressesOfDiscardServiceOnBroadcastCapableInterfaces() -> [Data] {
var addrList: UnsafeMutablePointer<ifaddrs>? = nil
let err = getifaddrs(&addrList)
guard err == 0, let start = addrList else { return [] }
defer { freeifaddrs(start) }
return sequence(first: start, next: { $0.pointee.ifa_next })
.compactMap { i -> Data? in
guard
(i.pointee.ifa_flags & UInt32(bitPattern: IFF_BROADCAST)) != 0,
let sa = i.pointee.ifa_addr
else { return nil }
var result = Data(UnsafeRawBufferPointer(start: sa, count: Int(sa.pointee.sa_len)))
switch CInt(sa.pointee.sa_family) {
case AF_INET:
result.withUnsafeMutableBytes { buf in
let sin = buf.baseAddress!.assumingMemoryBound(to: sockaddr_in.self)
sin.pointee.sin_port = UInt16(9).bigEndian
}
case AF_INET6:
result.withUnsafeMutableBytes { buf in
let sin6 = buf.baseAddress!.assumingMemoryBound(to: sockaddr_in6.self)
sin6.pointee.sin6_port = UInt16(9).bigEndian
}
default:
return nil
}
return result
}
}
| 36.758701 | 132 | 0.546487 |
878d820675104cd1d53758443c22649817fcf3e6 | 244 | //
// Bool+Ext.swift
// Traviler
//
// Created by Mohammed Iskandar on 24/12/2020.
//
import Foundation
extension Bool {
var numeric: Int {
if self {
return 1
} else {
return 0
}
}
}
| 12.842105 | 47 | 0.495902 |
edfc913d0f432d0e31dccf9b3c5524e6bc27f128 | 2,357 | //
// AppDelegate.swift
// ImagePreviewDemo
//
// Created by Tim van Steenis on 26/10/15.
// Copyright © 2015 Q42. All rights reserved.
//
import UIKit
import ImagePreview
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Uncomment this if you want to implement your own headers.
// ImagePreviewSettings.sharedSettings.headers = [
// 1 : NSData(base64EncodedString: "your base64 encoded header", options: [])!
// ]
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:.
}
}
| 44.471698 | 281 | 0.764531 |
e053c031dbda90b4a61c3d7d6cb0e72a8d42174c | 482 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
c
j)
func c<k>() -> (k, > k) -> k {
d h d.f 1, k(j, i)))
class k {
typealias h = h
| 32.133333 | 78 | 0.686722 |
11d208b368f1cf5a236fbcaad883dfc096554633 | 194 | //
// This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to Plist.playground.
//
| 48.5 | 187 | 0.78866 |
0842dd8b8bd60ee965a414d8a2e24d634bab5506 | 1,481 | //
// DataGroupParser.swift
//
// Created by Andy Qua on 14/06/2019.
//
import OpenSSL
@available(iOS 13, macOS 10.15, *)
class DataGroupParser {
static let dataGroupNames = ["Common", "DG1", "DG2", "DG3", "DG4", "DG5", "DG6", "DG7", "DG8", "DG9", "DG10", "DG11", "DG12", "DG13", "DG14", "DG15", "DG16", "SecurityData"]
static let tags : [UInt8] = [0x60, 0x61, 0x75, 0x63, 0x76, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x77]
static let classes : [DataGroup.Type] = [COM.self, DataGroup1.self, DataGroup2.self,
DataGroup3.self, DataGroup4.self, DataGroup5.self,
DataGroup6.self, DataGroup7.self, DataGroup8.self,
DataGroup9.self, DataGroup10.self, DataGroup11.self,
DataGroup12.self, DataGroup13.self, DataGroup14.self,
DataGroup15.self, DataGroup16.self, SOD.self]
func parseDG( data : [UInt8] ) throws -> DataGroup {
let header = data[0..<4]
let dg = try tagToDG(header[0])
return try dg.init(data)
}
func tagToDG( _ tag : UInt8 ) throws -> DataGroup.Type {
guard let index = DataGroupParser.tags.firstIndex(of: tag) else { throw NFCPassportReaderError.UnknownTag}
return DataGroupParser.classes[index]
}
}
| 40.027027 | 177 | 0.548953 |
e230ac5e2f482119aa5fa557b8194021577e655f | 797 | import Foundation
class SynchronizedDictionary<Key: Hashable, Value> {
private var dictionary: [Key: Value] = [:]
private let queue = DispatchQueue(label: "Tasker.Collections.SynchronizedDictionary", attributes: [.concurrent])
init() {}
var data: [Key: Value] {
self.queue.sync {
self.dictionary
}
}
subscript(key: Key) -> Value? {
get {
self.queue.sync {
self.dictionary[key]
}
}
set {
self.queue.async(flags: .barrier) { [weak self] in
guard let newValue = newValue else {
self?.dictionary[key] = nil
return
}
self?.dictionary[key] = newValue
}
}
}
}
| 24.90625 | 116 | 0.496863 |
8a8beefee16cc487485c609115710b4b506ae9c3 | 238 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class d<T {
struct d< A {
protocol a {
init( )
}
let c {
d<T : {
a {
| 18.307692 | 87 | 0.697479 |
62865710b3e49092ec77e9788a737424e7f71c59 | 11,109 | //
// ObservableType.swift
// MyBroker
//
// Created by Alexej Nenastev on 26.02.2018.
// Copyright © 2018 BCS. All rights reserved.
//
import RxSwift
import RxCocoa
public extension Observable where Element: OptionalType, Element.Wrapped == Int {
func nilToZero() -> Observable<Element.Wrapped> {
return flatMap { value in
value.optional.map { Observable<Element.Wrapped>.just($0) } ?? Observable<Element.Wrapped>.just(0)
}
}
}
public extension Observable where Element: OptionalType, Element.Wrapped == Double {
func nilToZero() -> Observable<Element.Wrapped> {
return flatMap { value in
value.optional.map { Observable<Element.Wrapped>.just($0) } ?? Observable<Element.Wrapped>.just(0)
}
}
}
public extension Observable where Element: OptionalType {
func ignoreNil() -> Observable<Element.Wrapped> {
return flatMap { value in
value.optional.map { Observable<Element.Wrapped>.just($0) } ?? Observable<Element.Wrapped>.empty()
}
}
}
public extension ObservableType where Element == Bool {
func bindsIsHidden(bag: DisposeBag, to views: UIView?...) {
let shared = self.share()
views.compactMap { $0 }.forEach { shared.bind(to: $0.rx.isHidden).disposed(by: bag) }
}
func throttleOnlyTrue(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Observable<Bool> {
return flatMapLatest {
$0 ? Observable.just(true).delay(dueTime, scheduler: scheduler) : Observable.just(false)
}
}
}
public extension ObservableType where Self.Element == Any {
static func timerWithTrigger(trigger: Observable<Bool>, timer: Observable<Int>) -> Observable<Void> {
return Observable.combineLatest(trigger, timer)
.flatMapLatest {
$0.0 ? Observable<Int64>.interval(.seconds($0.1), scheduler: MainScheduler.instance).startWith(0).map { _ in () } : .empty() }
}
}
public extension PrimitiveSequenceType where Self.Trait == RxSwift.SingleTrait {
func subscribe<T: AnyObject>(_ instance: T,
complete classFunc: @escaping (T)->(Element)->Void,
error errClassFunc: ((T)->(Error)->Void)? = nil,
bag: DisposeBag) {
self.subscribe(onSuccess: { [weak instance] args in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction(args)
}, onError: { [weak instance] error in
guard let instance = instance, let errClassFunc = errClassFunc else { return }
let instanceFunction = errClassFunc(instance)
instanceFunction(error)
}).disposed(by: bag)
}
func subscribe<T: AnyObject>(_ instance: T,
complete classFunc: @escaping (T)->()->Void,
error errClassFunc: ((T)->(Error)->Void)? = nil,
bag: DisposeBag) {
self.subscribe(onSuccess: { [weak instance] _ in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction()
}, onError: { [weak instance] error in
guard let instance = instance, let errClassFunc = errClassFunc else { return }
let instanceFunction = errClassFunc(instance)
instanceFunction(error)
}).disposed(by: bag)
}
}
public extension PrimitiveSequence {
func map<R>(_ transform: @escaping (PrimitiveSequence.Element) throws -> R) -> Single<R> {
return self.asObservable().map(transform).asSingle()
}
}
public extension ObservableType {
func onlyOnce() -> Observable<Self.Element> {
return self.take(1)
}
func mapToVoid() -> Observable<Void> {
return map { _ in ()}
}
func binds<O>(bag: DisposeBag, to observer: O...) where O: ObserverType, Self.Element == O.Element {
let shared = self.share()
observer.forEach { shared.bind(to: $0).disposed(by: bag) }
}
/**
Добавляет в observable объект как weak ссылку, когда произойдет событие будет проверка что объект доступен иначе вернется .empty()
*/
func guardWeak<WeakObj: AnyObject>(_ weakObj: WeakObj) -> Observable<(WeakObj, Self.Element)> {
return self.flatMap({ [weak weakObj] (obj) -> Observable<(WeakObj, Self.Element)> in
guard let weakObj = weakObj else { return Observable.empty() }
return Observable.just((weakObj, obj))
})
}
func map<T: AnyObject, Res>(_ instance: T, with classFunc: @escaping (T)->(Self.Element)->(Res)) -> Observable<Res> {
return self.flatMap { [weak instance] args -> Observable<Res> in
guard let instance = instance else { return Observable.empty() }
let instanceFunction = classFunc(instance)
return Observable.just(instanceFunction(args))
}
}
func filter<T: AnyObject>(_ instance: T, with classFunc: @escaping (T) -> () -> (Bool)) -> Observable<Self.Element> {
return self.filter { [weak instance] _ in
guard let instance = instance else { return false}
let instanceFunction = classFunc(instance)
return instanceFunction()
}
}
func subscribeNext(_ handler: @escaping (Self.Element) -> Void) -> Disposable {
return self.subscribe(onNext: handler)
}
func subscribeNextOnMain<T: AnyObject>(_ instance: T, with classFunc: @escaping (T)->(Self.Element)->Void, bag: DisposeBag) {
self.observeOn(MainScheduler.asyncInstance)
.subscribeNext(instance, with: classFunc, bag: bag)
}
func subscribeNext<T: AnyObject>(_ instance: T, with classFunc: @escaping (T)->(Self.Element)->Void, bag: DisposeBag) {
self.subscribe(onNext: { [weak instance] args in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction(args)
}).disposed(by: bag)
}
func subscribeNext<T: AnyObject>(_ instance: T, do classFunc: @escaping (T) -> () -> Void, bag: DisposeBag) {
self.subscribe(onNext: { [weak instance] _ in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction()
}).disposed(by: bag)
}
func doNext<T: AnyObject>(_ instance: T, with classFunc: @escaping (T)->(Self.Element)->Void) -> Observable<Self.Element> {
return self.do(onNext: { [weak instance] args in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction(args)
})
}
func doNext<T: AnyObject>(_ instance: T, do classFunc: @escaping (T) -> () -> Void) -> Observable<Self.Element> {
return self.do(onNext: { [weak instance] _ in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction()
})
}
func filter(_ val: Variable<Bool>) -> Observable<Element> {
return filter { _ in val.value }
}
func doOnError<T: AnyObject>(_ instance: T, _ classFunc: @escaping (T) -> (Error) -> Void) -> Observable<Element> {
return self.do(onError: { [unowned instance] err in
let instanceFunction = classFunc(instance)
instanceFunction(err)
})
}
func subscribe<T: AnyObject>(_ instance: T,
with classFunc: @escaping (T)->(Element)->Void,
error errClassFunc: ((T)->(Error)->Void)?,
disposeBy bag: DisposeBag) {
self.subscribe(onNext: { [weak instance] args in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction(args)
}, onError: { [weak instance] error in
guard let instance = instance, let errClassFunc = errClassFunc else { return }
let instanceFunction = errClassFunc(instance)
instanceFunction(error)
}).disposed(by: bag)
}
func subscribe<T: AnyObject>(_ instance: T,
do classFunc: @escaping (T)->()->Void,
error errClassFunc: ((T)->(Error)->Void)?,
disposeBy bag: DisposeBag) {
self.subscribe(onNext: { [weak instance] _ in
guard let instance = instance else { return }
let instanceFunction = classFunc(instance)
instanceFunction()
}, onError: { [weak instance] error in
guard let instance = instance, let errClassFunc = errClassFunc else { return }
let instanceFunction = errClassFunc(instance)
instanceFunction(error)
}).disposed(by: bag)
}
}
public extension ObservableType {
func endEditingOnNext<T: UIViewController>(_ instance: T) -> Observable<Element> {
return self.do(onNext: { [weak instance] _ in
guard let instance = instance else { return }
instance.view.endEditing(true)
})
}
}
public typealias Seconds = Int
public extension ObservableType where Element == Seconds {
func intervalMapLatest() -> Observable<Int64> {
return flatMapLatest ({ seconds in
Observable<Int64>
.interval(.seconds(seconds), scheduler: MainScheduler.instance)
.startWith(0)})
}
}
public extension ObservableType {
// swiftlint:disable all
func flatMapCatchError<O: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> O,
doOnNext: @escaping (O.Element) -> Void = { _ in },
doOnError: @escaping (Error) -> Void = { _ in })
-> Observable<O.Element> {
return self.flatMap({ (val) -> Observable<O.Element> in
return try selector(val).asObservable().catchError({ error -> Observable<O.Element> in
doOnError(error)
return Observable.empty()
})
}).do(onNext: doOnNext)
}
func flatMapFirstCatchError<O>(_ selector: @escaping (Self.Element) throws -> O,
doOnNext: @escaping (O.Element) -> Void = { _ in },
doOnError: @escaping (Error) -> Void = { _ in }) -> RxSwift.Observable<O.Element> where O: ObservableConvertibleType {
return self.flatMapFirst({ (val) -> Observable<O.Element> in
return try selector(val).asObservable().catchError({ error -> Observable<O.Element> in
doOnError(error)
return Observable.empty()
})
}).do(onNext: doOnNext)
}
}
| 40.104693 | 154 | 0.589162 |
eb3fdb55a40ab66300ccd07503ba029257ede4f9 | 8,162 | // autogenerated
// swiftlint:disable all
import Foundation
public struct CiWorkflowCreateRequest: Hashable, Codable {
public var data: Data
public init(data: Data) {
self.data = data
}
private enum CodingKeys: String, CodingKey {
case data
}
public struct Data: Hashable, Codable {
public var type: `Type`
public var attributes: Attributes
public var relationships: Relationships
public init(
type: `Type`,
attributes: Attributes,
relationships: Relationships
) {
self.type = type
self.attributes = attributes
self.relationships = relationships
}
private enum CodingKeys: String, CodingKey {
case type
case attributes
case relationships
}
public enum `Type`: String, Hashable, Codable {
case ciWorkflows
}
public struct Attributes: Hashable, Codable {
public var actions: [CiAction]
public var branchStartCondition: CiBranchStartCondition?
public var clean: Bool
public var containerFilePath: String
public var description: String
public var isEnabled: Bool
public var isLockedForEditing: Bool?
public var name: String
public var pullRequestStartCondition: CiPullRequestStartCondition?
public var scheduledStartCondition: CiScheduledStartCondition?
public var tagStartCondition: CiTagStartCondition?
public init(
actions: [CiAction],
branchStartCondition: CiBranchStartCondition? = nil,
clean: Bool,
containerFilePath: String,
description: String,
isEnabled: Bool,
isLockedForEditing: Bool? = nil,
name: String,
pullRequestStartCondition: CiPullRequestStartCondition? = nil,
scheduledStartCondition: CiScheduledStartCondition? = nil,
tagStartCondition: CiTagStartCondition? = nil
) {
self.actions = actions
self.branchStartCondition = branchStartCondition
self.clean = clean
self.containerFilePath = containerFilePath
self.description = description
self.isEnabled = isEnabled
self.isLockedForEditing = isLockedForEditing
self.name = name
self.pullRequestStartCondition = pullRequestStartCondition
self.scheduledStartCondition = scheduledStartCondition
self.tagStartCondition = tagStartCondition
}
private enum CodingKeys: String, CodingKey {
case actions
case branchStartCondition
case clean
case containerFilePath
case description
case isEnabled
case isLockedForEditing
case name
case pullRequestStartCondition
case scheduledStartCondition
case tagStartCondition
}
}
public struct Relationships: Hashable, Codable {
public var macOsVersion: MacOsVersion
public var product: Product
public var repository: Repository
public var xcodeVersion: XcodeVersion
public init(
macOsVersion: MacOsVersion,
product: Product,
repository: Repository,
xcodeVersion: XcodeVersion
) {
self.macOsVersion = macOsVersion
self.product = product
self.repository = repository
self.xcodeVersion = xcodeVersion
}
private enum CodingKeys: String, CodingKey {
case macOsVersion
case product
case repository
case xcodeVersion
}
public struct MacOsVersion: Hashable, Codable {
public var data: Data
public init(data: Data) {
self.data = data
}
private enum CodingKeys: String, CodingKey {
case data
}
public struct Data: Hashable, Codable {
public var id: String
public var type: `Type`
public init(
id: String,
type: `Type`
) {
self.id = id
self.type = type
}
private enum CodingKeys: String, CodingKey {
case id
case type
}
public enum `Type`: String, Hashable, Codable {
case ciMacOsVersions
}
}
}
public struct Product: Hashable, Codable {
public var data: Data
public init(data: Data) {
self.data = data
}
private enum CodingKeys: String, CodingKey {
case data
}
public struct Data: Hashable, Codable {
public var id: String
public var type: `Type`
public init(
id: String,
type: `Type`
) {
self.id = id
self.type = type
}
private enum CodingKeys: String, CodingKey {
case id
case type
}
public enum `Type`: String, Hashable, Codable {
case ciProducts
}
}
}
public struct Repository: Hashable, Codable {
public var data: Data
public init(data: Data) {
self.data = data
}
private enum CodingKeys: String, CodingKey {
case data
}
public struct Data: Hashable, Codable {
public var id: String
public var type: `Type`
public init(
id: String,
type: `Type`
) {
self.id = id
self.type = type
}
private enum CodingKeys: String, CodingKey {
case id
case type
}
public enum `Type`: String, Hashable, Codable {
case scmRepositories
}
}
}
public struct XcodeVersion: Hashable, Codable {
public var data: Data
public init(data: Data) {
self.data = data
}
private enum CodingKeys: String, CodingKey {
case data
}
public struct Data: Hashable, Codable {
public var id: String
public var type: `Type`
public init(
id: String,
type: `Type`
) {
self.id = id
self.type = type
}
private enum CodingKeys: String, CodingKey {
case id
case type
}
public enum `Type`: String, Hashable, Codable {
case ciXcodeVersions
}
}
}
}
}
}
// swiftlint:enable all
| 29.15 | 78 | 0.454545 |
7a067e28526cfae20a911a23d8b05ee8612f0e39 | 1,437 | //
// Promise+Web3+Eth+GetAccounts.swift
// web3swift
//
// Created by Alexander Vlasov on 17.06.2018.
// Copyright © 2018 Bankex Foundation. All rights reserved.
//
import Foundation
import BigInt
import PromiseKit
import EthereumAddress
extension web3.Eth {
public func getAccountsPromise() -> Promise<[EthereumAddress]> {
let queue = web3.requestDispatcher.queue
if (self.web3.provider.attachedKeystoreManager != nil) {
let promise = Promise<[EthereumAddress]>.pending()
queue.async {
let result = self.web3.wallet.getAccounts()
switch result {
case .success(let allAccounts):
promise.resolver.fulfill(allAccounts)
case .failure(let error):
promise.resolver.reject(error)
}
}
return promise.promise
}
let request = JSONRPCRequestFabric.prepareRequest(.getAccounts, parameters: [])
let rp = web3.dispatch(request)
return rp.map(on: queue ) { response in
guard let value: [EthereumAddress] = response.getValue() else {
if response.error != nil {
throw Web3Error.nodeError(desc: response.error!.message)
}
throw Web3Error.nodeError(desc: "Invalid value from Ethereum node")
}
return value
}
}
}
| 33.418605 | 87 | 0.585943 |
20544b32993aa10dc3524764fc1c89b616a35eae | 12,287 | //
// AudioUnitManager+Effects.swift
// AudioUnitManager
//
// Created by Ryan Francesconi, revision history on Githbub.
// Copyright © 2017 Ryan Francesconi. All rights reserved.
//
import AudioKit
import AVFoundation
import Cocoa
extension AudioUnitManager {
internal func initManager() {
internalManager = AKAudioUnitManager(inserts: 6)
internalManager?.delegate = self
internalManager?.requestEffects(completionHandler: { audioUnits in
self.updateEffectsUI(audioUnits: audioUnits)
})
internalManager?.requestInstruments(completionHandler: { audioUnits in
self.updateInstrumentsUI(audioUnits: audioUnits)
})
}
internal func initUI() {
let colors = [NSColor(calibratedRed: 1, green: 0.652, blue: 0, alpha: 1),
NSColor(calibratedRed: 0.32, green: 0.584, blue: 0.8, alpha: 1),
NSColor(calibratedRed: 0.79, green: 0.372, blue: 0.191, alpha: 1),
NSColor(calibratedRed: 0.676, green: 0.537, blue: 0.315, alpha: 1),
NSColor(calibratedRed: 0.431, green: 0.701, blue: 0.407, alpha: 1),
NSColor(calibratedRed: 0.59, green: 0.544, blue: 0.763, alpha: 1)]
var counter = 0
var buttons = effectsContainer.subviews.filter { $0 as? MenuButton != nil }
buttons.sort { $0.tag < $1.tag }
for sv in buttons {
guard let b = sv as? MenuButton else { continue }
b.bgColor = colors[counter]
counter += 1
if counter > colors.count {
counter = 0
}
}
}
////////////////////////////
func showEffect(at auIndex: Int, state: Bool) {
guard let internalManager = internalManager else { return }
if auIndex > internalManager.effectsChain.count - 1 {
AKLog("index is out of range")
return
}
if state {
// get audio unit at the specified index
if let au = internalManager.effectsChain[auIndex] {
showAudioUnit(au, identifier: auIndex)
} else {
AKLog("Nothing at this index")
}
} else {
if let w = getWindowFromIndentifier(auIndex) {
w.close()
}
}
}
func handleEffectSelected(_ auname: String, identifier: Int) {
guard let internalManager = internalManager else { return }
AKLog("\(identifier) \(auname)")
if auname == "-" {
let blankName = "▼ Insert \(identifier + 1)"
if let button = getEffectsButtonFromIdentifier(identifier) {
button.state = .off
}
if let menu = getMenuFromIdentifier(identifier) {
selectEffectInMenu(name: "-", identifier: identifier)
menu.title = blankName
}
if let win = getWindowFromIndentifier(identifier) {
win.close()
}
internalManager.removeEffect(at: identifier)
return
}
internalManager.insertAudioUnit(name: auname, at: identifier)
// select the item in the menu
selectEffectInMenu(name: auname, identifier: identifier)
}
func selectEffectInMenu(name: String, identifier: Int) {
guard let button = getMenuFromIdentifier(identifier) else { return }
guard let menu = button.menu else { return }
var parentMenu: NSMenuItem?
for man in menu.items {
guard let sub = man.submenu else { continue }
man.state = .off
for item in sub.items {
item.state = (item.title == name) ? .on : .off
if item.state == .on {
parentMenu = man
}
}
}
if let pm = parentMenu {
pm.state = .on
button.title = "▶︎ \(name)"
}
}
// MARK: - Build the effects menus
fileprivate func updateEffectsUI(audioUnits: [AVAudioUnitComponent]) {
var manufacturers = [String]()
for component in audioUnits {
let man = component.manufacturerName
if !manufacturers.contains(man) {
manufacturers.append(man)
}
}
// going to put internal AUs in here
manufacturers.append(akInternals)
manufacturers.sort()
// fill all the menus with the same list
for sv in effectsContainer.subviews {
guard let b = sv as? MenuButton else { continue }
fillAUMenu(button: b, manufacturers: manufacturers, audioUnits: audioUnits)
}
}
private func fillAUMenu(button: MenuButton, manufacturers: [String], audioUnits: [AVAudioUnitComponent]) {
guard let internalManager = internalManager else { return }
if button.menu == nil {
let theMenu = NSMenu(title: "Effects")
theMenu.font = NSFont.systemFont(ofSize: 10)
button.menu = theMenu
}
button.menu?.removeAllItems()
button.title = "▼ Insert \(button.tag + 1)"
let blankItem = ClosureMenuItem(title: "-", closure: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.handleEffectSelected("-", identifier: button.tag)
})
button.menu?.addItem(blankItem)
// first make a menu of manufacturers
for man in manufacturers {
let manItem = NSMenuItem()
manItem.title = man
manItem.submenu = NSMenu(title: man)
button.menu?.addItem(manItem)
}
// then add each AU into it's parent folder
for component in audioUnits {
let item = ClosureMenuItem(title: component.name, closure: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.handleEffectSelected(component.name, identifier: button.tag)
})
guard let bmenu = button.menu else { continue }
// manufacturer list
for man in bmenu.items where man.title == component.manufacturerName {
man.submenu?.addItem(item)
}
}
let internalSubmenu = button.menu?.items.first(where: { $0.title == akInternals })
for name in internalManager.internalAudioUnits {
let item = ClosureMenuItem(title: name, closure: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.handleEffectSelected(name, identifier: button.tag)
})
internalSubmenu?.submenu?.addItem(item)
}
}
internal func getMenuFromIdentifier(_ tag: Int) -> MenuButton? {
guard effectsContainer != nil else { return nil }
for sv in effectsContainer.subviews {
guard let b = sv as? MenuButton else { continue }
if b.tag == tag {
return b
}
}
return nil
}
internal func getWindowFromIndentifier(_ tag: Int) -> NSWindow? {
let identifier = windowPrefix + String(tag)
guard let windows = self.view.window?.childWindows else { return nil }
for w in windows where w.identifier?.rawValue == identifier {
return w
}
return nil
}
internal func getEffectsButtonFromIdentifier(_ buttonId: Int) -> NSButton? {
guard effectsContainer != nil else { return nil }
for sv in effectsContainer.subviews {
if !sv.isKind(of: NSPopUpButton.self) {
if let b = sv as? NSButton {
if b.tag == buttonId {
return b
}
}
}
}
return nil
}
public func showAudioUnit(_ audioUnit: AVAudioUnit, identifier: Int) {
var previousWindowOrigin: NSPoint?
if let w = getWindowFromIndentifier(identifier) {
previousWindowOrigin = w.frame.origin
w.close()
}
var windowColor = NSColor.darkGray
if let buttonColor = getMenuFromIdentifier(identifier)?.bgColor {
windowColor = buttonColor
}
// first we ask the audio unit if it has a view controller inside it
audioUnit.auAudioUnit.requestViewController { [weak self] viewController in
guard let strongSelf = self else { return }
var ui = viewController
DispatchQueue.main.async {
// if it doesn't - then an Audio Unit host's job is to create one for it
if ui == nil {
// AKLog("No ViewController for \(audioUnit.name )")
ui = NSViewController()
ui?.view = AudioUnitGenericView(audioUnit: audioUnit)
}
guard let theUI = ui else { return }
strongSelf.createAUWindow(viewController: theUI,
audioUnit: audioUnit,
identifier: identifier,
origin: previousWindowOrigin,
color: windowColor)
}
}
}
private func createAUWindow(viewController: NSViewController,
audioUnit: AVAudioUnit,
identifier: Int,
origin: NSPoint? = nil,
color: NSColor? = nil) {
let incomingFrame = viewController.view.frame
let toolbarHeight: CGFloat = 20
let windowColor = color ?? NSColor.darkGray
AKLog("Audio Unit incoming frame: \(incomingFrame)")
let unitWindowController = AudioUnitGenericWindow(audioUnit: audioUnit)
guard let unitWindow = unitWindowController.window else { return }
guard let auName = audioUnit.auAudioUnit.audioUnitName else { return }
let winId = windowPrefix + String(identifier)
let origin = origin ??
windowPositions[winId] ?? view.window?.frame.origin ?? NSPoint()
let f = NSRect(origin: origin,
size: NSSize(width: incomingFrame.width, height: incomingFrame.height + toolbarHeight + 20))
unitWindow.setFrame(f, display: false)
unitWindow.title = "\(auName)"
unitWindow.delegate = self
unitWindow.identifier = NSUserInterfaceItemIdentifier(winId)
unitWindowController.scrollView.documentView = viewController.view
unitWindowController.toolbar?.backgroundColor = windowColor.withAlphaComponent(0.9)
view.window?.addChildWindow(unitWindow, ordered: NSWindow.OrderingMode.above)
if let button = self.getEffectsButtonFromIdentifier(identifier) {
button.state = .on
}
}
fileprivate func reconnect() {
guard let internalManager = internalManager else { return }
// is FM playing?
if fmOscillator.isStarted {
internalManager.connectEffects(firstNode: fmOscillator, lastNode: mixer)
return
} else if let auInstrument = auInstrument, !(player?.isPlaying ?? false) {
internalManager.connectEffects(firstNode: auInstrument, lastNode: mixer)
return
} else if let player = player {
let wasPlaying = player.isPlaying
if wasPlaying {
player.stop()
}
internalManager.connectEffects(firstNode: player, lastNode: mixer)
if wasPlaying {
player.play()
}
}
}
}
extension AudioUnitManager: AKAudioUnitManagerDelegate {
func handleAudioUnitNotification(type: AKAudioUnitManager.Notification, object: Any?) {
if type == AKAudioUnitManager.Notification.changed {
guard let internalManager = internalManager else { return }
updateEffectsUI(audioUnits: internalManager.availableEffects)
}
}
func handleEffectAdded(at auIndex: Int) {
showEffect(at: auIndex, state: true)
reconnect()
}
func handleEffectRemoved(at auIndex: Int) {
reconnect()
}
}
| 34.036011 | 115 | 0.570847 |
293ebed76a1f3d113b6d7ccca9c258bd14cc97b6 | 2,139 | //
// AppDelegate.swift
// Tinder
//
// Created by Lee Edwards on 3/2/16.
// Copyright © 2016 Lee Edwards. 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.510638 | 285 | 0.753156 |
72fd348d8d4bb1ff07d2a3b4b6d4fae6da890161 | 287 | import UIKit
class MovieCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var opendate: UILabel!
@IBOutlet weak var desc: UILabel!
@IBOutlet weak var rating: UILabel!
@IBOutlet weak var thumbnail: UIImageView!
}
| 17.9375 | 46 | 0.648084 |
d9c5725596562366e37952fb0774b5a59f6e79d4 | 1,129 | //
// Library
//
// Created by Otto Suess on 05.12.18.
// Copyright © 2018 Zap. All rights reserved.
//
import Foundation
final class SyncPercentageEstimator {
let initialLndBlockHeight: Int
let initialHeaderDate: Date
init(initialLndBlockHeight: Int, initialHeaderDate: Date) {
self.initialLndBlockHeight = initialLndBlockHeight
self.initialHeaderDate = initialHeaderDate
}
func percentage(lndBlockHeight: Int, lndHeaderDate: Date, maxBlockHeight: Int) -> Double {
// blocks
let blocksToSync = maxBlockHeight - initialLndBlockHeight
let blocksRemaining = maxBlockHeight - lndBlockHeight
let blocksDone = blocksToSync - blocksRemaining
// filters
let filtersToSync = Int(abs(initialHeaderDate.timeIntervalSinceNow / 10))
let filtersRemaining = Int(abs(lndHeaderDate.timeIntervalSinceNow / 10))
let filtersDone = filtersToSync - filtersRemaining
// totals
let totalToSync = blocksToSync + filtersToSync
let done = blocksDone + filtersDone
return Double(done) / Double(totalToSync)
}
}
| 31.361111 | 94 | 0.698849 |
8ab6faace329dbce3a6e72612d19f5a6edb21b97 | 146 | // THIS-TEST-SHOULD-NOT-COMPILE
// Use invalid type as array key in constructor expression.
main {
int k[] = [1,2,3];
trace({ k: 1 }[k]);
}
| 16.222222 | 59 | 0.616438 |
5d7aec7539e0353d43320008a2b997d0e57d3f21 | 1,175 | //
// POEditor.swift
// POEditor-Swift
//
// Created by Giuseppe Travasoni on 10/04/2020.
//
import Foundation
public struct POEditor {
public enum POEditorError: Error {
case notStarted
}
private static var apiService: APIService?
private(set) static var translationService: TranslationService?
public static func start(withKey apiKey: String) {
self.apiService = APIService(apiKey: apiKey)
}
public static func updateLanguages(for projectId: Int, completion: @escaping ((Error?) -> Void)) throws {
guard let apiService = apiService else {
throw POEditorError.notStarted
}
let translationService = TranslationService(projectId: projectId, apiService: apiService)
self.translationService = translationService
translationService.updateLanguages(completion)
}
public static func getProjects(_ completion: @escaping ((Result<[Project], Error>) -> Void)) {
guard let apiService = apiService else {
completion(.failure(POEditorError.notStarted))
return
}
apiService.getProjects(completion)
}
}
| 29.375 | 109 | 0.666383 |
bb35804af08be767dd2144e95d0aaa2e8d28e953 | 4,945 | //
// CVCalendarViewAnimator.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/27/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public final class CVCalendarViewAnimator {
fileprivate var calendarView: CalendarView?
// MARK: - Public properties
public weak var delegate: CVCalendarViewAnimatorDelegate!
public var coordinator: CVCalendarDayViewControlCoordinator? {
return calendarView?.coordinator
}
// MARK: - Init
public init(calendarView: CalendarView) {
self.calendarView = calendarView
delegate = self
}
}
// MARK: - Public methods
extension CVCalendarViewAnimator {
public func animateSelectionOnDayView(_ dayView: DayView) {
let selectionAnimation = delegate.selectionAnimation()
let selectionType = (calendarView?.shouldSelectRange ?? false) ? CVSelectionType.range(.changed) : CVSelectionType.single
dayView.setSelectedWithType(selectionType)
selectionAnimation(dayView) { _ in
//should not do anything here for now. can cause crashs if calender is dismissed before animation is completed.
}
}
public func animateDeselectionOnDayView(_ dayView: DayView) {
let deselectionAnimation = delegate.deselectionAnimation()
deselectionAnimation(dayView) { [weak dayView] _ in
if let selectedDayView = dayView {
self.coordinator?.deselectionPerformedOnDayView(selectedDayView)
}
}
}
}
// MARK: - CVCalendarViewAnimatorDelegate
extension CVCalendarViewAnimator: CVCalendarViewAnimatorDelegate {
@objc public func selectionAnimation() -> ((DayView, @escaping ((Bool) -> ())) -> ()) {
return selectionWithBounceEffect()
}
@objc public func deselectionAnimation() -> ((DayView, @escaping ((Bool) -> ())) -> ()) {
return deselectionWithFadeOutEffect()
}
}
// MARK: - Default animations
private extension CVCalendarViewAnimator {
func selectionWithBounceEffect() -> ((DayView, @escaping ((Bool) -> ())) -> ()) {
return {
dayView, completion in
dayView.dayLabel?.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
dayView.selectionView?.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.1,
options: UIView.AnimationOptions.beginFromCurrentState,
animations: {
dayView.selectionView?.transform = CGAffineTransform(scaleX: 1, y: 1)
dayView.dayLabel?.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: completion)
}
}
func deselectionWithBubbleEffect() -> ((DayView, @escaping ((Bool) -> ())) -> ()) {
return {
dayView, completion in
UIView.animate(withDuration: 0.15, delay: 0, usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.8,
options: UIView.AnimationOptions.curveEaseOut, animations: {
dayView.selectionView!.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
}) { _ in
UIView.animate(withDuration: 0.2, delay: 0,
options: UIView.AnimationOptions(),
animations: {
if let selectionView = dayView.selectionView {
selectionView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
}
}, completion: completion)
}
}
}
func deselectionWithFadeOutEffect() -> ((DayView, @escaping ((Bool) -> ())) -> ()) {
return {
dayView, completion in
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.6,
initialSpringVelocity: 0, options: [], animations: {
// return labels' defaults while circle view disappearing
dayView.setDeselectedWithClearing(false)
if let selectionView = dayView.selectionView {
selectionView.alpha = 0
}
}, completion: completion)
}
}
func deselectionWithRollingEffect() -> ((DayView, @escaping ((Bool) -> ())) -> ()) {
return {
dayView, completion in
UIView.animate(withDuration: 0.25, delay: 0,
options: UIView.AnimationOptions(),
animations: { () -> Void in
dayView.selectionView?.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
dayView.selectionView?.alpha = 0.0
}, completion: completion)
}
}
}
| 38.937008 | 129 | 0.579778 |
2f043958ff2d4ebff9a65dd9f917a3fe819d8010 | 1,658 | //
// Copyright (c) Chris Bartley 2020. Licensed under the MIT license. See LICENSE file.
//
import Foundation
public protocol BuzzDelegate: AnyObject {
func buzz(_ buzz: Buzz, isCommunicationEnabled: Bool, error: Error?)
func buzz(_ buzz: Buzz, isAuthorized: Bool, errorMessage: String?)
func buzz(_ buzz: Buzz, batteryInfo: Buzz.BatteryInfo)
func buzz(_ buzz: Buzz, deviceInfo: Buzz.DeviceInfo)
func buzz(_ buzz: Buzz, isMicEnabled: Bool)
func buzz(_ buzz: Buzz, areMotorsEnabled: Bool)
func buzz(_ buzz: Buzz, isMotorsQueueCleared: Bool)
func buzz(_ buzz: Buzz, responseError error: Error)
func buzz(_ buzz: Buzz, unknownCommand command: String)
func buzz(_ buzz: Buzz, badRequestFor command: Buzz.Command, errorMessage: String?)
func buzz(_ buzz: Buzz, failedToParse responseMessage: String, forCommand command: Buzz.Command)
}
public extension BuzzDelegate {
func buzz(_ buzz: Buzz, isCommunicationEnabled: Bool, error: Error?) {}
func buzz(_ buzz: Buzz, isAuthorized: Bool, errorMessage: String?) {}
func buzz(_ buzz: Buzz, batteryInfo: Buzz.BatteryInfo) {}
func buzz(_ buzz: Buzz, deviceInfo: Buzz.DeviceInfo) {}
func buzz(_ buzz: Buzz, isMicEnabled: Bool) {}
func buzz(_ buzz: Buzz, areMotorsEnabled: Bool) {}
func buzz(_ buzz: Buzz, isMotorsQueueCleared: Bool) {}
func buzz(_ buzz: Buzz, responseError error: Error) {}
func buzz(_ buzz: Buzz, unknownCommand command: String) {}
func buzz(_ buzz: Buzz, badRequestFor command: Buzz.Command, errorMessage: String?) {}
func buzz(_ buzz: Buzz, failedToParse responseMessage: String, forCommand command: Buzz.Command) {}
}
| 35.276596 | 102 | 0.723764 |
26c21f1f9ae05d12911699b098167d3657e61e53 | 4,018 | //
// StringAttribute.swift
// Alamofire
//
// Created by Fanxx on 2019/8/22.
//
import UIKit
public struct EasyStringAttribute {
public var attributes: [NSAttributedString.Key: Any]
///为nil则表示全局
public var range: NSRange?
public init(_ key: NSAttributedString.Key, _ value: Any, range: NSRange? = nil) {
self.attributes = [key: value]
self.range = range
}
public init(_ attrs: [NSAttributedString.Key: Any], range: NSRange? = nil) {
self.attributes = attrs
self.range = range
}
///指定作用范围, len<=0则代表到结尾
public static func range(_ loc: Int,_ len: Int,_ attrs: EasyStringAttribute...) -> EasyStringAttribute {
var values: [NSAttributedString.Key: Any] = [:]
for a in attrs {
values.merge(a.attributes) { (v, _) -> Any in return v }
}
return .init(values, range: NSMakeRange(loc, len))
}
///指定作用范围, len<=0则代表到结尾
public static func range(_ range: NSRange,_ attrs: EasyStringAttribute...) -> EasyStringAttribute {
var values: [NSAttributedString.Key: Any] = [:]
for a in attrs {
values.merge(a.attributes) { (v, _) -> Any in return v }
}
return .init(values, range: range)
}
///应用
public func apply(_ string: NSMutableAttributedString) {
var range: NSRange
if let r = self.range {
if r.length <= 0 {
range = NSMakeRange(r.location, string.length - r.location)
}else{
range = r
}
}else{
range = NSMakeRange(0, string.length)
}
string.addAttributes(self.attributes, range: range)
}
}
extension EasyCoding where Base == String {
public func attr(_ attrs: EasyStringAttribute...) -> NSAttributedString {
if attrs.count == 0 {
return NSAttributedString(string: self.base)
} else if attrs.count == 1 {
if attrs[0].range == nil {
return NSAttributedString(string: self.base, attributes: attrs[0].attributes)
}
}
let str = NSMutableAttributedString(string: self.base)
attrs.forEach({ $0.apply(str) })
return str
}
public func mutableAttr(_ attrs: EasyStringAttribute...) -> NSMutableAttributedString {
let str = NSMutableAttributedString(string: self.base)
attrs.forEach({ $0.apply(str) })
return str
}
}
extension EasyCoding where Base: NSAttributedString {
public func attr(_ attrs: EasyStringAttribute...) -> NSMutableAttributedString {
let str = NSMutableAttributedString(attributedString: self.base)
attrs.forEach({ $0.apply(str) })
return str
}
}
extension EasyCoding where Base: NSMutableAttributedString {
@discardableResult
public func attr(_ attrs: EasyStringAttribute...) -> Base {
attrs.forEach({ $0.apply(self.base) })
return self.base
}
@discardableResult
public func reg(_ reg: String, options: NSRegularExpression.Options = .caseInsensitive, _ attrs: EasyStringAttribute...) -> Base {
var values: [NSAttributedString.Key: Any] = [:]
for a in attrs {
values.merge(a.attributes) { (v, _) -> Any in return v }
}
let reg = try? NSRegularExpression(pattern: reg, options: options)
reg?.enumerateMatches(in: self.base.string, options: .reportProgress, range: NSRange(location: 0, length: self.base.string.count)) { (result, flags, _) in
if let r = result {
EasyStringAttribute(values, range: r.range).apply(self.base)
}
}
return self.base
}
}
extension Dictionary where Key == NSAttributedString.Key, Value == Any {
public static func easy(_ attrs: EasyStringAttribute...) -> [NSAttributedString.Key: Any] {
var result:[NSAttributedString.Key: Any] = [:]
attrs.forEach({ result.merge($0.attributes, uniquingKeysWith: { $1 })})
return result
}
}
| 36.862385 | 162 | 0.610503 |
7593ba35d19c82232e121e7197c22d5eb629565d | 7,258 | //
// 🦠 Corona-Warn-App
//
import ExposureNotification
import Foundation
import UIKit
import OpenCombine
// MARK: - Supported Cell Types
extension DynamicCell {
private static let relativeDateTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.doesRelativeDateFormatting = true
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter
}()
private static func exposureDetectionCell(_ identifier: TableViewCellReuseIdentifiers, action: DynamicAction = .none, accessoryAction: DynamicAction = .none, configure: GenericCellConfigurator<ExposureDetectionViewController>? = nil) -> DynamicCell {
.custom(withIdentifier: identifier, action: action, accessoryAction: accessoryAction, configure: configure)
}
static func risk(hasSeparator: Bool = true, configure: @escaping GenericCellConfigurator<ExposureDetectionViewController>) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.risk) { viewController, cell, indexPath in
let viewModel = viewController.viewModel
cell.backgroundColor = viewModel.riskBackgroundColor
cell.tintColor = viewModel.riskContrastTintColor
cell.textLabel?.textColor = viewModel.titleTextColor
if let cell = cell as? ExposureDetectionRiskCell {
cell.separatorView.isHidden = (indexPath.row == 0) || !hasSeparator
cell.separatorView.backgroundColor = viewModel.riskSeparatorColor
}
configure(viewController, cell, indexPath)
}
}
static func riskLastRiskLevel(hasSeparator: Bool = true, text: String, image: UIImage?) -> DynamicCell {
.risk(hasSeparator: hasSeparator) { viewController, cell, _ in
let viewModel = viewController.viewModel
cell.textLabel?.text = String(format: text, viewModel.previousRiskTitle)
cell.imageView?.image = image
}
}
static func riskContacts(text: String, image: UIImage?) -> DynamicCell {
.risk { viewController, cell, _ in
cell.textLabel?.text = String(format: text, viewController.viewModel.riskDetails?.numberOfDaysWithRiskLevel ?? 0)
cell.imageView?.image = image
}
}
static func riskLastExposure(text: String, image: UIImage?) -> DynamicCell {
.risk { viewController, cell, _ in
cell.imageView?.image = image
guard let mostRecentDateWithHighRisk = viewController.viewModel.riskDetails?.mostRecentDateWithRiskLevel else {
assertionFailure("mostRecentDateWithRiskLevel must be set on high risk state")
cell.textLabel?.text = ""
return
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let formattedMostRecentDateWithHighRisk = dateFormatter.string(from: mostRecentDateWithHighRisk)
cell.textLabel?.text = .localizedStringWithFormat(text, formattedMostRecentDateWithHighRisk)
}
}
static func riskStored(daysSinceInstallation: Int) -> DynamicCell {
.risk { _, cell, _ in
cell.textLabel?.text = String(format: AppStrings.Home.daysSinceInstallation, daysSinceInstallation)
cell.imageView?.image = UIImage(named: "Icons-DaysSinceInstall")
}
}
static func riskRefreshed(text: String, image: UIImage?) -> DynamicCell {
.risk { viewController, cell, _ in
var valueText: String
if let enfRiskCalulationResult = viewController.store.enfRiskCalculationResult,
let checkinRiskCalculationResult = viewController.store.checkinRiskCalculationResult,
let date = Risk(enfRiskCalculationResult: enfRiskCalulationResult, checkinCalculationResult: checkinRiskCalculationResult).details.calculationDate {
valueText = relativeDateTimeFormatter.string(from: date)
} else {
valueText = AppStrings.ExposureDetection.refreshedNever
}
cell.textLabel?.text = String(format: text, valueText)
cell.imageView?.image = image
}
}
static func riskText(text: String) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.riskText) { viewController, cell, _ in
let viewModel = viewController.viewModel
cell.backgroundColor = viewModel.riskBackgroundColor
cell.textLabel?.textColor = viewModel.titleTextColor
cell.textLabel?.text = text
}
}
static func riskLoading(text: String) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.riskLoading) { viewController, cell, _ in
let cell = cell as? ExposureDetectionLoadingCell
let viewModel = viewController.viewModel
cell?.backgroundColor = viewModel.riskBackgroundColor
cell?.textLabel?.textColor = viewModel.titleTextColor
cell?.textLabel?.text = text
cell?.activityIndicatorView.color = viewModel.titleTextColor
}
}
static func header(title: String, subtitle: String) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.header) { _, cell, _ in
let cell = cell as? ExposureDetectionHeaderCell
cell?.titleLabel?.text = title
cell?.subtitleLabel?.text = subtitle
cell?.titleLabel?.accessibilityTraits = .header
}
}
static func guide(text: String, image: UIImage?) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.guide) { viewController, cell, _ in
cell.tintColor = viewController.viewModel.riskTintColor
cell.textLabel?.text = text
cell.imageView?.image = image
cell.accessibilityIdentifier = nil
}
}
static func guide(attributedString text: NSAttributedString, image: UIImage?, link: URL? = nil, accessibilityIdentifier: String? = nil) -> DynamicCell {
var action: DynamicAction = .none
if let url = link {
action = .open(url: url)
}
return .exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.guide, action: action) { viewController, cell, _ in
cell.tintColor = viewController.viewModel.riskTintColor
cell.textLabel?.attributedText = text
cell.imageView?.image = image
cell.accessibilityIdentifier = accessibilityIdentifier
}
}
static func guide(image: UIImage?, text: [String]) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.longGuide) { viewController, cell, _ in
cell.tintColor = viewController.viewModel.riskTintColor
(cell as? ExposureDetectionLongGuideCell)?.configure(image: image, text: text)
}
}
static func guide(image: UIImage?, attributedStrings text: [NSAttributedString]) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.longGuide) { viewController, cell, _ in
cell.tintColor = viewController.viewModel.riskTintColor
(cell as? ExposureDetectionLongGuideCell)?.configure(image: image, attributedText: text)
}
}
static func link(text: String, url: URL?, accessibilityIdentifier: String? = nil) -> DynamicCell {
.custom(withIdentifier: ExposureDetectionViewController.ReusableCellIdentifier.link, action: .open(url: url)) { _, cell, _ in
cell.textLabel?.text = text
cell.textLabel?.accessibilityIdentifier = accessibilityIdentifier
}
}
static func hotline(number: String) -> DynamicCell {
.exposureDetectionCell(ExposureDetectionViewController.ReusableCellIdentifier.hotline) { _, cell, _ in
(cell as? ExposureDetectionHotlineCell)?.hotlineContentView.primaryAction = {
LinkHelper.open(urlString: "tel://\(number)")
}
}
}
}
| 40.322222 | 251 | 0.772527 |
729d713ba725a8e036e7456d1156ada2a43caff0 | 14,079 | //
// ViewController.swift
// LTAutoScrollView
//
// Created by [email protected] on 04/14/2018.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
// 如有疑问,欢迎联系本人QQ: 1282990794
//
// UICollectionView 实现无限轮播功能,本框架不依赖任何第三方框架,Demo中使用Kingfisher加载,仅用于本Demo中测试,开发中可根据自己的实际需求进行更换
//
// github地址: https://github.com/gltwy/LTAutoScrollView
//
// clone地址: https://github.com/gltwy/LTAutoScrollView.git
//
// 支持cocoapods安装: pod 'LTAutoScrollView'
//
import UIKit
import Kingfisher
import LTAutoScrollView
class ViewController: UIViewController {
/* 用作本地图片展示 */
private let images = ["image1", "image2" , "image1", "image2"]
/* pageControl未选中图片 */
private let dotImage = UIImage(named: "pageControlDot")
/* pageControl选中图片 */
private let dotSelectImage = UIImage(named: "pageControlCurrentDot")
/* 用作网络图片展示 */
private let imageUrls = [
"http://i2.hdslb.com/bfs/archive/41f5d8b1bb5c6a03e6740ab342c9461786d45c0a.jpg",
"http://scimg.jb51.net/allimg/151113/14-15111310522aG.jpg" ,
"http://i2.hdslb.com/bfs/archive/41f5d8b1bb5c6a03e6740ab342c9461786d45c0a.jpg",
"http://scimg.jb51.net/allimg/151113/14-15111310522aG.jpg"
]
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: view.frame)
scrollView.backgroundColor = UIColor.RGBA(0, 0, 0, 0.25)
return scrollView
}()
/* 上下轮播利用scrollDirection控制 自定义pageControl 不设置dotLayout 则为隐藏pageControl */
private lazy var autoScrollView1: LTAutoScrollView = {
//pageControl的dot设置,详情看内部属性说明
let layout = LTDotLayout(dotWidth: 37/3.0, dotHeight: 19/3.0, dotMargin: 8, dotImage: dotImage, dotSelectImage: dotSelectImage)
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150), dotLayout: layout)
//设置滚动时间间隔 默认2.0s
autoScrollView.glt_timeInterval = 1.5
//设置轮播图的方向 默认水平
autoScrollView.scrollDirection = .vertical
//加载网络图片传入图片url数组, 加载本地图片传入图片名称数组
autoScrollView.images = images
//加载图片,内部不依赖任何图片加载框架
autoScrollView.imageHandle = {(imageView, imageName) in
//加载本地图片(根据传入的images数组来决定加载方式)
imageView.image = UIImage(named: imageName)
//加载网络图片(根据传入的images数组来决定加载方式)
// imageView.kf.setImage(with: URL(string: imageName))
}
// 滚动手势禁用(文字轮播较实用) 默认为false
autoScrollView.isDisableScrollGesture = false
//设置pageControl View的高度 默认为20
autoScrollView.gltPageControlHeight = 20;
//dot在轮播图的位置 中心 左侧 右侧 默认居中
autoScrollView.dotDirection = .default
//点击事件
autoScrollView.didSelectItemHandle = {
print("autoScrollView1 点击了第 \($0) 个索引")
}
//自动滚动到当前索引事件
autoScrollView.autoDidSelectItemHandle = { index in
print("autoScrollView1 自动滚动到了第 \(index) 个索引")
}
//PageControl点击事件
autoScrollView.pageControlDidSelectIndexHandle = { index in
print("autoScrollView1 pageControl点击了第 \(index) 个索引")
}
return autoScrollView
}()
/* 左右轮播 加载网络图片 */
private lazy var autoScrollView2: LTAutoScrollView = {
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150))
autoScrollView.glt_timeInterval = 1.5
autoScrollView.images = imageUrls
autoScrollView.imageHandle = {(imageView, imageName) in
imageView.kf.setImage(with: URL(string: imageName))
}
// 是否自动轮播 默认true
autoScrollView.isAutoScroll = true
autoScrollView.didSelectItemHandle = {[weak self] in
self?.navigationController?.pushViewController(PushViewController(), animated: true)
print("autoScrollView2 点击了第 \($0) 个索引")
}
autoScrollView.pageControlDidSelectIndexHandle = { index in
print("autoScrollView2 pageControl点击了第 \(index) 个索引")
}
let layout = LTDotLayout(dotImage: dotImage, dotSelectImage: dotSelectImage)
layout.dotMargin = 10.0
autoScrollView.dotLayout = layout
return autoScrollView
}()
/* 左右轮播 自定义控件 autoType = custom控制 */
private lazy var autoScrollView3: LTAutoScrollView = {
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150))
autoScrollView.glt_timeInterval = 1.5
autoScrollView.autoViewHandle = {
return self.customAutoView1()
}
autoScrollView.didSelectItemHandle = {
print("autoScrollView3 点击了第 \($0) 个索引")
}
//设置pageControl的位置
autoScrollView.dotDirection = .right
//dot在轮播图的位置 左侧 或 右侧时,距离最屏幕最左边或最最右边的距离
autoScrollView.adjustValue = 15.0
//pageControl高度调整从而改变pageControl位置
autoScrollView.gltPageControlHeight = 25
let layout = LTDotLayout(dotImage: dotImage, dotSelectImage: dotSelectImage)
autoScrollView.dotLayout = layout
return autoScrollView
}()
/* 文字上下轮播两行 */
private lazy var autoScrollView4: LTAutoScrollView = {
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 60))
autoScrollView.glt_timeInterval = 1.5
autoScrollView.scrollDirection = .vertical
// 滚动手势禁用(文字轮播较实用)
autoScrollView.isDisableScrollGesture = true
autoScrollView.autoViewHandle = {
return self.customAutoView2()
}
return autoScrollView
}()
/* 文字上下轮播一行 */
private lazy var autoScrollView5: LTAutoScrollView = {
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 30))
autoScrollView.glt_timeInterval = 1.5
autoScrollView.scrollDirection = .vertical
autoScrollView.isDisableScrollGesture = true
autoScrollView.autoViewHandle = {
return self.customAutoView3()
}
return autoScrollView
}()
/* 加载本地图片 */
private lazy var autoScrollView6: LTAutoScrollView = {
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150))
autoScrollView.glt_timeInterval = 1.5
autoScrollView.images = images
autoScrollView.imageHandle = {(imageView, imageName) in
imageView.image = UIImage(named: imageName)
}
autoScrollView.didSelectItemHandle = {
print("autoScrollView6 点击了第 \($0) 个索引")
}
let layout = LTDotLayout(dotImage: dotImage, dotSelectImage: dotSelectImage)
autoScrollView.dotLayout = layout
return autoScrollView
}()
/* 隐藏pageControl */
private lazy var autoScrollView7: LTAutoScrollView = {
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150))
autoScrollView.glt_timeInterval = 1.5
autoScrollView.images = images
autoScrollView.imageHandle = {(imageView, imageName) in
imageView.image = UIImage(named: imageName)
}
autoScrollView.didSelectItemHandle = {
print("autoScrollView7 点击了第 \($0) 个索引")
}
return autoScrollView
}()
/* 设置为系统的pageControl样式利用dotType */
private lazy var autoScrollView8: LTAutoScrollView = {
let autoScrollView = LTAutoScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150))
autoScrollView.glt_timeInterval = 1.5
autoScrollView.images = images
autoScrollView.imageHandle = {(imageView, imageName) in
imageView.image = UIImage(named: imageName)
}
autoScrollView.didSelectItemHandle = {
print("autoScrollView8 点击了第 \($0) 个索引")
}
let layout = LTDotLayout(dotColor: UIColor.white, dotSelectColor: UIColor.red, dotType: .default)
/*设置dot的间距*/
layout.dotMargin = 8
/* 如果需要改变dot的大小,设置dotWidth的宽度即可 */
layout.dotWidth = 10
/*如需和系统一致,dot放大效果需手动关闭 */
layout.isScale = false
autoScrollView.dotLayout = layout
return autoScrollView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
view.backgroundColor = UIColor.white
self.title = "轮播图"
let lable1 = baseLabel(Y: 34, text: "autoScrollView1")
scrollView.addSubview(autoScrollView1)
autoScrollView1.frame.origin.y = nextAutoViewY(lable1)
let lable2 = baseLabel(Y: nextItemY(autoScrollView1), text: "autoScrollView2")
scrollView.addSubview(autoScrollView2)
autoScrollView2.frame.origin.y = nextAutoViewY(lable2)
let lable3 = baseLabel(Y: nextItemY(autoScrollView2), text: "autoScrollView3")
scrollView.addSubview(autoScrollView3)
autoScrollView3.frame.origin.y = nextAutoViewY(lable3)
let lable4 = baseLabel(Y: nextItemY(autoScrollView3), text: "autoScrollView4")
scrollView.addSubview(autoScrollView4)
autoScrollView4.frame.origin.y = nextAutoViewY(lable4)
let lable5 = baseLabel(Y: nextItemY(autoScrollView4), text: "autoScrollView5")
scrollView.addSubview(autoScrollView5)
autoScrollView5.frame.origin.y = nextAutoViewY(lable5)
let lable6 = baseLabel(Y: nextItemY(autoScrollView5), text: "autoScrollView6")
scrollView.addSubview(autoScrollView6)
autoScrollView6.frame.origin.y = nextAutoViewY(lable6)
let lable7 = baseLabel(Y: nextItemY(autoScrollView6), text: "autoScrollView7")
scrollView.addSubview(autoScrollView7)
autoScrollView7.frame.origin.y = nextAutoViewY(lable7)
let lable8 = baseLabel(Y: nextItemY(autoScrollView7), text: "autoScrollView8")
scrollView.addSubview(autoScrollView8)
autoScrollView8.frame.origin.y = nextAutoViewY(lable8)
scrollView.contentSize = CGSize(width: view.bounds.width, height: viewBottom(autoScrollView8) + 34);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
private func customAutoView1() -> [UIImageView] {
var views = [UIImageView]()
for index in 0 ..< 3 {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 150))
imageView.image = UIImage(named: "image\(index / 2 + 1)")
views.append(imageView)
let label1 = UILabel(frame: CGRect(x: 40, y: 40, width: 180, height: 25))
label1.textColor = UIColor.white
label1.textAlignment = .center
label1.backgroundColor = UIColor.RGBA(0, 0, 0, 0.45)
label1.text = "自定义内部控件"
imageView.addSubview(label1)
let label2 = UILabel(frame: CGRect(x: 0, y: 125, width: view.bounds.width, height: 25))
label2.textColor = UIColor.white
label2.backgroundColor = UIColor.RGBA(0, 0, 0, 0.45)
label2.text = "自定义内部控件"
imageView.addSubview(label2)
}
return views
}
private func customAutoView2() -> [UIView] {
var views = [UIView]()
let labelText = ["大家一起起来嗨!", "今天天气不错哦!", "厉害了我的哥!"]
for index in 0 ..< labelText.count {
let bottomView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 60))
views.append(bottomView)
let label1 = UILabel(frame: CGRect(x: 10, y: 10, width: 180, height: 20))
label1.textColor = UIColor.white
label1.backgroundColor = UIColor.RGBA(0, 0, 0, 0.45)
label1.text = labelText[index]
bottomView.addSubview(label1)
let label2 = UILabel(frame: CGRect(x: 10, y: 30, width: view.bounds.width, height: 20))
label2.textColor = UIColor.white
label2.backgroundColor = UIColor.RGBA(0, 0, 0, 0.45)
label2.text = "不错哦!哈哈哈哈"
bottomView.addSubview(label2)
}
return views
}
private func customAutoView3() -> [UIView] {
var views = [UIView]()
let labelText = ["大家一起起来嗨!", "今天天气不错哦!", "厉害了我的哥!"]
for index in 0 ..< labelText.count {
let bottomView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 60))
views.append(bottomView)
let label1 = UILabel(frame: CGRect(x: 10, y: 0, width: 180, height: 30))
label1.textColor = UIColor.white
label1.backgroundColor = UIColor.RGBA(0, 0, 0, 0.45)
label1.text = labelText[index]
bottomView.addSubview(label1)
}
return views
}
}
extension ViewController {
@discardableResult
private func baseLabel(Y: CGFloat, text: String?) -> UILabel {
let label = UILabel(frame: CGRect(x: 0, y: Y, width: view.bounds.width, height: 25))
label.textColor = UIColor.white
label.backgroundColor = UIColor.RGBA(0, 0, 0, 0.45)
label.text = text
scrollView.addSubview(label)
return label
}
private func viewBottom(_ view: UIView) -> CGFloat {
return view.frame.origin.y + view.bounds.height
}
private func nextItemY(_ view: UIView) -> CGFloat {
return viewBottom(view) + 15
}
private func nextAutoViewY(_ lable: UILabel) -> CGFloat {
return viewBottom(lable) + 1
}
}
extension UIColor {
static func RGBA(_ R:CGFloat, _ G:CGFloat, _ B:CGFloat, _ alpha:CGFloat) -> UIColor{
let color = UIColor.init(red: (R / 255.0), green: (G / 255.0), blue: (B / 255.0), alpha: alpha);
return color;
}
}
| 39.108333 | 135 | 0.631224 |
38e81399032a928e0143b0ee1cb05cc75f623fde | 760 | //
// Created by Jim van Zummeren on 04/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
open class ContentfulFlavor : Flavor {
open var rules:[Rule] = [
HeaderRule(),
ListRule(listTypes:[
AlphabeticListType(),
OrderedListType()
]),
BlockQuoteRule(),
CodeBlockRule(),
ImageBlockRule()
]
open var defaultRule:Rule = ParagraphRule()
open var inlineRules:[InlineRule] = [
BoldRule(),
ItalicRule(),
StrikeRule(),
ImageRule(),
LinkRule(),
InlineCodeRule(),
ColoredFragmentRule()
]
open var defaultInlineRule: InlineRule = InlineTextRule()
public init() {
}
}
| 19.487179 | 61 | 0.565789 |
dda91b67993ff4392588957e4682fcad77a2efef | 922 | import SwiftUI
struct LogView: View {
@ObservedObject private(set) var log: Log
@Environment(\.locale) var locale
var body: some View {
List {
ForEach(log.entries, id: \.date) { entry in
HStack {
Text(entry.dateString(locale: self.locale))
Text(entry.skill.name)
}
}
.onDelete(perform: self.onDelete)
}
.navigationBarTitle("Log")
.navigationBarItems(trailing: EditButton())
}
private func onDelete(offsets: IndexSet) {
self.log.removeEntries(atOffsets: offsets)
}
}
struct LogView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
LogView(log: Log.testInstance)
}
.navigationViewStyle(StackNavigationViewStyle())
.environment(\.locale, Locale(identifier: "ru"))
}
}
| 26.342857 | 63 | 0.574837 |
5b1416e195923eb934868ad0a58bd908631f1a68 | 3,294 | //
// String+CDMarkdownKit.swift
// CDMarkdownKit
//
// Created by Christopher de Haan on 11/7/16.
//
// Copyright © 2016-2020 Christopher de Haan <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
internal extension String {
// Converts each character to its UTF16 form in hexadecimal value (e.g. "H" -> "0048")
func escapeUTF16() -> String {
return Array(utf16).map {
String(format: "%04x",
$0)
}.reduce("") {
return $0 + $1
}
}
// Converts each 4 digit characters to its String form (e.g. "0048" -> "H")
func unescapeUTF16() -> String? {
var utf16Array = [UInt16]()
stride(from: 0,
to: count,
by: 4).forEach {
let startIdx = index(startIndex,
offsetBy: $0)
if ($0 + 4) <= count {
let endIdx = index(startIndex,
offsetBy: $0 + 4)
let hex4 = self[startIdx..<endIdx]
if let utf16 = UInt16(hex4,
radix: 16) {
utf16Array.append(utf16)
}
}
}
return String(utf16CodeUnits: utf16Array,
count: utf16Array.count)
}
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
let from = from16.samePosition(in: self),
let to = to16.samePosition(in: self)
else { return nil }
return from ..< to
}
func characterCount() -> Int {
return self.count
}
func sizeWithAttributes(_ attributes: [CDAttributedStringKey: Any]? = nil) -> CGSize {
#if os(macOS)
return self.size(withAttributes: attributes)
#else
return self.size(withAttributes: attributes)
#endif
}
}
| 35.419355 | 125 | 0.6102 |
e0aeaac7a056d83970108b3e16823615c392f83e | 2,969 | import Foundation
import XCTestHTMLReportCore
var version = "2.1.0"
print("XCTestHTMLReport \(version)")
var command = Command()
var help = BlockArgument("h", "", required: false, helpMessage: "Print usage and available options") {
print(command.usage)
exit(EXIT_SUCCESS)
}
var verbose = BlockArgument("v", "", required: false, helpMessage: "Provide additional logs") {
Logger.verbose = true
}
var junitEnabled = false
var junit = BlockArgument("j", "junit", required: false, helpMessage: "Provide JUnit XML output") {
junitEnabled = true
}
var result = ValueArgument(.path, "r", "resultBundlePath", required: true, allowsMultiple: true, helpMessage: "Path to a result bundle (allows multiple)")
var renderingMode = Summary.RenderingMode.linking
var inlineAssets = BlockArgument("i", "inlineAssets", required: false, helpMessage: "Inline all assets in the resulting html-file, making it heavier, but more portable") {
renderingMode = .inline
}
var downsizeImagesEnabled = false
var downsizeImages = BlockArgument("z", "downsize-images", required: false, helpMessage: "Downsize image screenshots") {
downsizeImagesEnabled = true
}
var deleteUnattachedFilesEnabled = false
var deleteUnattachedFiles = BlockArgument("d", "delete-unattached", required: false, helpMessage: "Delete unattached files from bundle, reducing bundle size") {
deleteUnattachedFilesEnabled = true
}
command.arguments = [help,
verbose,
junit,
downsizeImages,
deleteUnattachedFiles,
result,
inlineAssets]
if !command.isValid {
print(command.usage)
exit(EXIT_FAILURE)
}
let summary = Summary(resultPaths: result.values, renderingMode: renderingMode)
Logger.step("Building HTML..")
let html = summary.generatedHtmlReport()
do {
let path = result.values.first!
.dropLastPathComponent()
.addPathComponent("index.html")
Logger.substep("Writing report to \(path)")
try html.write(toFile: path, atomically: false, encoding: .utf8)
Logger.success("\nReport successfully created at \(path)")
}
catch let e {
Logger.error("An error has occured while creating the report. Error: \(e)")
}
if junitEnabled {
Logger.step("Building JUnit..")
let junitXml = summary.generatedJunitReport()
do {
let path = "\(result.values.first!)/report.junit"
Logger.substep("Writing JUnit report to \(path)")
try junitXml.write(toFile: path, atomically: false, encoding: .utf8)
Logger.success("\nJUnit report successfully created at \(path)")
}
catch let e {
Logger.error("An error has occured while creating the JUnit report. Error: \(e)")
}
}
if downsizeImagesEnabled && renderingMode == .linking {
summary.reduceImageSizes()
}
if deleteUnattachedFilesEnabled && renderingMode == .linking {
summary.deleteUnattachedFiles()
}
exit(EXIT_SUCCESS)
| 32.988889 | 171 | 0.691815 |
161f7d64d0380c461c544b3ce28f2dd90b40c7ba | 375 | import Foundation
extension Array {
func at(_ index: Int?) -> Element? {
guard let index = index, index >= 0 && index < endIndex else {
return nil
}
return self[index]
}
func random() -> Element? {
// swiftlint:disable empty_count
guard count > 0 else {
return nil
}
return self[Int(arc4random_uniform(UInt32(count)))]
}
}
| 17.857143 | 66 | 0.605333 |
75ed216c9a7474c5f0a5926678ce1d933d968883 | 4,812 | //
// UIImage+Extensions.swift
//
//
// Created by Franklyn Weber on 19/02/2021.
//
import UIKit
extension UIImage {
enum Aspect {
case portrait
case landscape
}
func withCorrectedRotation(desiredAspect: Aspect? = nil) -> UIImage {
func rotatedIfNecessary(_ image: UIImage) -> UIImage {
guard let desiredAspect = desiredAspect, (desiredAspect == .portrait && image.size.width > image.size.height) || (desiredAspect == .landscape && image.size.width < image.size.height) else {
return image
}
// we have no idea whether to rotate cw or ccw so just do 90 degrees
return image.rotated(by: .pi / 2)
}
if imageOrientation == .up {
return rotatedIfNecessary(self)
}
var transform = CGAffineTransform.identity
let width = size.width
let height = size.height
switch imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: width, y: height)
transform = transform.rotated(by: .pi)
break
case .left, .leftMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.rotated(by: .pi / 2)
break
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: height)
transform = transform.rotated(by: -.pi / 2)
break
default:
break
}
switch imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
break
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: height, y: 0);
transform = transform.scaledBy(x: -1, y: 1)
break
default:
break
}
guard let cgImage = cgImage, let colorSpace = cgImage.colorSpace else {
return self
}
guard let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: cgImage.bitmapInfo.rawValue) else {
return self
}
context.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width))
break
default:
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
break
}
guard let image = context.makeImage() else {
return self
}
let correctedImage = UIImage(cgImage: image)
return rotatedIfNecessary(correctedImage)
}
func rotated(by radians: CGFloat) -> UIImage {
guard let orientation = CGImagePropertyOrientation(rawValue: UInt32(imageOrientation.rawValue)) else {
return self
}
guard let image = CIImage(image: self)?.oriented(orientation) else {
return self
}
let rotation = CGAffineTransform(rotationAngle: radians)
let output = image.transformed(by: rotation)
guard let cgImage = CIContext().createCGImage(output, from: output.extent) else {
return self
}
return UIImage(cgImage: cgImage)
}
func scaled(to scale: CGFloat) -> UIImage {
let scaledSize = CGSize(width: size.width * scale, height: size.height * scale)
let scaledRect = CGRect(origin: .zero, size: scaledSize)
UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, self.scale)
draw(in: scaledRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage ?? self
}
func cropped(with insets: UIEdgeInsets) -> UIImage {
guard let cgImage = cgImage else {
return self
}
let croppedRect = CGRect(origin: CGPoint(x: insets.left, y: insets.top), size: CGSize(width: size.width - insets.left - insets.right, height: size.height - insets.top - insets.bottom))
guard let cropped = cgImage.cropping(to: croppedRect) else {
return self
}
return UIImage(cgImage: cropped, scale: scale, orientation: imageOrientation)
}
}
| 31.86755 | 215 | 0.561721 |
e67969f73555cece22f525e00eba9fa41e96156b | 3,277 | //
// bulk_record_importer.swift
// CDAKit
//
// Created by Eric Whitley on 1/11/16.
// Copyright © 2016 Eric Whitley. All rights reserved.
//
import Foundation
import Fuzi
public enum CDAKImportError : Error {
case notImplemented
case unableToDetermineFormat
case noClinicalDocumentElement
case invalidXML
}
internal class CDAKImport_BulkRecordImporter {
internal class func importRecord(_ XMLString: String, providier_map:[String:CDAKProvider] = [:]) throws -> CDAKRecord {
do {
let doc = try XMLDocument(string: XMLString, encoding: String.Encoding.utf8)
if let root = doc.root {
if let root_element_name = root.tag , root_element_name == "ClinicalDocument" {
doc.definePrefix("cda", defaultNamespace: "urn:hl7-org:v3")
doc.definePrefix("sdtc", defaultNamespace: "urn:hl7-org:sdtc")
doc.definePrefix("mif", defaultNamespace: "urn:hl7-org:v3/mif")
if doc.xpath("/cda:ClinicalDocument/cda:templateId[@root='2.16.840.1.113883.3.88.11.32.1']").count > 0 {
print("Deteremined XML document format as: C32")
let importer = CDAKImport_C32_PatientImporter()
let record = importer.parse_c32(doc)
record.header = CDAKImport_cat1_HeaderImporter.import_header(doc)
return record
} else if doc.xpath("/cda:ClinicalDocument/cda:templateId[@root='2.16.840.1.113883.10.20.22.1.2']").count > 0 {
print("Deteremined XML document format as: CCDA")
let importer = CDAKImport_CCDA_PatientImporter()
let record = importer.parse_ccda(doc)
record.header = CDAKImport_cat1_HeaderImporter.import_header(doc)
return record
} else if doc.xpath("/cda:ClinicalDocument/cda:templateId[@root='2.16.840.1.113883.10.20.24.1.2']").count > 0 {
print("QRDA1 not (yet) supported")
throw CDAKImportError.notImplemented
} else if doc.xpath("/cda:ClinicalDocument/cda:templateId[@root='2.16.840.1.113883.10.20.22.1.1']").count > 0 && CDAKGlobals.sharedInstance.attemptNonStandardCDAImport == true {
//last ditch "we have a general US header, but that's about it"
print("Deteremined XML document format as: Non-Standard CDA. This may or may not import completely.")
let importer = CDAKImport_CCDA_PatientImporter()
let record = importer.parse_ccda(doc)
record.header = CDAKImport_cat1_HeaderImporter.import_header(doc)
return record
} else {
print("Unable to determinate document template/type of CDA document")
throw CDAKImportError.unableToDetermineFormat
}
} else {
print("XML does not appear to be a valid ClinicalDocument")
throw CDAKImportError.noClinicalDocumentElement
}
} else {
throw CDAKImportError.invalidXML
}
} catch let error as XMLError {
switch error {
case .parserFailure, .invalidData: print(error)
case .libXMLError(let code, let message):
print("libxml error code: \(code), message: \(message)")
default: print(error)
}
throw CDAKImportError.invalidXML
}
}
}
| 39.963415 | 187 | 0.649374 |
efcb26de10a883d8546d829a69d227449fa30072 | 1,412 | import XCTest
import Testing
import HTTP
import Sockets
@testable import Vapor
@testable import App
/// This file shows an example of testing an
/// individual controller without initializing
/// a Droplet.
class HelloControllerTests: TestCase {
/// For these tests, we won't be spinning up a live
/// server, and instead we'll be passing our constructed
/// requests programmatically
/// this is usually an effective way to test your
/// application in a convenient and safe manner
/// See RouteTests for an example of a live server test
let controller = HelloController(TestViewRenderer())
func testIndex() throws {
let req = Request.makeTest(method: .get)
try controller.index(req).makeResponse()
.assertBody(contains: "hello") // path
.assertBody(contains: "World") // default name
}
func testShow() throws {
let req = Request.makeTest(method: .get)
try controller.show(req, "Foo").makeResponse()
.assertBody(contains: "hello") // path
.assertBody(contains: "Foo") // custom name
}
}
// MARK: Manifest
extension HelloControllerTests {
/// This is a requirement for XCTest on Linux
/// to function properly.
/// See ./Tests/LinuxMain.swift for examples
static let allTests = [
("testIndex", testIndex),
("testShow", testShow),
]
}
| 30.042553 | 60 | 0.652266 |
8fae2a373b708cd0b7ae460bd5087aeac2deb2dd | 1,090 | //
// DisplayViewController.swift
// Waku
//
// Created by Mitsuaki Ihara on 2018/11/28.
// Copyright © 2018年 Mitsuaki Ihara. All rights reserved.
//
import UIKit
import WebKit
class DisplayViewController: UIViewController {
var url: String?
convenience init() {
self.init(url: nil)
}
init(url: String?) {
self.url = url
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
let view = DisplayView()
view.displayArea.uiDelegate = self
self.view = view
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let url = self.url,
let myURL = URL(string: url) else { fatalError("Please set url.") }
let myRequest = URLRequest(url: myURL)
let view = self.view as! DisplayView
view.displayArea.load(myRequest)
}
}
extension DisplayViewController: WKUIDelegate {}
| 22.708333 | 79 | 0.616514 |
7a046ce2cf3ba37f5e57224ce1398686980fac4a | 27,215 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A Swift Array or Dictionary of types conforming to
/// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or
/// NSDictionary, respectively. The elements of the resulting NSArray
/// or NSDictionary will be the result of calling `_bridgeToObjectiveC`
/// on each element of the source container.
public protocol _ObjectiveCBridgeable {
associatedtype _ObjectiveCType: AnyObject
/// Convert `self` to Objective-C.
func _bridgeToObjectiveC() -> _ObjectiveCType
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for forced downcasting (e.g.,
/// via as), and may defer complete checking until later. For
/// example, when bridging from `NSArray` to `Array<Element>`, we can defer
/// the checking for the individual elements of the array.
///
/// - parameter result: The location where the result is written. The optional
/// will always contain a value.
static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
)
/// Try to bridge from an Objective-C object of the bridged class
/// type to a value of the Self type.
///
/// This conditional bridging operation is used for conditional
/// downcasting (e.g., via as?) and therefore must perform a
/// complete conversion to the value type; it cannot defer checking
/// to a later time.
///
/// - parameter result: The location where the result is written.
///
/// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant
/// information is provided for the convenience of the runtime's `dynamic_cast`
/// implementation, so that it need not look into the optional representation
/// to determine success.
@discardableResult
static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) -> Bool
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for unconditional bridging when
/// interoperating with Objective-C code, either in the body of an
/// Objective-C thunk or when calling Objective-C code, and may
/// defer complete checking until later. For example, when bridging
/// from `NSArray` to `Array<Element>`, we can defer the checking
/// for the individual elements of the array.
///
/// \param source The Objective-C object from which we are
/// bridging. This optional value will only be `nil` in cases where
/// an Objective-C method has returned a `nil` despite being marked
/// as `_Nonnull`/`nonnull`. In most such cases, bridging will
/// generally force the value immediately. However, this gives
/// bridging the flexibility to substitute a default value to cope
/// with historical decisions, e.g., an existing Objective-C method
/// that returns `nil` to for "empty result" rather than (say) an
/// empty array. In such cases, when `nil` does occur, the
/// implementation of `Swift.Array`'s conformance to
/// `_ObjectiveCBridgeable` will produce an empty array rather than
/// dynamically failing.
@_effects(readonly)
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self
}
#if _runtime(_ObjC)
// Note: This function is not intended to be called from Swift. The
// availability information here is perfunctory; this function isn't considered
// part of the Stdlib's Swift ABI.
@available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *)
@_cdecl("_SwiftCreateBridgedArray")
@usableFromInline
internal func _SwiftCreateBridgedArray_DoNotCall(
values: UnsafePointer<AnyObject>,
numValues: Int
) -> Unmanaged<AnyObject> {
let bufPtr = UnsafeBufferPointer(start: values, count: numValues)
let bridged = Array(bufPtr)._bridgeToObjectiveCImpl()
return Unmanaged<AnyObject>.passRetained(bridged)
}
// Note: This function is not intended to be called from Swift. The
// availability information here is perfunctory; this function isn't considered
// part of the Stdlib's Swift ABI.
@available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *)
@_cdecl("_SwiftCreateBridgedMutableArray")
@usableFromInline
internal func _SwiftCreateBridgedMutableArray_DoNotCall(
values: UnsafePointer<AnyObject>,
numValues: Int
) -> Unmanaged<AnyObject> {
let bufPtr = UnsafeBufferPointer(start: values, count: numValues)
let bridged = _SwiftNSMutableArray(Array(bufPtr))
return Unmanaged<AnyObject>.passRetained(bridged)
}
@_silgen_name("swift_stdlib_connectNSBaseClasses")
internal func _connectNSBaseClasses() -> Bool
private let _bridgeInitializedSuccessfully = _connectNSBaseClasses()
internal var _orphanedFoundationSubclassesReparented: Bool = false
/// Reparents the SwiftNativeNS*Base classes to be subclasses of their respective
/// Foundation types, or is false if they couldn't be reparented. Must be run
/// in order to bridge Swift Strings, Arrays, Dictionarys, Sets, or Enumerators to ObjC.
internal func _connectOrphanedFoundationSubclassesIfNeeded() -> Void {
let bridgeWorks = _bridgeInitializedSuccessfully
_debugPrecondition(bridgeWorks)
_orphanedFoundationSubclassesReparented = true
}
//===--- Bridging for metatypes -------------------------------------------===//
/// A stand-in for a value of metatype type.
///
/// The language and runtime do not yet support protocol conformances for
/// structural types like metatypes. However, we can use a struct that contains
/// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table
/// will be ABI-compatible with one that directly provided conformance to the
/// metatype type itself.
public struct _BridgeableMetatype: _ObjectiveCBridgeable {
internal var value: AnyObject.Type
internal init(value: AnyObject.Type) {
self.value = value
}
public typealias _ObjectiveCType = AnyObject
public func _bridgeToObjectiveC() -> AnyObject {
return value
}
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) {
result = _BridgeableMetatype(value: source as! AnyObject.Type)
}
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) -> Bool {
if let type = source as? AnyObject.Type {
result = _BridgeableMetatype(value: type)
return true
}
result = nil
return false
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> _BridgeableMetatype {
var result: _BridgeableMetatype?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
//===--- Bridging facilities written in Objective-C -----------------------===//
// Functions that must discover and possibly use an arbitrary type's
// conformance to a given protocol. See ../runtime/Casting.cpp for
// implementations.
//===----------------------------------------------------------------------===//
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
// COMPILER_INTRINSIC
@inlinable
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return unsafeBitCast(x, to: AnyObject.self)
}
return _bridgeAnythingNonVerbatimToObjectiveC(x)
}
@_silgen_name("")
public // @testable
func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject
/// Convert a purportedly-nonnull `id` value from Objective-C into an Any.
///
/// Since Objective-C APIs sometimes get their nullability annotations wrong,
/// this includes a failsafe against nil `AnyObject`s, wrapping them up as
/// a nil `AnyObject?`-inside-an-`Any`.
///
// COMPILER_INTRINSIC
public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any {
if let nonnullObject = possiblyNullObject {
return nonnullObject // AnyObject-in-Any
}
return possiblyNullObject as Any
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, trap;
/// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`;
/// - otherwise, trap.
@inlinable
public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as! T
}
var result: T?
_bridgeNonVerbatimFromObjectiveC(x, T.self, &result)
return result!
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, the result is empty;
/// + otherwise, returns the result of
/// `T._conditionallyBridgeFromObjectiveC(x)`;
/// - otherwise, the result is empty.
@inlinable
public func _conditionallyBridgeFromObjectiveC<T>(
_ x: AnyObject,
_: T.Type
) -> T? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as? T
}
var result: T?
_ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result)
return result
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
@_silgen_name("")
@usableFromInline
internal func _bridgeNonVerbatimFromObjectiveC<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
)
/// Helper stub to upcast to Any and store the result to an inout Any?
/// on the C++ runtime's behalf.
@_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny")
internal func _bridgeNonVerbatimFromObjectiveCToAny(
_ x: AnyObject,
_ result: inout Any?
) {
result = x as Any
}
/// Helper stub to upcast to Optional on the C++ runtime's behalf.
@_silgen_name("_bridgeNonVerbatimBoxedValue")
internal func _bridgeNonVerbatimBoxedValue<NativeType>(
_ x: UnsafePointer<NativeType>,
_ result: inout NativeType?
) {
result = x.pointee
}
/// Runtime optional to conditionally perform a bridge from an object to a value
/// type.
///
/// - parameter result: Will be set to the resulting value if bridging succeeds, and
/// unchanged otherwise.
///
/// - Returns: `true` to indicate success, `false` to indicate failure.
@_silgen_name("")
public func _bridgeNonVerbatimFromObjectiveCConditional<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
) -> Bool
/// Determines if values of a given type can be converted to an Objective-C
/// representation.
///
/// - If `T` is a class type, returns `true`;
/// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`.
public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return true
}
return _isBridgedNonVerbatimToObjectiveC(T.self)
}
@_silgen_name("")
public func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool
/// A type that's bridged "verbatim" does not conform to
/// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an
/// `AnyObject`. When this function returns true, the storage of an
/// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`.
@inlinable // FIXME(sil-serialize-all)
public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool {
return _isClassOrObjCExistential(T.self)
}
/// Retrieve the Objective-C type to which the given type is bridged.
@inlinable // FIXME(sil-serialize-all)
public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return T.self
}
return _getBridgedNonVerbatimObjectiveCType(T.self)
}
@_silgen_name("")
public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?
// -- Pointer argument bridging
/// A mutable pointer addressing an Objective-C reference that doesn't own its
/// target.
///
/// `Pointee` must be a class type or `Optional<C>` where `C` is a class.
///
/// This type has implicit conversions to allow passing any of the following
/// to a C or ObjC API:
///
/// - `nil`, which gets passed as a null pointer,
/// - an inout argument of the referenced type, which gets passed as a pointer
/// to a writeback temporary with autoreleasing ownership semantics,
/// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is.
///
/// Passing pointers to mutable arrays of ObjC class pointers is not
/// directly supported. Unlike `UnsafeMutablePointer<Pointee>`,
/// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that
/// does not own a reference count to the referenced
/// value. UnsafeMutablePointer's operations, by contrast, assume that
/// the referenced storage owns values loaded from or stored to it.
///
/// This type does not carry an owner pointer unlike the other C*Pointer types
/// because it only needs to reference the results of inout conversions, which
/// already have writeback-scoped lifetime.
@frozen
public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
: _Pointer {
public let _rawValue: Builtin.RawPointer
@_transparent
public // COMPILER_INTRINSIC
init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Retrieve or set the `Pointee` instance referenced by `self`.
///
/// `AutoreleasingUnsafeMutablePointer` is assumed to reference a value with
/// `__autoreleasing` ownership semantics, like `NSFoo **` declarations in
/// ARC. Setting the pointee autoreleases the new value before trivially
/// storing it in the referenced memory.
///
/// - Precondition: the pointee has been initialized with an instance of type
/// `Pointee`.
@inlinable
public var pointee: Pointee {
@_transparent get {
// The memory addressed by this pointer contains a non-owning reference,
// therefore we *must not* point an `UnsafePointer<AnyObject>` to
// it---otherwise we would allow the compiler to assume it has a +1
// refcount, enabling some optimizations that wouldn't be valid.
//
// Instead, we need to load the pointee as a +0 unmanaged reference. For
// an extra twist, `Pointee` is allowed (but not required) to be an
// optional type, so we actually need to load it as an optional, and
// explicitly handle the nil case.
let unmanaged =
UnsafePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee
return _unsafeReferenceCast(
unmanaged?.takeUnretainedValue(),
to: Pointee.self)
}
@_transparent nonmutating set {
// Autorelease the object reference.
let object = _unsafeReferenceCast(newValue, to: Optional<AnyObject>.self)
Builtin.retain(object)
Builtin.autorelease(object)
// Convert it to an unmanaged reference and trivially assign it to the
// memory addressed by this pointer.
let unmanaged: Optional<Unmanaged<AnyObject>>
if let object = object {
unmanaged = Unmanaged.passUnretained(object)
} else {
unmanaged = nil
}
UnsafeMutablePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee =
unmanaged
}
}
/// Access the `i`th element of the raw array pointed to by
/// `self`.
///
/// - Precondition: `self != nil`.
@inlinable // unsafe-performance
public subscript(i: Int) -> Pointee {
@_transparent
get {
return self.advanced(by: i).pointee
}
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
public init<U>(@_nonEphemeral _ from: UnsafeMutablePointer<U>) {
self._rawValue = from._rawValue
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
public init?<U>(@_nonEphemeral _ from: UnsafeMutablePointer<U>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Explicit construction from a UnsafePointer.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@usableFromInline @_transparent
internal init<U>(
@_nonEphemeral _ from: UnsafePointer<U>
) {
self._rawValue = from._rawValue
}
/// Explicit construction from a UnsafePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@usableFromInline @_transparent
internal init?<U>(
@_nonEphemeral _ from: UnsafePointer<U>?
) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension UnsafeMutableRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>
) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>?
) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension UnsafeRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>
) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>?
) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension AutoreleasingUnsafeMutablePointer: ConcurrentValue { }
internal struct _CocoaFastEnumerationStackBuf {
// Clang uses 16 pointers. So do we.
internal var _item0: UnsafeRawPointer?
internal var _item1: UnsafeRawPointer?
internal var _item2: UnsafeRawPointer?
internal var _item3: UnsafeRawPointer?
internal var _item4: UnsafeRawPointer?
internal var _item5: UnsafeRawPointer?
internal var _item6: UnsafeRawPointer?
internal var _item7: UnsafeRawPointer?
internal var _item8: UnsafeRawPointer?
internal var _item9: UnsafeRawPointer?
internal var _item10: UnsafeRawPointer?
internal var _item11: UnsafeRawPointer?
internal var _item12: UnsafeRawPointer?
internal var _item13: UnsafeRawPointer?
internal var _item14: UnsafeRawPointer?
internal var _item15: UnsafeRawPointer?
@_transparent
internal var count: Int {
return 16
}
internal init() {
_item0 = nil
_item1 = _item0
_item2 = _item0
_item3 = _item0
_item4 = _item0
_item5 = _item0
_item6 = _item0
_item7 = _item0
_item8 = _item0
_item9 = _item0
_item10 = _item0
_item11 = _item0
_item12 = _item0
_item13 = _item0
_item14 = _item0
_item15 = _item0
_internalInvariant(MemoryLayout.size(ofValue: self) >=
MemoryLayout<Optional<UnsafeRawPointer>>.size * count)
}
}
/// Get the ObjC type encoding for a type as a pointer to a C string.
///
/// This is used by the Foundation overlays. The compiler will error if the
/// passed-in type is generic or not representable in Objective-C
@_transparent
public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> {
// This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is
// only supported by the compiler for concrete types that are representable
// in ObjC.
return UnsafePointer(Builtin.getObjCTypeEncoding(type))
}
#endif
//===--- Bridging without the ObjC runtime --------------------------------===//
#if !_runtime(_ObjC)
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
public // SPI(Foundation)
protocol _NSSwiftValue: AnyObject {
init(_ value: Any)
var value: Any { get }
static var null: AnyObject { get }
}
@usableFromInline
internal class __SwiftValue {
@usableFromInline
let value: Any
@usableFromInline
init(_ value: Any) {
self.value = value
}
@usableFromInline
static let null = __SwiftValue(Optional<Any>.none as Any)
}
// Internal stdlib SPI
@_silgen_name("swift_unboxFromSwiftValueWithType")
public func swift_unboxFromSwiftValueWithType<T>(
_ source: inout AnyObject,
_ result: UnsafeMutablePointer<T>
) -> Bool {
if source === _nullPlaceholder {
if let unpacked = Optional<Any>.none as? T {
result.initialize(to: unpacked)
return true
}
}
if let box = source as? __SwiftValue {
if let value = box.value as? T {
result.initialize(to: value)
return true
}
} else if let box = source as? _NSSwiftValue {
if let value = box.value as? T {
result.initialize(to: value)
return true
}
}
return false
}
// Internal stdlib SPI
@_silgen_name("swift_swiftValueConformsTo")
public func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool {
if let foundationType = _foundationSwiftValueType {
return foundationType is T.Type
} else {
return __SwiftValue.self is T.Type
}
}
@_silgen_name("_swift_extractDynamicValue")
public func _extractDynamicValue<T>(_ value: T) -> AnyObject?
@_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible")
public func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject?
internal protocol _Unwrappable {
func _unwrap() -> Any?
}
extension Optional: _Unwrappable {
internal func _unwrap() -> Any? {
return self
}
}
private let _foundationSwiftValueType = _typeByName("Foundation.__SwiftValue") as? _NSSwiftValue.Type
@usableFromInline
internal var _nullPlaceholder: AnyObject {
if let foundationType = _foundationSwiftValueType {
return foundationType.null
} else {
return __SwiftValue.null
}
}
@usableFromInline
func _makeSwiftValue(_ value: Any) -> AnyObject {
if let foundationType = _foundationSwiftValueType {
return foundationType.init(value)
} else {
return __SwiftValue(value)
}
}
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
// COMPILER_INTRINSIC
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
var done = false
var result: AnyObject!
let source: Any = x
if let dynamicSource = _extractDynamicValue(x) {
result = dynamicSource as AnyObject
done = true
}
if !done, let wrapper = source as? _Unwrappable {
if let value = wrapper._unwrap() {
result = value as AnyObject
} else {
result = _nullPlaceholder
}
done = true
}
if !done {
if type(of: source) as? AnyClass != nil {
result = unsafeBitCast(x, to: AnyObject.self)
} else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) {
result = object
} else {
result = _makeSwiftValue(source)
}
}
return result
}
#endif // !_runtime(_ObjC)
| 32.789157 | 101 | 0.705163 |
d6fe041194043bcbb2eb3948033d2a0efd4c6c33 | 4,141 | /*
Copyright (C) 2017 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to use UIButton.
The buttons are created using storyboards, but each of the system buttons can be created in code by
using the UIButton.init(type buttonType: UIButtonType) initializer.
See the UIButton interface for a comprehensive list of the various UIButtonType values.
*/
import UIKit
class ButtonViewController: UITableViewController {
// MARK: - Properties
@IBOutlet weak var systemTextButton: UIButton!
@IBOutlet weak var systemContactAddButton: UIButton!
@IBOutlet weak var systemDetailDisclosureButton: UIButton!
@IBOutlet weak var imageButton: UIButton!
@IBOutlet weak var attributedTextButton: UIButton!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// All of the buttons are created in the storyboard, but configured below.
configureSystemTextButton()
configureSystemContactAddButton()
configureSystemDetailDisclosureButton()
configureImageButton()
configureAttributedTextSystemButton()
}
// MARK: - Configuration
func configureSystemTextButton() {
let buttonTitle = NSLocalizedString("Button", comment: "")
systemTextButton.setTitle(buttonTitle, for: .normal)
systemTextButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureSystemContactAddButton() {
systemContactAddButton.backgroundColor = UIColor.clear
systemContactAddButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureSystemDetailDisclosureButton() {
systemDetailDisclosureButton.backgroundColor = UIColor.clear
systemDetailDisclosureButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureImageButton() {
// To create this button in code you can use `UIButton.init(type: .system)`.
// Remove the title text.
imageButton.setTitle("", for: .normal)
imageButton.tintColor = UIColor(named: "Tint_Purple_Color")
let imageButtonNormalImage = #imageLiteral(resourceName: "x_icon")
imageButton.setImage(imageButtonNormalImage, for: .normal)
// Add an accessibility label to the image.
imageButton.accessibilityLabel = NSLocalizedString("X Button", comment: "")
imageButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureAttributedTextSystemButton() {
let buttonTitle = NSLocalizedString("Button", comment: "")
// Set the button's title for normal state.
let normalTitleAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: UIColor(named: "Tint_Blue_Color")!,
NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue
]
let normalAttributedTitle = NSAttributedString(string: buttonTitle, attributes: normalTitleAttributes)
attributedTextButton.setAttributedTitle(normalAttributedTitle, for: .normal)
// Set the button's title for highlighted state.
let highlightedTitleAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.thick.rawValue
] as [NSAttributedString.Key : Any]
let highlightedAttributedTitle = NSAttributedString(string: buttonTitle, attributes: highlightedTitleAttributes)
attributedTextButton.setAttributedTitle(highlightedAttributedTitle, for: .highlighted)
attributedTextButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
// MARK: - Actions
@objc
func buttonClicked(_ sender: UIButton) {
print("A button was clicked: \(sender).")
}
}
| 37.645455 | 132 | 0.719633 |
dec86c98569a5ebc7c01457f982ce1a2493ff72a | 1,078 | // Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
struct CasdoorResponse<D1,D2>: Decodable where D1:Decodable,D2:Decodable {
let status: String
let msg: String
let data: D1?
let data2: D2?
func isOk() throws {
if status == "error" {
throw CasdoorError.init(error: .responseMessage(msg))
}
}
}
typealias CasdoorOneDataResponse<D:Decodable> = CasdoorResponse<D,String>
typealias CasdoorNoDataResponse = CasdoorResponse<String,String>
| 33.6875 | 75 | 0.719852 |
d9617ff70d182b5ca4cfe424a1403a9cd1ec4345 | 1,350 | //
// AppDelegate.swift
// TextFieldDelegate
//
// Created by 양승현 on 2022/01/22.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.486486 | 179 | 0.746667 |
09caad119fbbbd7aa8423c0d560678f89f83c46c | 1,432 | import UIKit
// This is not mutating
let testString = "This is a test string"
var testStringReplacedOccurences = testString.replacingOccurrences(of: "is",
with: "*")
print("testStringReplacedOccurences: ", testStringReplacedOccurences)
// OUTPUT: Th* * a test string
// https://developer.apple.com/documentation/foundation/nsregularexpression
var testStringOccurences2 = testString.replacingOccurrences(of: #"\bis"#,
with: "was",
options: .regularExpression,
range: nil)
print("testStringOccurences2: ", testStringOccurences2)
// OUTPUT: This was a test string
if let range = testString.range(of: "is") {
let testString2 = testString.replacingCharacters(in: range,
with: "at")
print("testString2: ", testString2)
// OUTPUT: That is a test string
}
// Mutating
var substringReplace = "Replace a substring"
let endIndex = substringReplace.index(substringReplace.startIndex,
offsetBy: 8)
substringReplace.replaceSubrange(...endIndex,
with: "Replaced the")
print("substringReplace", substringReplace)
// OUTPUT: Replaced the substring
| 36.717949 | 88 | 0.560754 |
1175e76e05c142ccf75997d126010f3eed8e9305 | 1,640 | //
// AppDelegate.swift
// compositional-layouts-kit
//
// Created by Astemir Eleev on 19/06/2019.
// Copyright © 2019 Astemir Eleev. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 39.047619 | 179 | 0.75 |
1d94f82befc7696627a4c92595d06ae29e4db403 | 5,327 | //
// MTKView.swift
// IBDecodable
//
// Created by phimage on 01/04/2018.
//
import SWXMLHash
public struct MTKView: IBDecodable, ViewProtocol, IBIdentifiable {
public let id: String
public let elementClass: String = "MTKView"
public let key: String?
public let autoresizingMask: AutoresizingMask?
public let clipsSubviews: Bool?
public let constraints: [Constraint]?
public let contentMode: String?
public let customClass: String?
public let customModule: String?
public let customModuleProvider: String?
public let userLabel: String?
public let colorLabel: String?
public let isMisplaced: Bool?
public let isAmbiguous: Bool?
public let verifyAmbiguity: VerifyAmbiguity?
public let opaque: Bool?
public let rect: Rect?
public let subviews: [AnyView]?
public let translatesAutoresizingMaskIntoConstraints: Bool?
public let userInteractionEnabled: Bool?
public let viewLayoutGuide: LayoutGuide?
public let userDefinedRuntimeAttributes: [UserDefinedRuntimeAttribute]?
public let connections: [AnyConnection]?
public let variations: [Variation]?
public let backgroundColor: Color?
public let tintColor: Color?
public let isHidden: Bool?
public let alpha: Float?
enum ConstraintsCodingKeys: CodingKey { case constraint }
enum VariationCodingKey: CodingKey { case variation }
enum ExternalCodingKeys: CodingKey { case color }
enum ColorsCodingKeys: CodingKey { case key }
static func decode(_ xml: XMLIndexerType) throws -> MTKView {
let container = xml.container(keys: MappedCodingKey.self).map { (key: CodingKeys) in
let stringValue: String = {
switch key {
case .isMisplaced: return "misplaced"
case .isAmbiguous: return "ambiguous"
case .isHidden: return "hidden"
default: return key.stringValue
}
}()
return MappedCodingKey(stringValue: stringValue)
}
let constraintsContainer = container.nestedContainerIfPresent(of: .constraints, keys: ConstraintsCodingKeys.self)
let variationContainer = xml.container(keys: VariationCodingKey.self)
let colorsContainer = xml.container(keys: ExternalCodingKeys.self)
.nestedContainerIfPresent(of: .color, keys: ColorsCodingKeys.self)
return MTKView(
id: try container.attribute(of: .id),
key: container.attributeIfPresent(of: .key),
autoresizingMask: container.elementIfPresent(of: .autoresizingMask),
clipsSubviews: container.attributeIfPresent(of: .clipsSubviews),
constraints: constraintsContainer?.elementsIfPresent(of: .constraint),
contentMode: container.attributeIfPresent(of: .contentMode),
customClass: container.attributeIfPresent(of: .customClass),
customModule: container.attributeIfPresent(of: .customModule),
customModuleProvider: container.attributeIfPresent(of: .customModuleProvider),
userLabel: container.attributeIfPresent(of: .userLabel),
colorLabel: container.attributeIfPresent(of: .colorLabel),
isMisplaced: container.attributeIfPresent(of: .isMisplaced),
isAmbiguous: container.attributeIfPresent(of: .isAmbiguous),
verifyAmbiguity: container.attributeIfPresent(of: .verifyAmbiguity),
opaque: container.attributeIfPresent(of: .opaque),
rect: container.elementIfPresent(of: .rect),
subviews: container.childrenIfPresent(of: .subviews),
translatesAutoresizingMaskIntoConstraints: container.attributeIfPresent(of: .translatesAutoresizingMaskIntoConstraints),
userInteractionEnabled: container.attributeIfPresent(of: .userInteractionEnabled),
viewLayoutGuide: container.elementIfPresent(of: .viewLayoutGuide),
userDefinedRuntimeAttributes: container.childrenIfPresent(of: .userDefinedRuntimeAttributes),
connections: container.childrenIfPresent(of: .connections),
variations: variationContainer.elementsIfPresent(of: .variation),
backgroundColor: colorsContainer?.withAttributeElement(.key, CodingKeys.backgroundColor.stringValue),
tintColor: colorsContainer?.withAttributeElement(.key, CodingKeys.tintColor.stringValue),
isHidden: container.attributeIfPresent(of: .isHidden),
alpha: container.attributeIfPresent(of: .alpha)
)
}
}
| 56.670213 | 139 | 0.600526 |
01536c119ed97d44ae8d52462a6876f2623fd680 | 1,202 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import UIKit
import EssentialFeed
final class WeakRefVirtualProxy<T: AnyObject> {
private weak var object: T?
init(_ object: T) {
self.object = object
}
}
extension WeakRefVirtualProxy: FeedErrorView where T: FeedErrorView {
func display(_ viewModel: FeedErrorViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: FeedLoadingView where T: FeedLoadingView {
func display(_ viewModel: FeedLoadingViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: FeedImageView where T: FeedImageView, T.Image == UIImage {
func display(_ model: FeedImageViewModel<UIImage>) {
object?.display(model)
}
}
extension WeakRefVirtualProxy: CommentLoadingView where T: CommentLoadingView {
func display(_ viewModel: CommentLoadingViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: CommentView where T: CommentView {
func display(_ viewModel: CommentViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: CommentErrorView where T: CommentErrorView {
func display(_ viewModel: CommentErrorViewModel) {
object?.display(viewModel)
}
}
| 23.568627 | 89 | 0.772047 |
7236dffcfa28193f8fd9abd449287fbba622b05b | 1,878 | //
// GYReaderModel.swift
// Reader
//
// Created by CQSC on 16/7/17.
// Copyright © 2016年 CQSC. All rights reserved.
//
import UIKit
class GYReaderModel: MQIBaseModel {
var bid: String = ""
var bookChapterIndex: Int = 0
var bookChapterPage: Int = 0
var bookChapterTitle: String = ""
var bookPageMode: Bool = false
var bookTitle: String = ""
var bookCover: String = ""
override init() {
super.init()
}
required init(jsonDict: [String : Any]) {
super.init(jsonDict: jsonDict)
}
required init?(response: HTTPURLResponse, representation: Any) {
super.init(response: response, representation: representation)
}
required init(coder aDecoder: NSCoder){
super.init()
bid = decodeStringForKey(aDecoder, key: "bookId")
bookChapterIndex = decodeIntForKey(aDecoder, key: "chapterIndex") < 0 ? 0 : decodeIntForKey(aDecoder, key: "chapterIndex")
bookChapterPage = decodeIntForKey(aDecoder, key: "chapterPage") < 0 ? 0 : decodeIntForKey(aDecoder, key: "chapterPage")
bookPageMode = decodeBoolForKey(aDecoder, key: "bookPageMode_new")
bookChapterTitle = decodeStringForKey(aDecoder, key: "bookChapterTitle")
bookTitle = decodeStringForKey(aDecoder, key: "bookTitle")
bookCover = decodeStringForKey(aDecoder, key: "bookCover")
}
override func encode(with aCoder: NSCoder) {
aCoder.encode(bid, forKey: "bookId")
aCoder.encode(bookChapterIndex, forKey: "chapterIndex")
aCoder.encode(bookChapterPage, forKey: "chapterPage")
aCoder.encode(bookPageMode, forKey: "bookPageMode_new")
aCoder.encode(bookChapterTitle, forKey: "bookChapterTitle")
aCoder.encode(bookTitle, forKey: "bookTitle")
aCoder.encode(bookCover, forKey: "bookCover")
}
}
| 32.947368 | 130 | 0.658147 |
480d7e2874bc0c48fc6815898cc5889ace0ce82a | 1,746 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//819. Most Common Word
//Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
//Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
//Example:
//Input:
//paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
//banned = ["hit"]
//Output: "ball"
//Explanation:
//"hit" occurs 3 times, but it is a banned word.
//"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
//Note that words in the paragraph are not case sensitive,
//that punctuation is ignored (even if adjacent to words, such as "ball,"),
//and that "hit" isn't the answer even though it occurs more because it is banned.
// Note:
//1 <= paragraph.length <= 1000.
//1 <= banned.length <= 100.
//1 <= banned[i].length <= 10.
//The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
//paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
//Different words in paragraph are always separated by a space.
//There are no hyphens or hyphenated words.
//Words only consist of letters, never apostrophes or other punctuation symbols.
//
//class Solution {
// func mostCommonWord(_ paragraph: String, _ banned: [String]) -> String {
// }
//}
// Time Is Money | 49.885714 | 213 | 0.729668 |
c1f55e84df1b3cc282a004e42f05d93cf44db5ae | 5,271 | //
// SignUpViewController.swift
// SeeFood
//
// Created by Thiago Hissa on 2017-08-09.
// Copyright © 2017 Errol Thiago. All rights reserved.
//
import UIKit
import Stevia
class SignUpViewController: UIViewController {
//MARK: Properties
@IBOutlet weak var myWebView: UIWebView!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var signupButton: UIButton!
let alertController = UIAlertController(title: "Sign Up Error", message: "", preferredStyle: UIAlertControllerStyle.alert)
override func viewDidLoad() {
super.viewDidLoad()
//MARK: Background Animation
let htmlPath = Bundle.main.path(forResource: "WebViewContent", ofType: "html")
let htmlURL = URL(fileURLWithPath: htmlPath!)
let html = try? Data(contentsOf: htmlURL)
self.myWebView.load(html!, mimeType: "text/html", textEncodingName: "UTF-8", baseURL: htmlURL.deletingLastPathComponent())
self.myWebView.isHidden = true
//MARK: Styles
signupButton.layer.cornerRadius = 20
let border1 = CALayer()
let border2 = CALayer()
let border3 = CALayer()
border1.borderColor = UIColor.white.withAlphaComponent(0.6).cgColor
border1.frame = CGRect(x: 0, y: usernameTextField.frame.size.height - 2.0, width: usernameTextField.frame.size.width, height: usernameTextField.frame.size.height)
border2.borderColor = UIColor.white.withAlphaComponent(0.6).cgColor
border2.frame = CGRect(x: 0, y: usernameTextField.frame.size.height - 2.0, width: usernameTextField.frame.size.width, height: usernameTextField.frame.size.height)
border3.borderColor = UIColor.white.withAlphaComponent(0.6).cgColor
border3.frame = CGRect(x: 0, y: usernameTextField.frame.size.height - 2.0, width: usernameTextField.frame.size.width, height: usernameTextField.frame.size.height)
border1.borderWidth = 0.7
border2.borderWidth = 0.7
border3.borderWidth = 0.7
usernameTextField.layer.addSublayer(border1)
usernameTextField.layer.masksToBounds = true
passwordTextField.layer.addSublayer(border2)
passwordTextField.layer.masksToBounds = true
emailTextField.layer.masksToBounds = true
emailTextField.layer.addSublayer(border3)
usernameTextField.layer.cornerRadius = 5
passwordTextField.layer.cornerRadius = 5
emailTextField.layer.cornerRadius = 5
usernameTextField.attributedPlaceholder = NSAttributedString(string:"Username",
attributes: [NSForegroundColorAttributeName: UIColor.white.withAlphaComponent(0.2)])
passwordTextField.attributedPlaceholder = NSAttributedString(string:"Password",
attributes: [NSForegroundColorAttributeName: UIColor.white.withAlphaComponent(0.2)])
emailTextField.attributedPlaceholder = NSAttributedString(string:"Email",
attributes: [NSForegroundColorAttributeName: UIColor.white.withAlphaComponent(0.2)])
//UIAlertController Button
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
//Dismiss Controller
let dismissLoginButton = UIButton()
dismissLoginButton.setImage(UIImage(named:"x-icon.png"), for: .normal)
dismissLoginButton.sizeToFit()
dismissLoginButton.tap { self.dismiss(animated: true, completion: nil) }
view.sv(dismissLoginButton)
view.layout(
UIApplication.shared.statusBarFrame.height + 10,
dismissLoginButton.width(30)-12-| ~ 30
)
}
//MARK: IBActions
@IBAction func signupButton(_ sender: UIButton) {
self.myWebView.isHidden = false
if (usernameTextField.text?.isEmpty)! || (passwordTextField.text?.isEmpty)! || (emailTextField.text?.isEmpty)! {
print("Error: Empty textfields")
}
else {
ParseManager.shared.userSignUp(username: usernameTextField.text!, password: passwordTextField.text!, email: emailTextField.text!) { (result:String?) in
guard let result = result else
{
OperationQueue.main.addOperation({
self.performSegue(withIdentifier: "unwindSegueToMain", sender: nil)
})
return
}
self.alertController.message = result
self.myWebView.isHidden = true
OperationQueue.main.addOperation({
self.present(self.alertController, animated: true, completion: nil)
})
}
}
// self.myWebView.isHidden = false
// DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
// self.performSegue(withIdentifier: "SegueToMain", sender: nil)
// })
}
@IBAction func loginButtonDismissView(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| 39.044444 | 169 | 0.650541 |
f7a9f3a383505121692f4a8adadf9989684a276c | 7,902 | //
// ImageViewController.swift
// ImageViewer
//
// Created by Kristian Angyal on 01/08/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
import AVFoundation
extension VideoView: ItemView {}
class VideoViewController: ItemBaseController<VideoView> {
fileprivate let swipeToDismissFadeOutAccelerationFactor: CGFloat = 6
let fetchURL: FetchURLBlock
var videoURL: URL?
var player: AVPlayer?
unowned let scrubber: VideoScrubber
let fullHDScreenSizeLandscape = CGSize(width: 1920, height: 1080)
let fullHDScreenSizePortrait = CGSize(width: 1080, height: 1920)
let embeddedPlayButton = UIButton.circlePlayButton(70)
private var autoPlayStarted: Bool = false
private var autoPlayEnabled: Bool = false
private var isObservePlayer: Bool = false
init(index: Int, itemCount: Int, fetchImageBlock: @escaping FetchImageBlock, videoURL: @escaping FetchURLBlock, scrubber: VideoScrubber, configuration: GalleryConfiguration, isInitialController: Bool = false) {
self.fetchURL = videoURL
self.scrubber = scrubber
///Only those options relevant to the paging VideoViewController are explicitly handled here, the rest is handled by ItemViewControllers
for item in configuration {
switch item {
case .videoAutoPlay(let enabled):
autoPlayEnabled = enabled
default: break
}
}
super.init(index: index, itemCount: itemCount, fetchImageBlock: fetchImageBlock, configuration: configuration, isInitialController: isInitialController)
self.fetchURL { [weak self] url in
//TODO: Display video unavailable video=)
guard let url = url else { return }
self?.videoURL = url
self?.player = AVPlayer(url: url)
guard let welf = self else { return }
welf.player?.addObserver(welf, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
welf.player?.addObserver(welf, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
welf.isObservePlayer = true
welf.scrubber.player = welf.player
if welf.itemView.player == nil {
welf.itemView.player = welf.player
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if isInitialController == true { embeddedPlayButton.alpha = 0 }
embeddedPlayButton.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
self.view.addSubview(embeddedPlayButton)
embeddedPlayButton.center = self.view.boundsCenter
embeddedPlayButton.addTarget(self, action: #selector(playVideoEmbedButtonTapped), for: UIControlEvents.touchUpInside)
self.itemView.player = player
self.itemView.contentMode = .scaleAspectFill
self.scrubber.onDidChangePlaybackState = { [weak self] _ in
self?.updateEmbeddedPlayButtonVisibility()
}
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.beginReceivingRemoteControlEvents()
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
UIApplication.shared.endReceivingRemoteControlEvents()
super.viewWillDisappear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
performAutoPlay()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.player?.pause()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let isLandscape = itemView.bounds.width >= itemView.bounds.height
itemView.bounds.size = aspectFitSize(forContentOfSize: isLandscape ? fullHDScreenSizeLandscape : fullHDScreenSizePortrait, inBounds: self.scrollView.bounds.size)
itemView.center = scrollView.boundsCenter
}
override func scrollViewDidSingleTap() {
switchPlayblackState()
}
private func switchPlayblackState() {
switch scrubber.playbackState {
case .paused: scrubber.play()
case .finished: scrubber.replay()
case .playing: scrubber.pause()
}
}
private func updateEmbeddedPlayButtonVisibility() {
embeddedPlayButton.alpha = scrubber.playbackState == .playing ? 0.0 : 1.0
}
@objc func playVideoEmbedButtonTapped() {
switchPlayblackState()
}
override func closeDecorationViews(_ duration: TimeInterval) {
UIView.animate(withDuration: duration, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
self?.itemView.previewImageView.alpha = 1
})
}
override func presentItem(alongsideAnimation: () -> Void, completion: @escaping () -> Void) {
let circleButtonAnimation = {
UIView.animate(withDuration: 0.15, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 1
})
}
super.presentItem(alongsideAnimation: alongsideAnimation) {
circleButtonAnimation()
completion()
}
}
override func displacementTargetSize(forSize size: CGSize) -> CGSize {
let isLandscape = itemView.bounds.width >= itemView.bounds.height
return aspectFitSize(forContentOfSize: isLandscape ? fullHDScreenSizeLandscape : fullHDScreenSizePortrait, inBounds: rotationAdjustedBounds().size)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" || keyPath == "status" {
fadeOutEmbeddedPlayButton()
}
else if keyPath == "contentOffset" {
handleSwipeToDismissTransition()
}
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
func handleSwipeToDismissTransition() {
guard let _ = swipingToDismiss else { return }
embeddedPlayButton.center.y = view.center.y - scrollView.contentOffset.y
}
func fadeOutEmbeddedPlayButton() {
if player?.isPlaying() == true && embeddedPlayButton.alpha != 0 {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
})
}
}
override func remoteControlReceived(with event: UIEvent?) {
if let event = event {
if event.type == UIEventType.remoteControl {
switch event.subtype {
case .remoteControlTogglePlayPause:
if self.player?.isPlaying() == true {
self.player?.pause()
}
else {
self.player?.play()
}
case .remoteControlPause:
self.player?.pause()
case .remoteControlPlay:
self.player?.play()
case .remoteControlPreviousTrack:
self.player?.pause()
self.player?.seek(to: CMTime(value: 0, timescale: 1))
self.player?.play()
default:
break
}
}
}
}
private func performAutoPlay() {
guard autoPlayEnabled else { return }
guard autoPlayStarted == false else { return }
autoPlayStarted = true
embeddedPlayButton.isHidden = true
scrubber.play()
}
}
| 30.747082 | 214 | 0.626424 |
4804c83864b7aaf975f89ca2fc359197851e0f57 | 296 | //: [Previous](@previous)
import Swiftz
struct Fib<A, B, FB> : Functor {
func fmap(f: Int -> Int) -> Fib {
return fmap(f)
}
init<M: Monad where M.A == A, M.B == B, M.FB == FB>(_ t:M) {
}
}
let a = Fib(Optional(0.0))
print("Finished")
//: [Next](@next)
| 14.095238 | 64 | 0.486486 |
6abe146ea46bd1cb64e077876b2dd45b7b7abbc5 | 618 | //
// Data+Int.swift
// CryptoKit
//
// Created by Chris Amanse on 29/08/2016.
//
//
import Foundation
extension Data {
init<T: FixedWidthInteger>(from value: T) {
let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer {
// valuePointer.deallocate(capacity: 1)
valuePointer.deallocate()
}
valuePointer.pointee = value
let bytesPointer = valuePointer.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<UInt8>.size) { $0 }
self.init(bytes: bytesPointer, count: MemoryLayout<T>.size)
}
}
| 23.769231 | 116 | 0.613269 |
089cc307c6434f1517f84ca5a73124ea2fc47e09 | 4,132 | import Core
import NIO
import AsyncHTTPClient
import Foundation
public protocol TopicsAPI {
/// Gets the configuration of a topic.
///
/// - parameter `topicId`: Name of the topic
/// - returns: If successful, the response body contains an instance of `Topic`.
func get(topicId: String) -> EventLoopFuture<GoogleCloudPubSubTopic>
/// Lists matching topics.
///
/// - parameter `pageSize`: Maximum number of topics to return.
/// `pageToken`: The value returned by the last ListTopicsResponse; indicates that this is a
/// continuation of a prior topics.list call, and that the system should return the next page of data
/// - returns: Returns a list of topics and the `nextPageToken`
func list(pageSize: Int?, pageToken: String?) -> EventLoopFuture<GooglePubSubListTopicResponse>
/// Adds one or more messages to the topic.
///
/// - parameter `topidId`: Name of the topic
/// `data`: Data to be passed in the message
/// `attributes`: Attributes for this message
/// `orderingKey`: Identifies related messages for which publish order should be respected
/// - returns: Returns an array of `messageId`. `MessageId` is the server-assigned ID of each published message, in the same order as the messages in the request. IDs are guaranteed to be unique within the topic.
func publish(topicId: String, data: String, attributes: [String: String]?, orderingKey: String?) -> EventLoopFuture<GoogleCloudPublishResponse>
/// Lists the names of the attached subscriptions on this topic.
func getSubscriptionsList(topicId: String, pageSize: Int?, pageToken: String?) -> EventLoopFuture<GooglePubSubTopicSubscriptionListResponse>
}
public final class GoogleCloudPubSubTopicsAPI: TopicsAPI {
let endpoint: String
let request: GoogleCloudPubSubRequest
let encoder = JSONEncoder()
init(request: GoogleCloudPubSubRequest,
endpoint: String) {
self.request = request
self.endpoint = endpoint
}
public func get(topicId: String) -> EventLoopFuture<GoogleCloudPubSubTopic> {
return request.send(method: .GET, path: "\(endpoint)/v1/projects/\(request.project)/topics/\(topicId)")
}
public func list(pageSize: Int?, pageToken: String?) -> EventLoopFuture<GooglePubSubListTopicResponse> {
var query = "pageSize=\(pageSize ?? 10)"
if let pageToken = pageToken {
query.append(contentsOf: "&pageToken=\(pageToken)")
}
return request.send(method: .GET,
path: "\(endpoint)/v1/projects/\(request.project)/topics",
query: query)
}
public func publish(topicId: String, data: String, attributes: [String: String]?, orderingKey: String?) -> EventLoopFuture<GoogleCloudPublishResponse> {
do {
let message = GoogleCloudPubSubMessage(data: data, attributes: attributes, orderingKey: orderingKey)
let publishRequest = GoogleCloudPublishRequest(messages: [message])
let body = try HTTPClient.Body.data(encoder.encode(publishRequest))
let path = "\(endpoint)/v1/projects/\(request.project)/topics/\(topicId):publish"
print("<<<--- Publish on: \(path) --->")
return request.send(method: .POST,
path: path,
body: body)
} catch {
return request.eventLoop.makeFailedFuture(error)
}
}
public func getSubscriptionsList(topicId: String, pageSize: Int?, pageToken: String?) -> EventLoopFuture<GooglePubSubTopicSubscriptionListResponse> {
var query = "pageSize=\(pageSize ?? 10)"
if let pageToken = pageToken {
query.append(contentsOf: "&pageToken=\(pageToken)")
}
return request.send(method: .GET,
path: "\(endpoint)/v1/projects/\(request.project)/topics/subscriptions",
query: query)
}
}
| 46.954545 | 216 | 0.635286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.