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
|
---|---|---|---|---|---|
185d2b723b46d3161b1bdd88a0221d7a798a8b98 | 10,068 | //
// SessionDetailViewController.swift
// MyTouch
//
// Created by Tommy Lin on 2019/1/16.
// Copyright © 2019 NTU HCI Lab. All rights reserved.
//
import UIKit
class SessionDetailViewController: UIViewController {
var session: Session? {
didSet {
if let session = session {
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byWordWrapping
style.lineSpacing = 8.0
style.alignment = .center
let attrs = [
NSAttributedString.Key.paragraphStyle: style,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15, weight: .regular)
]
let formatter = DateFormatter()
formatter.calendar = Calendar.current
formatter.timeZone = TimeZone.current
formatter.dateStyle = .long
let dateString = formatter.string(from: session.start)
briefLabel.attributedText = NSAttributedString(string: "\(dateString)\n Tommy’s iPhone", attributes: attrs)
}
tableView.reloadData()
}
}
let topShadowView = UIView()
let backgroundView = UIView()
let briefLabel = UILabel()
let tableView = UITableView(frame: .zero, style: .plain)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
backgroundView.backgroundColor = UIColor(hex: 0x00b894)
topShadowView.backgroundColor = UIColor(white: 0.0, alpha: 0.15)
briefLabel.numberOfLines = 0
tableView.cellLayoutMarginsFollowReadableWidth = true
tableView.register(AccomodationCell.self, forCellReuseIdentifier: "accomodation")
tableView.register(SessionInfoCell.self, forCellReuseIdentifier: "info")
tableView.separatorStyle = .none
tableView.estimatedRowHeight = 100
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundView = nil
tableView.backgroundColor = .clear
tableView.contentInset.top = 80
tableView.contentInset.bottom = 20
view.addSubview(backgroundView)
view.addSubview(briefLabel)
view.addSubview(tableView)
view.addSubview(topShadowView)
backgroundView.translatesAutoresizingMaskIntoConstraints = false
briefLabel.translatesAutoresizingMaskIntoConstraints = false
tableView.translatesAutoresizingMaskIntoConstraints = false
topShadowView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
briefLabel.topAnchor.constraint(equalToSystemSpacingBelow: view.topAnchor, multiplier: 1.0),
briefLabel.leftAnchor.constraint(equalTo: view.leftAnchor),
briefLabel.rightAnchor.constraint(equalTo: view.rightAnchor),
briefLabel.heightAnchor.constraint(equalToConstant: 60),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
backgroundView.topAnchor.constraint(equalTo: view.topAnchor),
backgroundView.leftAnchor.constraint(equalTo: view.leftAnchor),
backgroundView.rightAnchor.constraint(equalTo: view.rightAnchor),
backgroundView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1/3),
topShadowView.topAnchor.constraint(equalTo: view.topAnchor),
topShadowView.leftAnchor.constraint(equalTo: view.leftAnchor),
topShadowView.rightAnchor.constraint(equalTo: view.rightAnchor),
topShadowView.heightAnchor.constraint(equalToConstant: 1)
])
topShadowView.alpha = 0.0
}
@objc private func handleAccomodationButton(sender: UIButton) {
guard let session = session else {
return
}
switch session.state {
case .local:
let homeTabBarController = tabBarController as? HomeTabBarController
homeTabBarController?.uploadSession(session) { [weak self] (session, error) in
if let session = session {
self?.session = session
}
}
case .completed:
presentGoToSettings()
default:
break
}
}
private func presentGoToSettings() {
let viewController = SettingsStepByStepViewController()
viewController.modalPresentationStyle = .custom
viewController.transitioningDelegate = self
present(viewController, animated: true, completion: nil)
}
}
extension SessionDetailViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return session != nil ? 3 : 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "accomodation", for: indexPath) as! AccomodationCell
if let session = session {
cell.session = session
}
/*cell.button.addTarget(self, action: #selector(handleAccomodationButton(sender:)), for: .touchUpInside)*/
cell.layoutItemViews()
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as! SessionInfoCell
cell.titleLabel.text = NSLocalizedString("DEVICE_INFO_TITLE", comment: "")
if let deviceInfo = session?.deviceInfo {
cell.items = [
SessionInfoCell.Item(title: NSLocalizedString("DEVICE_INFO_DEVICE_NAME", comment: ""), text: deviceInfo.name),
SessionInfoCell.Item(title: NSLocalizedString("DEVICE_INFO_MODEL_NAME", comment: ""), text: deviceInfo.model),
SessionInfoCell.Item(title: NSLocalizedString("DEVICE_INFO_MANUFACTURER", comment: ""), text: deviceInfo.manufacturer),
SessionInfoCell.Item(title: NSLocalizedString("DEVICE_INFO_OS_VERSION", comment: ""), text: "\(deviceInfo.platform) \(deviceInfo.osVersion)"),
SessionInfoCell.Item(title: NSLocalizedString("DEVICE_INFO_APP_VERSION", comment: ""), text: deviceInfo.appVersion)
]
}
cell.layoutItemViews()
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as! SessionInfoCell
cell.titleLabel.text = NSLocalizedString("SUBJECT_INFO_TITLE", comment: "")
// TODO: symptoms
if let subject = session?.subject {
cell.items = [
SessionInfoCell.Item(title: NSLocalizedString("SUBJECT_INFO_SITUATION", comment: ""), text: subject.situation),
SessionInfoCell.Item(title: NSLocalizedString("SUBJECT_INFO_BIRTH_YEAR", comment: ""), text: "\(subject.birthYear)"),
SessionInfoCell.Item(title: NSLocalizedString("SUBJECT_INFO_GENDER", comment: ""), text: subject.gender.localizedString),
SessionInfoCell.Item(title: NSLocalizedString("SUBJECT_INFO_DOMINANT_HAND", comment: ""), text: subject.dominantHand.localizedString),
SessionInfoCell.Item(title: NSLocalizedString("SUBJECT_INFO_IMPAIRMENT", comment: ""), text: subject.impairment.localizedString),
SessionInfoCell.Item(title: NSLocalizedString("SUBJECT_INFO_SYMPTOMS", comment: ""), text: subject.symptomStrings.joined(separator: ", ")),
]
}
cell.layoutItemViews()
return cell
default:
fatalError()
}
}
}
extension SessionDetailViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if abs(scrollView.contentOffset.y) < scrollView.contentInset.top {
let scale = max(abs(scrollView.contentOffset.y) / scrollView.contentInset.top, 0)
briefLabel.transform = CGAffineTransform(translationX: 0, y: -40 * (1 - scale)).scaledBy(x: 0.5 + scale/2, y: 0.5 + scale/2)
briefLabel.alpha = scale
} else if scrollView.contentOffset.y > 0 {
briefLabel.alpha = 0.0
} else {
briefLabel.transform = .identity
briefLabel.alpha = 1.0
}
UIView.animate(withDuration: 0.15, delay: 0.0, options: [.beginFromCurrentState], animations: {
self.topShadowView.alpha = scrollView.contentOffset.y > 0 ? 1.0 : 0.0
}, completion: nil)
}
}
extension SessionDetailViewController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
if presented is SettingsStepByStepViewController {
let presentation = CenterModalPresentationController(presentedViewController: presented, presenting: presenting)
presentation.tapToDismiss = true
return presentation
}
return nil
}
}
| 43.025641 | 162 | 0.630115 |
dbde7fbef88d54dae32cd2c8e1ef37943b602bde | 4,830 | import XCTest
import BraintreeDataCollector
import BraintreeTestShared
class BTDataCollector_Tests: XCTestCase {
func testSetFraudMerchantID_overridesMerchantID() {
let config = [
"environment":"development",
"kount": [
"kountMerchantId": "500000"
]
] as [String : Any]
let mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: config)
let dataCollector = BTDataCollector(apiClient: mockAPIClient)
dataCollector.setFraudMerchantID("500001")
let expectation = self.expectation(description: "Returns fraud data")
dataCollector.collectDeviceData { (deviceData: String) in
let json = BTJSON(data: deviceData.data(using: String.Encoding.utf8)!)
XCTAssertEqual((json["fraud_merchant_id"] as AnyObject).asString(), "500001")
XCTAssert((json["device_session_id"] as AnyObject).asString()!.count >= 32)
XCTAssert((json["correlation_id"] as AnyObject).asString()!.count > 0)
expectation.fulfill()
}
waitForExpectations(timeout: 2, handler: nil)
}
func testCollectDeviceData_whenMerchantConfiguredForKount_collectsAllData() {
let config = [
"environment": "development" as AnyObject,
"kount": [
"kountMerchantId": "500000"
]
] as [String : Any]
let mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: config)
let dataCollector = BTDataCollector(apiClient: mockAPIClient)
let expectation = self.expectation(description: "Returns fraud data")
dataCollector.collectDeviceData { deviceData in
let json = BTJSON(data: deviceData.data(using: String.Encoding.utf8)!)
XCTAssertEqual((json["fraud_merchant_id"] as AnyObject).asString(), "500000")
XCTAssert((json["device_session_id"] as AnyObject).asString()!.count >= 32)
XCTAssert((json["correlation_id"] as AnyObject).asString()!.count > 0)
expectation.fulfill()
}
waitForExpectations(timeout: 2, handler: nil)
}
func testCollectDeviceData_whenMerchantConfiguredForKount_setsMerchantIDOnKount() {
let config = [
"environment": "sandbox",
"kount": [
"kountMerchantId": "500000"
]
] as [String : Any]
let mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: config)
let dataCollector = BTDataCollector(apiClient: mockAPIClient)
let stubKount = FakeDeviceCollectorSDK()
dataCollector.kount = stubKount
let expectation = self.expectation(description: "Returns fraud data")
dataCollector.collectDeviceData { _ in
expectation.fulfill()
}
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(500000, stubKount.merchantID)
XCTAssertEqual(KEnvironment.test, stubKount.environment)
}
func testCollectDeviceData_whenMerchantNotConfiguredForKount_doesNotCollectKountData() {
let config = [
"environment": "development",
"kount": [
"kountMerchantId": nil
]
] as [String : Any]
let mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: config)
let dataCollector = BTDataCollector(apiClient: mockAPIClient)
let expectation = self.expectation(description: "Returns fraud data")
dataCollector.collectDeviceData { deviceData in
let json = BTJSON(data: deviceData.data(using: String.Encoding.utf8)!)
XCTAssertNil(json["fraud_merchant_id"].asString())
XCTAssertNil(json["device_session_id"].asString())
XCTAssert((json["correlation_id"] as AnyObject).asString()!.count > 0)
expectation.fulfill()
}
waitForExpectations(timeout: 2, handler: nil)
}
}
class FakeDeviceCollectorSDK: KDataCollector {
var lastCollectSessionID: String?
var forceError = false
override func collect(forSession sessionID: String, completion completionBlock: ((String, Bool, Error?) -> Void)? = nil) {
lastCollectSessionID = sessionID
if forceError {
completionBlock?("1981", false, NSError(domain: "Fake", code: 1981, userInfo: nil))
} else {
completionBlock?(sessionID, true, nil)
}
}
}
| 39.268293 | 126 | 0.649068 |
38c00ee9efe2e648e4305429337fa7db4464eb8a | 456 | //
// ResultCallback.swift
// RCTWuji
//
// Created by 3 on 2020/12/7.
//
import Foundation
class ResultCallback: NSObject, Callback {
private var result: FlutterResult?
init(_ result: FlutterResult?) {
self.result = result
}
func success(_ data: Any?) {
result?(data)
}
func failure(_ code: String, _ message: String) {
result?(FlutterError.init(code: code, message: message, details: nil))
}
}
| 18.24 | 78 | 0.622807 |
390730839a612f1da892efe141b2d1f49e8c044c | 15,196 | // Copyright 2020 TensorFlow Authors
//
// 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 _Differentiation
import TensorFlow
typealias GradMapFn = (inout Tensor<Float>, Tensor<Float>, Int) -> Void
// A partially type erased base-class that essentially provides a
// WritableKeypath<Base, Child> + a TensorVisitorPlan<Child> and is used for
// doing the recursive walk over the structure tree.
class TensorVisitorPlanWrapperBase<Base> {
func appendKeyPaths<TrueBase>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ kps: inout [WritableKeyPath<TrueBase, Tensor<Float>>]
) {
fatalError("calling abstract function")
}
func findFirstIndex<TrueBase, T>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ prefix: WritableKeyPath<TrueBase, T>, _ i: inout Int
) -> Bool {
fatalError("calling abstract function")
}
func populateTensors(_ v: Base, _ tensors: inout [Tensor<Float>]) {
fatalError("calling abstract function")
}
func mapTensors(_ v1: inout Base, _ v2: Base, _ i: inout Int, _ fn: GradMapFn) {
fatalError("calling abstract function")
}
func populateMask<Base>(_ mask: inout [Bool], _ kp: WritableKeyPath<Base, Tensor<Float>>) {
fatalError("calling abstract function")
}
}
// The basic implementation of TensorVisitorPlanWrapperBase for normally extending
// keypaths.
final class TensorVisitorPlanWrapper<Base, Child>: TensorVisitorPlanWrapperBase<Base> {
var child: WritableKeyPath<Base, Child>
var childPlan: TensorVisitorPlan<Child>
init(child: WritableKeyPath<Base, Child>, childPlan: TensorVisitorPlan<Child>) {
self.child = child
self.childPlan = childPlan
}
override func appendKeyPaths<TrueBase>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ kps: inout [WritableKeyPath<TrueBase, Tensor<Float>>]
) {
childPlan.appendKeyPaths(rootKeyPath.appending(path: child), &kps)
}
override func populateTensors(_ v: Base, _ tensors: inout [Tensor<Float>]) {
childPlan.populateTensors(v[keyPath: child], &tensors)
}
override func mapTensors(_ v1: inout Base, _ v2: Base, _ i: inout Int, _ fn: GradMapFn) {
childPlan.mapTensors(&v1[keyPath: child], v2[keyPath: child], &i, fn)
}
override func populateMask<Base>(_ mask: inout [Bool], _ kp: WritableKeyPath<Base, Tensor<Float>>)
{
childPlan.populateMask(&mask, kp)
}
override func findFirstIndex<TrueBase, T>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ prefix: WritableKeyPath<TrueBase, T>, _ i: inout Int
) -> Bool {
childPlan.findFirstIndex(rootKeyPath.appending(path: child), prefix, &i)
}
}
// Faster implementation for iterating over nested arrays.
final class ArrayTensorVisitorPlanWrapper<Base, Child>: TensorVisitorPlanWrapperBase<Base> {
var child: WritableKeyPath<Base, [Child]>
var childPlans: [TensorVisitorPlan<Child>]
init(child: WritableKeyPath<Base, [Child]>, childPlans: [TensorVisitorPlan<Child>]) {
self.child = child
self.childPlans = childPlans
}
override func appendKeyPaths<TrueBase>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ kps: inout [WritableKeyPath<TrueBase, Tensor<Float>>]
) {
let childKp = rootKeyPath.appending(path: child)
for (i, childPlan) in childPlans.enumerated() {
childPlan.appendKeyPaths(childKp.appending(path: \[Child][i]), &kps)
}
}
override func populateTensors(_ v: Base, _ tensors: inout [Tensor<Float>]) {
let arr = v[keyPath: child]
for (i, childPlan) in childPlans.enumerated() {
childPlan.populateTensors(arr[i], &tensors)
}
}
override func mapTensors(_ v1: inout Base, _ v2: Base, _ i: inout Int, _ fn: GradMapFn) {
{ (arr1: inout [Child], arr2: [Child]) in
for (j, childPlan) in childPlans.enumerated() {
childPlan.mapTensors(&arr1[j], arr2[j], &i, fn)
}
}(&v1[keyPath: child], v2[keyPath: child])
}
override func populateMask<Base>(_ mask: inout [Bool], _ kp: WritableKeyPath<Base, Tensor<Float>>)
{
for childPlan in childPlans { childPlan.populateMask(&mask, kp) }
}
override func findFirstIndex<TrueBase, T>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ prefix: WritableKeyPath<TrueBase, T>, _ i: inout Int
) -> Bool {
let childKp = rootKeyPath.appending(path: child)
if childKp == prefix { return true }
for (j, childPlan) in childPlans.enumerated() {
let elementKp = childKp.appending(path: \[Child][j])
if elementKp == prefix || childPlan.findFirstIndex(elementKp, prefix, &i) {
return true
}
}
return childKp.appending(path: \[Child][childPlans.count]) == prefix
}
}
// Faster implementation for iterating over nested DifferentiableViews.
// Also improves the firstIndex() ui because \DifferentiableView.base[i] != \DifferentiableView[i]
final class ArrayDifferentiableTensorVisitorPlanWrapper<Base, Child>: TensorVisitorPlanWrapperBase<
Base
>
where Child: Differentiable {
var child: WritableKeyPath<Base, Array<Child>.DifferentiableView>
var childPlans: [TensorVisitorPlan<Child>]
init(
child: WritableKeyPath<Base, Array<Child>.DifferentiableView>,
childPlans: [TensorVisitorPlan<Child>]
) {
self.child = child
self.childPlans = childPlans
}
override func appendKeyPaths<TrueBase>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ kps: inout [WritableKeyPath<TrueBase, Tensor<Float>>]
) {
let childKp = rootKeyPath.appending(path: child)
for (i, childPlan) in childPlans.enumerated() {
childPlan.appendKeyPaths(
childKp.appending(path: \Array<Child>.DifferentiableView.base[i]), &kps)
}
}
override func populateTensors(_ v: Base, _ tensors: inout [Tensor<Float>]) {
let arr = v[keyPath: child]
for (i, childPlan) in childPlans.enumerated() {
childPlan.populateTensors(arr[i], &tensors)
}
}
override func mapTensors(_ v1: inout Base, _ v2: Base, _ i: inout Int, _ fn: GradMapFn) {
{ (arr1: inout Array<Child>.DifferentiableView, arr2: Array<Child>.DifferentiableView) in
for (j, childPlan) in childPlans.enumerated() {
childPlan.mapTensors(&arr1[j], arr2[j], &i, fn)
}
}(&v1[keyPath: child], v2[keyPath: child])
}
override func populateMask<Base>(_ mask: inout [Bool], _ kp: WritableKeyPath<Base, Tensor<Float>>)
{
for childPlan in childPlans { childPlan.populateMask(&mask, kp) }
}
override func findFirstIndex<TrueBase, T>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ prefix: WritableKeyPath<TrueBase, T>, _ i: inout Int
) -> Bool {
let childKp = rootKeyPath.appending(path: child)
if childKp == prefix { return true }
for (j, childPlan) in childPlans.enumerated() {
let elementKp = childKp.appending(path: \Array<Child>.DifferentiableView[j])
if elementKp == prefix || childPlan.findFirstIndex(elementKp, prefix, &i) {
return true
}
}
return childKp.appending(path: \Array<Child>.DifferentiableView[childPlans.count]) == prefix
}
}
/// TensorVisitorPlan approximates `[WritableKeyPath<Base, Tensor<Float>]` but
/// is more efficient. This is useful for writing generic optimizers which want
/// to map over the gradients, the existing weights, and an index which can be
/// used to find auxiliarily stored weights. This is slightly more efficient (~2x) but it could
/// be better because it trades off slightly higher overheads (extra pointer dereference)
/// for not having to do O(depth_of_tree) work that is required with a plain list to track
/// down each individual KeyPath.
public struct TensorVisitorPlan<Base> {
enum Impl {
case leaf(WritableKeyPath<Base, Tensor<Float>>)
case node(TensorVisitorPlanWrapperBase<Base>)
}
var elements: [Impl] = []
func appendKeyPaths<TrueBase>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ kps: inout [WritableKeyPath<TrueBase, Tensor<Float>>]
) {
for item in elements {
switch item {
case .leaf(let kp):
kps.append(rootKeyPath.appending(path: kp))
case .node(let plan):
plan.appendKeyPaths(rootKeyPath, &kps)
}
}
}
/// Flatten out the plan as a single `[WritableKeyPath<Base, Tensor<Float>]`.
public var allTensorKeyPaths: [WritableKeyPath<Base, Tensor<Float>>] {
var kps = [WritableKeyPath<Base, Tensor<Float>>]()
appendKeyPaths(\Base.self, &kps)
return kps
}
func populateTensors(_ v: Base, _ tensors: inout [Tensor<Float>]) {
for item in elements {
switch item {
case .leaf(let kp):
tensors.append(v[keyPath: kp])
case .node(let plan):
plan.populateTensors(v, &tensors)
}
}
}
/// Efficiently collect all the tensors.
public func allTensors(_ v: Base) -> [Tensor<Float>] {
var tensors = [Tensor<Float>]()
populateTensors(v, &tensors)
return tensors
}
/// Efficiently map over two values of type `Base` and apply a mapping function.
/// Returns the number of tensors. The extra `Int` argument is provided to allow indexing
/// into an auxiliary list of Tensors with the same Tensor count as the plan.
@discardableResult
public func mapTensors(
_ v1: inout Base, _ v2: Base, _ fn: (inout Tensor<Float>, Tensor<Float>, Int) -> Void
) -> Int {
var i = 0
mapTensors(&v1, v2, &i, fn)
return i
}
func mapTensors(_ v1: inout Base, _ v2: Base, _ i: inout Int, _ fn: GradMapFn) {
for item in elements {
switch item {
case .leaf(let kp):
let _ = fn(&v1[keyPath: kp], v2[keyPath: kp], i)
i += 1
case .node(let plan):
plan.mapTensors(&v1, v2, &i, fn)
}
}
}
}
protocol VisitorPlanBuilder {
func _buildWrappedVisitorPlan<Base>(_ rootKeyPath: PartialKeyPath<Base>)
-> TensorVisitorPlanWrapperBase<Base>?
}
extension Array: VisitorPlanBuilder {
func _buildWrappedVisitorPlan<Base>(_ rootKeyPath: PartialKeyPath<Base>)
-> TensorVisitorPlanWrapperBase<Base>?
{
if let kp = rootKeyPath as? WritableKeyPath<Base, Self> {
var nonEmpty = false
var plans = [TensorVisitorPlan<Element>]()
for element in self {
guard let element = element as? _KeyPathIterableBase else { return nil }
var plan = TensorVisitorPlan<Element>()
element._populateTensorVisitorPlan(&plan)
nonEmpty = nonEmpty || !plan.elements.isEmpty
plans.append(plan)
}
if nonEmpty {
return ArrayTensorVisitorPlanWrapper(child: kp, childPlans: plans)
}
}
return nil
}
}
extension Array.DifferentiableView: VisitorPlanBuilder where Element: Differentiable {
func _buildWrappedVisitorPlan<Base>(_ rootKeyPath: PartialKeyPath<Base>)
-> TensorVisitorPlanWrapperBase<Base>?
{
if let kp = rootKeyPath as? WritableKeyPath<Base, Self> {
var nonEmpty = false
var plans = [TensorVisitorPlan<Element>]()
for element in self {
guard let element = element as? _KeyPathIterableBase else { return nil }
var plan = TensorVisitorPlan<Element>()
element._populateTensorVisitorPlan(&plan)
nonEmpty = nonEmpty || !plan.elements.isEmpty
plans.append(plan)
}
if nonEmpty {
return ArrayDifferentiableTensorVisitorPlanWrapper(child: kp, childPlans: plans)
}
}
return nil
}
}
extension _KeyPathIterableBase {
func _buildWrappedVisitorPlan<Base>(
_ rootKeyPath: PartialKeyPath<Base>
) -> TensorVisitorPlanWrapperBase<Base>? {
if let kp = rootKeyPath as? WritableKeyPath<Base, Self> {
var plan = TensorVisitorPlan<Self>()
_populateTensorVisitorPlan(&plan)
if !plan.elements.isEmpty {
return TensorVisitorPlanWrapper(child: kp, childPlan: plan)
}
}
return nil
}
func _populateTensorVisitorPlan<Base>(_ plan: inout TensorVisitorPlan<Base>) {
for kp in _allKeyPathsTypeErased {
if let kp = kp as? WritableKeyPath<Base, Tensor<Float>> {
plan.elements.append(.leaf(kp))
} else if let nested = self[keyPath: kp] as? VisitorPlanBuilder {
if let child = nested._buildWrappedVisitorPlan(kp as! PartialKeyPath<Base>) {
plan.elements.append(.node(child))
}
} else if let value = self[keyPath: kp], let nested = value as? _KeyPathIterableBase {
if let child = nested._buildWrappedVisitorPlan(kp as! PartialKeyPath<Base>) {
plan.elements.append(.node(child))
}
}
}
}
}
extension TensorVisitorPlan where Base: KeyPathIterable {
/// Creates a plan to visit all the tensors in a particular instance of `Base`.
/// This plan is transferable to structurally equivalent versions of Base.
public init(_ obj: Base) {
obj._populateTensorVisitorPlan(&self)
}
}
extension TensorVisitorPlan {
func populateMask<Base>(_ mask: inout [Bool], _ kp: WritableKeyPath<Base, Tensor<Float>>) {
for item in elements {
switch item {
case .leaf(let okp):
mask.append(kp == okp)
case .node(let plan):
plan.populateMask(&mask, kp)
}
}
}
/// Find all keys ending with a particular key-path.
public func keysEnding<Base>(with kp: WritableKeyPath<Base, Tensor<Float>>) -> [Bool] {
var mask = [Bool]()
populateMask(&mask, kp)
return mask
}
func findFirstIndex<TrueBase, T>(
_ rootKeyPath: WritableKeyPath<TrueBase, Base>,
_ prefix: WritableKeyPath<TrueBase, T>, _ i: inout Int
) -> Bool {
if rootKeyPath == prefix { return true }
for item in elements {
switch item {
case .leaf(let kp):
if rootKeyPath.appending(path: kp) == prefix { return true }
i += 1
case .node(let plan):
if plan.findFirstIndex(rootKeyPath, prefix, &i) { return true }
}
}
return false
}
/// Find the index of the first keypath starting with a particular prefix.
/// Note: All array layers support 1-past-the-end indexing.
func firstIndex<T>(withPrefix prefix: WritableKeyPath<Base, T>) -> Int {
var i = 0
let _ = findFirstIndex(\Base.self, prefix, &i)
return i
}
/// Find all keys indices in a range defined by two KeyPath prefixes: [lower, upper)
public func allKeysBetween<T, U>(lower: WritableKeyPath<Base, T>, upper: WritableKeyPath<Base, U>)
-> [Bool]
{
let range = firstIndex(withPrefix: lower)..<firstIndex(withPrefix: upper)
return allTensorKeyPaths.indices.map { range.contains($0) }
}
}
extension Array where Element == Bool {
/// Computes `a || b` elementwise as though we were or-ing together
/// two masks.
public func mergingMask(with other: [Bool]) -> [Bool] {
precondition(count == other.count)
return indices.map { i in self[i] || other[i] }
}
}
| 35.094688 | 100 | 0.684193 |
2f22fe65e9fc6e222bcd2e0b117ce40f0f35ad7a | 451 | //
// UIColor-Extension.swift
// SwiftProject
//
// Created by zoubenjun on 2020/11/27.
//
import UIKit
extension UIColor {
convenience init(r:CGFloat,g:CGFloat,b:CGFloat) {
self.init(red: r/255.0 ,green: g/255.0 ,blue: b/255.0 ,alpha:1.0)
}
class func randomColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
}
| 25.055556 | 133 | 0.656319 |
e51a64c605ea632cc2531221dffbfa7fd968abb1 | 2,614 | import Quick
import Nimble
import Capsule
@testable import Utensils
class DebouncerSpec: QuickSpec {
override func spec() {
describe("Debouncer") {
var subject: Debouncer!
var fakeDispatchQueueWrapper: FakeDispatchQueueWrapper!
var fakeDispatchWorkItemWrapperBuilder: FakeDispatchWorkItemWrapperBuilder!
beforeEach {
fakeDispatchQueueWrapper = FakeDispatchQueueWrapper()
fakeDispatchWorkItemWrapperBuilder = FakeDispatchWorkItemWrapperBuilder()
fakeDispatchWorkItemWrapperBuilder.shouldUseDispatchWorkItemWrappersArray = true
subject = Debouncer(dispatchQueueWrapper: fakeDispatchQueueWrapper,
dispatchWorkItemWrapperBuilder: fakeDispatchWorkItemWrapperBuilder)
}
describe("#mainDebounce(seconds:qos:execute:)") {
var previousDispatchWorkItemWrapper: FakeDispatchWorkItemWrapper!
beforeEach {
previousDispatchWorkItemWrapper = (subject.currentDispatchWorkItemWrapper as! FakeDispatchWorkItemWrapper)
subject.mainDebounce(seconds: 33.33) { }
}
it("cancels previous work item wrapper execution") {
expect(previousDispatchWorkItemWrapper.didCancel).to(beTruthy())
}
it("creates a new work item wrapper to execute") {
let updatedDispatchWorkItemWrapper = (subject.currentDispatchWorkItemWrapper as! FakeDispatchWorkItemWrapper)
expect(updatedDispatchWorkItemWrapper === previousDispatchWorkItemWrapper).toNot(beTruthy())
}
it("dispatches the new work item wrapper using debounce seconds and qos") {
expect(fakeDispatchQueueWrapper.capturedMainAfterWorkItemWrapperSecondsDouble).to(equal(33.33))
let actualDispatchWorkItemWrapper = (fakeDispatchQueueWrapper.capturedMainAfterWorkItemWrapperSecondsDoubleProtocol as! FakeDispatchWorkItemWrapper)
let updatedDispatchWorkItemWrapper = (subject.currentDispatchWorkItemWrapper as! FakeDispatchWorkItemWrapper)
expect(actualDispatchWorkItemWrapper === updatedDispatchWorkItemWrapper).to(beTruthy())
}
}
}
}
}
| 47.527273 | 168 | 0.608263 |
f73df15aed5bf5ef1859969fcd866f2b933921fb | 495 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
extension Array {
func b.C> : B? = B
}
protocol d {
let c: A> Bool {
case c("
typealias A : A> T
| 30.9375 | 79 | 0.723232 |
e495d022d225086f1a47fa6031ee3697896b0590 | 2,267 | //
// API.Coinmarket.swift
// BBCap
//
// Created by Lam Le V. on 6/1/18.
// Copyright © 2018 Asian Tech Co., Ltd. All rights reserved.
//
import Foundation
import ObjectMapper
extension Api.CoinmarketCap {
static func getTickets(completion: @escaping Completion<[Ticket]>) {
let path = Api.CoinmarketCap.Tickets.path
api.request(method: .get, urlString: path) { result in
switch result {
case .success(let value):
guard let json = value as? JSArray else {
completion(.failure(Api.Error.json))
return
}
let tickets = Mapper<Ticket>().mapArray(JSONArray: json)
completion(.success(tickets))
case .failure(let error):
completion(.failure(error))
}
}
}
static func getGlobal(completion: @escaping Completion<GlobalInfo>) {
let path = Api.CoinmarketCap.Global.path
api.request(method: .get, urlString: path) { result in
switch result {
case .success(let value):
guard let json = value as? JSObject, let currency = Mapper<GlobalInfo>().map(JSON: json) else {
completion(.failure(Api.Error.json))
return
}
completion(.success(currency))
case .failure(let error):
completion(.failure(error))
}
}
}
static func getCurrencyBitcoin(type: DetailViewModel.TimeType, currency: String, completion: @escaping Completion<Currency>) {
let path = Api.CoinmarketCap.Currencies.Bitcoin(startDate: type.pastTimeInterval, endDate: type.currentTimeInterval, currency: currency).path
api.request(method: .get, urlString: path) { result in
switch result {
case .success(let value):
guard let json = value as? JSObject, let currency = Mapper<Currency>().map(JSON: json) else {
completion(.failure(Api.Error.json))
return
}
completion(.success(currency))
case .failure(let error):
completion(.failure(error))
}
}
}
}
| 35.984127 | 149 | 0.561535 |
defd7826383b30283245f87a919cae077bf0bd76 | 512 | //
// Date+extensions.swift
// IPSX
//
// Created by Calin Chitu on 14/05/2018.
// Copyright © 2018 Cristina Virlan. All rights reserved.
//
import UIKit
extension Date {
func dateToString(format: String) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
func isFromToday() -> Bool
{
let calendar = NSCalendar.current
return calendar.isDateInToday(self)
}
}
| 19.692308 | 58 | 0.630859 |
d6d30191b93c9e6aae621f99bbbcbbae34c7ae07 | 340 | //
// SwiftHashTagsExtensions.swift
// SwiftHashTags
//
// Created by Anuradh Caldera on 12/19/18.
//
import Foundation
extension UIColor {
func returngbColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor.init(red: red/255, green: green/255, blue: blue/255, alpha: alpha)
}
}
| 22.666667 | 96 | 0.685294 |
1da461b930f5f901f4b7d799987bd864053eb2f5 | 3,541 | //
// DonorAddAddressViewController.swift
// hackathon-for-hunger
//
// Created by ivan lares on 4/30/16.
// Copyright © 2016 Hacksmiths. All rights reserved.
//
import UIKit
class DonorAddAddressViewController: UIViewController {
@IBOutlet weak var addressTextField: UITextField!
@IBOutlet weak var cityTextField: UITextField!
@IBOutlet weak var stateTextField: UITextField!
@IBOutlet weak var zipTextField: UITextField!
@IBOutlet weak var addAddressButton: UIButton!
var delegate: DonorAddressViewControllerDelegate?
let userService = UserService()
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupTextFields()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
title = "ADD NEW ADDRESS"
tabBarController?.tabBar.hidden = true
addAddressButton.enabled = false
addAddressButton.alpha = 0.5
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
tabBarController?.tabBar.hidden = false
}
// MARK: Helper methods
func setupTextFields() {
addressTextField.delegate = self
cityTextField.delegate = self
stateTextField.delegate = self
zipTextField.delegate = self
addressTextField.addTarget(self, action: #selector(DonorAddAddressViewController.toggleButtonControl(_:)), forControlEvents: .AllEditingEvents)
cityTextField.addTarget(self, action: #selector(DonorAddAddressViewController.toggleButtonControl(_:)), forControlEvents: .AllEditingEvents)
stateTextField.addTarget(self, action: #selector(DonorAddAddressViewController.toggleButtonControl(_:)), forControlEvents: .AllEditingEvents)
zipTextField.addTarget(self, action: #selector(DonorAddAddressViewController.toggleButtonControl(_:)), forControlEvents: .AllEditingEvents)
}
func toggleButtonControl(sender: UITextField) {
guard
let address = addressTextField.text where !address.isBlank,
let city = cityTextField.text where !city.isBlank,
let state = stateTextField.text where !state.isBlank,
let zip = zipTextField.text where !zip.isBlank else {
addAddressButton.enabled = false
addAddressButton.alpha = 0.5
return
}
addAddressButton.enabled = true
addAddressButton.alpha = 1.0
}
func getAddressFromFields() -> String {
// The add address button won't be enabled until all fields are filled
// If reached here, we know the fields will have text
return "\(addressTextField.text!), \(cityTextField.text!)"
}
// MARK: Actions
@IBAction func didTapAddAddress(sender: AnyObject) {
let address = Address()
address.city = cityTextField.text!
address.street_address = addressTextField.text!
address.state = addressTextField.text!
address.zip = zipTextField.text!
address.isDefault = false
//saveAddress(address)
delegate?.addAddress(address)
navigationController?.popViewControllerAnimated(true)
}
}
extension DonorAddAddressViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
| 33.40566 | 151 | 0.666196 |
625ea025b9ca120a5e75760bda14d87a4f504aaa | 329 | //
// Product.swift
// ResturantShop
//
// Created by Марія Кухарчук on 08.01.2022.
//
import Foundation
struct Product: Decodable, Identifiable{
let id: Int
let category: String
let name: String
let ingredients: String
let calories: Int
let price: Double
let rate: Double
let time: String
}
| 16.45 | 44 | 0.665653 |
b9fd53c6c22ca7aaf52d3c5a82fb8fd7bacc7b76 | 2,393 | //
// Keychain.swift
// Quick-Start-iOS
//
// Created by hyyy on 2017/1/18.
// Copyright © 2017年 hyyy. All rights reserved.
//
import Foundation
struct Keychain {
static func password(service: String?, account: String?, accessGroup: String? = nil) -> String? {
var item = KeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.queryPassword()
}catch {
print("Error fetching password item - \(error)")
return ""
}
return item.password
}
static func passwordData(service: String?, account: String?, accessGroup: String? = nil) -> Data? {
var item = KeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.queryPassword()
}catch {
print("Error fetching passwordData item - \(error)")
return nil
}
return item.passwordData
}
static func deletePassword(service: String?, account: String?, accessGroup: String? = nil) {
var item = KeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.delete()
} catch {
print("Error deleting password item - \(error)")
}
}
static func set(password: String?, service: String?, account: String?, accessGroup: String? = nil) {
var item = KeychainItem (service: service, account: account)
item.accessGroup = accessGroup
item.password = password
do {
try item.save()
} catch {
print("Error setting password item - \(error)")
}
}
static func set(passwordData: Data?, service: String?, account: String?, accessGroup: String? = nil) {
var item = KeychainItem (service: service, account: account)
item.accessGroup = accessGroup
item.passwordData = passwordData
do {
try item.save()
}catch {
print("Error setting password item - \(error)")
}
}
static func allAccount() -> Array<[String : AnyObject]> {
return allAccounts(forService: nil)
}
static func allAccounts(forService service: String?) -> Array<[String : AnyObject]> {
var item = KeychainItem ()
item.service = service
var allAccountsArr: Array<[String : AnyObject]>
do {
try allAccountsArr = item.queryAll()
} catch {
print("Error setting password item - \(error)")
return []
}
return allAccountsArr
}
}
| 27.825581 | 104 | 0.640201 |
145922ffc41b85e4ecba9a71fc5a9acbccd1ac8d | 254 | //
// MessagesEntity.swift
// mobdevprototype
//
// Created by Dré on 25/05/2018.
// Copyright © 2018 dreyworks. All rights reserved.
//
import Foundation
protocol MessagesEntity: class {
var id: Int { get }
var success: [String] { get }
}
| 16.933333 | 52 | 0.661417 |
18f033ffbd77d59e18c77f242578c2d80aed9e62 | 1,881 | // Copyright 2016 Razeware Inc. (see LICENSE.txt for details)
class Pastry {
let flavor: String
var numberOnHand: Int
init(flavor: String, numberOnHand: Int) {
self.flavor = flavor
self.numberOnHand = numberOnHand
}
}
enum BakeryError: Error {
case tooFew(numberOnHand: Int)
case doNotSell
case wrongFlavor
}
class Bakery {
var itemsForSale = [
"Cookie": Pastry(flavor: "ChocolateChip", numberOnHand: 20),
"PopTart": Pastry(flavor: "WildBerry", numberOnHand: 13),
"Donut" : Pastry(flavor: "Sprinkles", numberOnHand: 24),
"HandPie": Pastry(flavor: "Cherry", numberOnHand: 6)
]
func orderPastry(item: String, amountRequested: Int, flavor: String) throws -> Int {
guard let pastry = itemsForSale[item] else {
throw BakeryError.doNotSell
}
guard flavor == pastry.flavor else {
throw BakeryError.wrongFlavor
}
guard amountRequested < pastry.numberOnHand else {
throw BakeryError.tooFew(numberOnHand: pastry.numberOnHand)
}
pastry.numberOnHand -= amountRequested
return pastry.numberOnHand
}
}
let bakery = Bakery()
do {
try bakery.orderPastry(item: "Albatross", amountRequested: 1, flavor: "AlbatrossFlavor")
} catch BakeryError.doNotSell {
print("Sorry, but we don't sell albatross")
} catch BakeryError.wrongFlavor {
print("Sorry, but we don't carry albatross flavor")
} catch BakeryError.tooFew {
print("Sorry, we don't have enough albatross to fulfill your order")
}
let remaining = try? bakery.orderPastry(item: "Albatross",
amountRequested: 1,
flavor: "AlbatrossFlavor")
do {
try bakery.orderPastry(item: "Cookie", amountRequested: 1, flavor: "ChocolateChip")
}
catch {
fatalError()
}
try! bakery.orderPastry(item: "Cookie", amountRequested: 1, flavor: "ChocolateChip")
| 26.871429 | 90 | 0.676236 |
298093551edf35d2a3413a7b15343d9a6222ea78 | 1,278 | //
// AuthorizationView.swift
// goland
//
// Created by Kusyumov Nikita on 27.08.2020.
// Copyright © 2020 [email protected]. All rights reserved.
//
import Foundation
import UIKit
class AuthorizationView: UIView {
// MARK: - Internal properties
private struct Appearance: Grid {
let signInViewLeadingTrailingInset: CGFloat = 38
}
private let appearance = Appearance()
// MARK: - UI elements
lazy var signInView = SignInView()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func commonInit() {
setupStyle()
addSubviews()
makeConstraints()
}
private func setupStyle() {
//backgroundColor = .red
}
private func addSubviews() {
addSubview(signInView)
}
private func makeConstraints() {
signInView.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.leading.trailing.equalToSuperview()
.inset(appearance.signInViewLeadingTrailingInset)
}
}
}
| 21.3 | 65 | 0.594679 |
8ff858c547d4d748b913307afdd0ae25b3395f71 | 1,083 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.0.1-9346c8cc45
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
This value set includes smattering of Payment Adjustment Reason codes.
URL: http://terminology.hl7.org/CodeSystem/payment-adjustment-reason
ValueSet: http://hl7.org/fhir/ValueSet/payment-adjustment-reason
*/
public enum PaymentAdjustmentReasonCodes: String, FHIRPrimitiveType {
/// Prior Payment Reversal
case A001 = "a001"
/// Prior Overpayment
case A002 = "a002"
}
| 30.083333 | 76 | 0.737765 |
4b227ac4551d33cc1780a7e3051140d7671ded4f | 908 | //
// Stack.swift
// DataStructure
//
// Created by Jigs Sheth on 11/13/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import Foundation
struct Stack<Element:Equatable>:Equatable {
//Storage
private var storage:[Element] = []
var isEmpty:Bool {
return peek() == nil
}
var first:Element? {
return storage.first
}
init(){}
init(_ elemenets:[Element]) {
storage = elemenets
}
//Push
mutating func push(_ element:Element) {
storage.append(element)
}
@discardableResult
mutating func pop() -> Element? {
return storage.popLast()
}
func peek() -> Element? {
return storage.last
}
}
extension Stack:CustomStringConvertible{
var description: String {
return storage.map{"\($0)"}.joined(separator: " ")
}
}
extension Stack: ExpressibleByArrayLiteral {
init(arrayLiteral elements: Element...) {
storage = elements
}
}
| 14.645161 | 60 | 0.65859 |
e009ffde3d71b468b050894ea9169ca51ef0b427 | 666 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 371. Sum of Two Integers
// Given two integers a and b, return the sum of the two integers without using the operators + and -.
// Example 1:
// Input: a = 1, b = 2
// Output: 3
// Example 2:
// Input: a = 2, b = 3
// Output: 5
// Constraints:
// -1000 <= a, b <= 1000
func getSum(_ a: Int, _ b: Int) -> Int {
var c = a
var d = b
while d != 0 {
let sum = c ^ d
let carry = (c & d) << 1
c = sum
d = carry
}
return c
}
} | 20.181818 | 106 | 0.448949 |
751bb91e46e46ddf3d5c5ea849016647a936bfc4 | 967 | import UIKit
import MRCountryPicker
class ViewController: UIViewController, MRCountryPickerDelegate {
@IBOutlet weak var countryPicker: MRCountryPicker!
@IBOutlet weak var countryName: UILabel!
@IBOutlet weak var countryCode: UILabel!
@IBOutlet weak var countryFlag: UIImageView!
@IBOutlet weak var phoneCode: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
countryPicker.countryPickerDelegate = self
countryPicker.showPhoneNumbers = true
countryPicker.setTopCountries(codes: ["no", "se", "gb", "pl", "dk", "de"])
countryPicker.setDefaultCountry()
}
func countryPhoneCodePicker(_ picker: MRCountryPicker, didSelectCountryWithName name: String, countryCode: String, phoneCode: String, flag: UIImage) {
self.countryName.text = name
self.countryCode.text = countryCode
self.phoneCode.text = phoneCode
self.countryFlag.image = flag
}
}
| 35.814815 | 154 | 0.703206 |
d6c41546f863c6cc73db93fac19198520547e87e | 7,865 | //
// PlayerViewController.swift
// ASPVideoPlayer
//
// Created by Andrei-Sergiu Pițiș on 09/12/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import ASPVideoPlayer
import AVFoundation
class PlayerViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var videoPlayerBackgroundView: UIView!
@IBOutlet weak var videoPlayer: ASPVideoPlayer!
let firstLocalVideoURL = Bundle.main.url(forResource: "video", withExtension: "mp4")
let secondLocalVideoURL = Bundle.main.url(forResource: "video2", withExtension: "mp4")
let firstNetworkURL = URL(string: "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8")
let secondNetworkURL = URL(string: "http://www.easy-fit.ae/wp-content/uploads/2014/09/WebsiteLoop.mp4")
override func viewDidLoad() {
super.viewDidLoad()
let firstAsset = AVURLAsset(url: firstLocalVideoURL!)
let secondAsset = AVURLAsset(url: secondLocalVideoURL!)
let thirdAsset = AVURLAsset(url: firstNetworkURL!)
let fourthAsset = AVURLAsset(url: secondNetworkURL!)
// videoPlayer.videoURLs = [firstLocalVideoURL!, secondLocalVideoURL!, firstNetworkURL!, secondNetworkURL!]
videoPlayer.videoAssets = [firstAsset, secondAsset, thirdAsset, fourthAsset]
// videoPlayer.configuration = ASPVideoPlayer.Configuration(videoGravity: .aspectFit, shouldLoop: true, startPlayingWhenReady: true, controlsInitiallyHidden: true, allowBackgroundPlay: true)
videoPlayer.resizeClosure = { [unowned self] isExpanded in
self.rotate(isExpanded: isExpanded)
}
videoPlayer.delegate = self
}
override var prefersStatusBarHidden: Bool {
return true
}
var previousConstraints: [NSLayoutConstraint] = []
func rotate(isExpanded: Bool) {
let views: [String:Any] = ["videoPlayer": videoPlayer as Any,
"backgroundView": videoPlayerBackgroundView as Any]
var constraints: [NSLayoutConstraint] = []
if isExpanded == false {
self.containerView.removeConstraints(self.videoPlayer.constraints)
self.view.addSubview(self.videoPlayerBackgroundView)
self.view.addSubview(self.videoPlayer)
self.videoPlayer.frame = self.containerView.frame
self.videoPlayerBackgroundView.frame = self.containerView.frame
let padding = (self.view.bounds.height - self.view.bounds.width) / 2.0
var bottomPadding: CGFloat = 0
if #available(iOS 11.0, *) {
if self.view.safeAreaInsets != .zero {
bottomPadding = self.view.safeAreaInsets.bottom
}
}
let metrics: [String:Any] = ["padding":padding,
"negativePaddingAdjusted":-(padding - bottomPadding),
"negativePadding":-padding]
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(negativePaddingAdjusted)-[videoPlayer]-(negativePaddingAdjusted)-|",
options: [],
metrics: metrics,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(padding)-[videoPlayer]-(padding)-|",
options: [],
metrics: metrics,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(negativePadding)-[backgroundView]-(negativePadding)-|",
options: [],
metrics: metrics,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(padding)-[backgroundView]-(padding)-|",
options: [],
metrics: metrics,
views: views))
self.view.addConstraints(constraints)
} else {
self.view.removeConstraints(self.previousConstraints)
let targetVideoPlayerFrame = self.view.convert(self.videoPlayer.frame, to: self.containerView)
let targetVideoPlayerBackgroundViewFrame = self.view.convert(self.videoPlayerBackgroundView.frame, to: self.containerView)
self.containerView.addSubview(self.videoPlayerBackgroundView)
self.containerView.addSubview(self.videoPlayer)
self.videoPlayer.frame = targetVideoPlayerFrame
self.videoPlayerBackgroundView.frame = targetVideoPlayerBackgroundViewFrame
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|[videoPlayer]|",
options: [],
metrics: nil,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|[videoPlayer]|",
options: [],
metrics: nil,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|[backgroundView]|",
options: [],
metrics: nil,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|[backgroundView]|",
options: [],
metrics: nil,
views: views))
self.containerView.addConstraints(constraints)
}
self.previousConstraints = constraints
UIView.animate(withDuration: 0.25, delay: 0.0, options: [], animations: {
self.videoPlayer.transform = isExpanded == true ? .identity : CGAffineTransform(rotationAngle: .pi / 2.0)
self.videoPlayerBackgroundView.transform = isExpanded == true ? .identity : CGAffineTransform(rotationAngle: .pi / 2.0)
self.view.layoutIfNeeded()
})
}
}
extension PlayerViewController: ASPVideoPlayerViewDelegate {
func startedVideo() {
print("Started video")
}
func stoppedVideo() {
print("Stopped video")
}
func newVideo() {
print("New Video")
}
func readyToPlayVideo() {
print("Ready to play video")
}
func playingVideo(progress: Double) {
// print("Playing: \(progress)")
}
func pausedVideo() {
print("Paused Video")
}
func finishedVideo() {
print("Finished Video")
}
func seekStarted() {
print("Seek started")
}
func seekEnded() {
print("Seek ended")
}
func error(error: Error) {
print("Error: \(error)")
}
func willShowControls() {
print("will show controls")
}
func didShowControls() {
print("did show controls")
}
func willHideControls() {
print("will hide controls")
}
func didHideControls() {
print("did hide controls")
}
}
| 38.553922 | 205 | 0.555499 |
2fec0ab8648b17341dee23342e49aa7fd9c074be | 1,983 | //
// Created by Michael Schwarz on 17.09.20.
//
import Foundation
import OperationLog
/// Snapshot which represents a string
struct StringSnapshot: SnapshotProtocol {
// MARK: - Properties
private(set) var string: String
init(string: String) {
self.string = string
}
// MARK: - StringSnapshot
func applying(_ operation: CharacterOperation) -> (snapshot: StringSnapshot, outcome: Outcome<CharacterOperation>) {
switch operation.kind {
case .append:
let undoOperation = CharacterOperation(kind: .removeLast, character: operation.character)
let newSnapshot = self.appending(character: operation.character)
return (newSnapshot, .fullApplied(undoOperation: undoOperation))
case .removeLast:
guard let lastCharacter = self.string.last else {
return (self, .skipped(reason: "Snapshot is empty"))
}
let undoOperation = CharacterOperation(kind: .append, character: lastCharacter)
let newSnapshot = self.removingLast(character: operation.character)
return (newSnapshot, .fullApplied(undoOperation: undoOperation))
}
}
func appending(character: Character) -> StringSnapshot {
return StringSnapshot(string: self.string.appending("\(character)"))
}
func removingLast(character: Character) -> StringSnapshot {
var newString = self.string
let last = newString.removeLast()
guard last == character else {
fatalError("Character should match \(last) <> \(character)")
}
return StringSnapshot(string: newString)
}
// MARK: - Snapshot
func serialize() throws -> Data {
return try JSONEncoder().encode(self)
}
static func deserialize(fromData data: Data) throws -> StringSnapshot {
return try JSONDecoder().decode(self, from: data)
}
}
// MARK: - Codable
extension StringSnapshot: Codable { }
| 29.597015 | 120 | 0.65053 |
f7d5f59156c2d3eb08af37109d2ee993292038f7 | 989 | //
// RoomView.swift
// ARHuxing
//
// Created by EJU on 2018/11/8.
// Copyright © 2018年 EJU. All rights reserved.
//
import UIKit
import SceneKit
class RoomView: UIView
{
//room
let room:Room2D!
required init?(coder aDecoder: NSCoder) {
room = Room2D()
super.init(coder: aDecoder)
}
override init(frame: CGRect)
{
room = Room2D(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
super.init(frame: frame)
self.addSubview(room)
}
//更新内容
func update(points: [SCNVector3])
{
//3d坐标转2d坐标
var point2ds:[GLKVector2] = []
for point3d in points
{
var point2d = GLKVector2()
point2d.x = point3d.x
point2d.y = point3d.z
point2ds.append(point2d)
}
room.update(points: point2ds)
}
// 清空
func clear()
{
room.update(points: [])
}
}
| 18.660377 | 90 | 0.525784 |
e2a5155d029ef9ae672619ed0252856828daa958 | 2,861 | /*
Copyright (c) 2016, OpenEmu Team
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the OpenEmu Team nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
extension NSDocumentController {
var currentGameDocument: OEGameDocument? {
if let document = currentDocument as? OEGameDocument {
return document
}
for document in NSApplication.shared.orderedDocuments {
if let document = document as? OEGameDocument {
return document
}
}
return nil
}
@objc(openGameDocumentWithGame:display:fullScreen:completionHandler:)
func openGameDocument(with game: OEDBGame, display displayDocument: Bool, fullScreen: Bool, completionHandler: @escaping (OEGameDocument?, Error?) -> Void) {
fatalError("Method must be implemented by a subclass.")
}
@objc(openGameDocumentWithRom:display:fullScreen:completionHandler:)
func openGameDocument(with rom: OEDBRom, display displayDocument: Bool, fullScreen: Bool, completionHandler: @escaping (OEGameDocument?, Error?) -> Void) {
fatalError("Method must be implemented by a subclass.")
}
@objc(openGameDocumentWithSaveState:display:fullScreen:completionHandler:)
func openGameDocument(with saveState: OEDBSaveState, display displayDocument: Bool, fullScreen: Bool, completionHandler: @escaping (OEGameDocument?, Error?) -> Void) {
fatalError("Method must be implemented by a subclass.")
}
}
| 46.901639 | 171 | 0.731562 |
bbeae6db2316a81e6974ccc28e1a60d928522110 | 1,237 | //
// AnyCancellableSpec.swift
// iCombineTests
//
// Created by Adamas Zhu on 22/8/21.
//
import Nimble
import Quick
#if COMBINE
import Combine
#else
@testable import iCombine
#endif
final class AnyCancellableSpec: QuickSpec {
override func spec() {
describe("calls ==") {
context("with different object") {
it("returns false") {
let firstCancellable = CurrentValueSubject<Int?, Never>(nil)
.sink(receiveCompletion: { _ in },
receiveValue: { _ in })
let secondCancellable = Just<Int?>(nil)
.sink(receiveCompletion: { _ in },
receiveValue: { _ in })
expect(firstCancellable == secondCancellable) == false
}
}
context("with the same object") {
it("returns true") {
let cancellable = CurrentValueSubject<Int?, Never>(nil)
.sink(receiveCompletion: { _ in },
receiveValue: { _ in })
expect(cancellable == cancellable) == true
}
}
}
}
}
| 28.767442 | 80 | 0.481811 |
c1889f49a1ea789f6d97e86b7e98efcfc39f0184 | 8,061 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
// MARK: Paginators
extension ServiceQuotas {
/// Lists all default service quotas for the specified AWS service or all AWS services. ListAWSDefaultServiceQuotas is similar to ListServiceQuotas except for the Value object. The Value object returned by ListAWSDefaultServiceQuotas is the default value assigned by AWS. This request returns a list of all service quotas for the specified service. The listing of each you'll see the default values are the values that AWS provides for the quotas. Always check the NextToken response parameter when calling any of the List* operations. These operations can return an unexpected list of results, even when there are more results available. When this happens, the NextToken response parameter contains a value to pass the next call to the same API to request the next part of the list.
public func listAWSDefaultServiceQuotasPaginator(
_ input: ListAWSDefaultServiceQuotasRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListAWSDefaultServiceQuotasResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listAWSDefaultServiceQuotas, tokenKey: \ListAWSDefaultServiceQuotasResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Requests a list of the changes to quotas for a service.
public func listRequestedServiceQuotaChangeHistoryPaginator(
_ input: ListRequestedServiceQuotaChangeHistoryRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListRequestedServiceQuotaChangeHistoryResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listRequestedServiceQuotaChangeHistory, tokenKey: \ListRequestedServiceQuotaChangeHistoryResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Requests a list of the changes to specific service quotas. This command provides additional granularity over the ListRequestedServiceQuotaChangeHistory command. Once a quota change request has reached CASE_CLOSED, APPROVED, or DENIED, the history has been kept for 90 days.
public func listRequestedServiceQuotaChangeHistoryByQuotaPaginator(
_ input: ListRequestedServiceQuotaChangeHistoryByQuotaRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListRequestedServiceQuotaChangeHistoryByQuotaResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listRequestedServiceQuotaChangeHistoryByQuota, tokenKey: \ListRequestedServiceQuotaChangeHistoryByQuotaResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Returns a list of the quota increase requests in the template.
public func listServiceQuotaIncreaseRequestsInTemplatePaginator(
_ input: ListServiceQuotaIncreaseRequestsInTemplateRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListServiceQuotaIncreaseRequestsInTemplateResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listServiceQuotaIncreaseRequestsInTemplate, tokenKey: \ListServiceQuotaIncreaseRequestsInTemplateResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Lists all service quotas for the specified AWS service. This request returns a list of the service quotas for the specified service. you'll see the default values are the values that AWS provides for the quotas. Always check the NextToken response parameter when calling any of the List* operations. These operations can return an unexpected list of results, even when there are more results available. When this happens, the NextToken response parameter contains a value to pass the next call to the same API to request the next part of the list.
public func listServiceQuotasPaginator(
_ input: ListServiceQuotasRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListServiceQuotasResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listServiceQuotas, tokenKey: \ListServiceQuotasResponse.nextToken, on: eventLoop, onPage: onPage)
}
/// Lists the AWS services available in Service Quotas. Not all AWS services are available in Service Quotas. To list the see the list of the service quotas for a specific service, use ListServiceQuotas.
public func listServicesPaginator(
_ input: ListServicesRequest,
on eventLoop: EventLoop? = nil,
logger: Logger = AWSClient.loggingDisabled,
onPage: @escaping (ListServicesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(input: input, command: listServices, tokenKey: \ListServicesResponse.nextToken, on: eventLoop, onPage: onPage)
}
}
extension ServiceQuotas.ListAWSDefaultServiceQuotasRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ServiceQuotas.ListAWSDefaultServiceQuotasRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
serviceCode: self.serviceCode
)
}
}
extension ServiceQuotas.ListRequestedServiceQuotaChangeHistoryRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ServiceQuotas.ListRequestedServiceQuotaChangeHistoryRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
serviceCode: self.serviceCode,
status: self.status
)
}
}
extension ServiceQuotas.ListRequestedServiceQuotaChangeHistoryByQuotaRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ServiceQuotas.ListRequestedServiceQuotaChangeHistoryByQuotaRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
quotaCode: self.quotaCode,
serviceCode: self.serviceCode,
status: self.status
)
}
}
extension ServiceQuotas.ListServiceQuotaIncreaseRequestsInTemplateRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ServiceQuotas.ListServiceQuotaIncreaseRequestsInTemplateRequest {
return .init(
awsRegion: self.awsRegion,
maxResults: self.maxResults,
nextToken: token,
serviceCode: self.serviceCode
)
}
}
extension ServiceQuotas.ListServiceQuotasRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ServiceQuotas.ListServiceQuotasRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
serviceCode: self.serviceCode
)
}
}
extension ServiceQuotas.ListServicesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ServiceQuotas.ListServicesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
| 52.344156 | 791 | 0.729686 |
c1fbf65263a567699a539740124b0e7e6833f426 | 500 | //
// ViewController.swift
// GYAPod
//
// Created by airfight on 02/25/2019.
// Copyright (c) 2019 airfight. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20 | 80 | 0.668 |
e8e09ac133525f4a42cd78f3b23ebfeeea3cd670 | 1,120 | //
// AmplitudeCore.swift
// AmplitudeCore
//
// Created by Brian Giori on 12/20/21.
//
import Foundation
@objc public class AmplitudeCore : NSObject {
private static let instancesLock: DispatchSemaphore = DispatchSemaphore(value: 1)
private static var instances: [String:AmplitudeCore] = [:]
@objc public static func getInstance(_ instanceName: String) -> AmplitudeCore {
instancesLock.wait()
defer { instancesLock.signal() }
if let instance = instances[instanceName] {
return instance
} else {
instances[instanceName] = AmplitudeCore(
analyticsConnector: AnalyticsConnectorImpl(),
identityStore: IdentityStoreImpl()
)
return instances[instanceName]!
}
}
@objc public let analyticsConnector: AnalyticsConnector
@objc public let identityStore: IdentityStore
private init(analyticsConnector: AnalyticsConnector, identityStore: IdentityStore) {
self.analyticsConnector = analyticsConnector
self.identityStore = identityStore
}
}
| 30.27027 | 88 | 0.661607 |
763ea23e38eff65e09cd043bd2e6050ba9099a91 | 1,592 | // DepthKit © 2017–2021 Constantino Tsarouhas
extension RangeReplaceableCollection {
/// Returns a copy of the collection with the contents of a given sequence appended to it.
///
/// - Parameter other: The sequence whose elements to append.
///
/// - Returns: A copy of the collection with the contents of `other` appended to it.
public func appending(_ element: Element) -> Self {
with(self) {
$0.append(element)
}
}
/// Returns a copy of the collection with the contents of a given sequence appended to it.
///
/// - Parameter other: The sequence whose elements to append.
///
/// - Returns: A copy of the collection with the contents of `other` appended to it.
public func appending<S : Sequence>(contentsOf other: S) -> Self where S.Element == Element {
with(self) {
$0.append(contentsOf: other)
}
}
/// Returns a copy of the collection after inserting an element at a given index.
///
/// - Parameter insertedElement: The element to insert.
/// - Parameter index: The index of the inserted element.
///
/// - Returns: A copy of `self` after inserting `insertedElement` at `index`.
public func inserting(_ insertedElement: Element, at index: Index) -> Self {
with(self) {
$0.insert(insertedElement, at: index)
}
}
/// Returns a copy of the collection after removing an element at a given index.
///
/// - Parameter index: The index of the removed element.
///
/// - Returns: A copy of `self` after removing the element at `index`.
public func removing(at index: Index) -> Self {
with(self) {
$0.remove(at: index)
}
}
}
| 31.215686 | 94 | 0.682161 |
fb8c746c334246c2e76980a811b105c64746739a | 188 | //
// UIImage+CIExt.swift
// TKUIKitModule
//
// Created by 聂子 on 2019/10/4.
//
import Foundation
// MARK: - UIImage CI
extension TypeWrapperProtocol where WrappedType : UIImage {
}
| 13.428571 | 59 | 0.691489 |
ede48862b9daa27aa8d31d45ec79ee410bffbc49 | 1,166 | // 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
//
@_implementationOnly import CoreFoundation
/* Output from NSLogv is serialized, in that only one thread in a process can be doing
* the writing/logging described above at a time. All attempts at writing/logging a
* message complete before the next thread can begin its attempts. The format specification
* allowed by these functions is that which is understood by NSString's formatting capabilities.
* CFLog1() uses writev/fprintf to write to stderr. Both these functions ensure atomic writes.
*/
public func NSLogv(_ format: String, _ args: CVaListPointer) {
let message = NSString(format: format, arguments: args)
CFLog1(CFLogLevel(kCFLogLevelWarning), message._cfObject)
}
public func NSLog(_ format: String, _ args: CVarArg...) {
withVaList(args) {
NSLogv(format, $0)
}
}
| 40.206897 | 96 | 0.747856 |
9115e671e186a670b45d02b269103bba6177322c | 221 | //
// NVIdentifiable.swift
// novella
//
// Created by Daniel Green on 30/11/2018.
// Copyright © 2018 Daniel Green. All rights reserved.
//
import Foundation
protocol NVIdentifiable {
var UUID: NSUUID {get set}
}
| 15.785714 | 55 | 0.696833 |
0a62e06cef32ee03125ebf17af203bb7feea6aac | 2,486 | //
// CryptoAlgorithm.swift
//
// Copyright (c) 2016-present, LINE Corporation. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by LINE Corporation.
//
// As with any software that integrates with the LINE Corporation platform, your use of this software
// is subject to the LINE Developers Agreement [http://terms2.line.me/LINE_Developers_Agreement].
// This copyright notice shall be included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import CommonCrypto
typealias CryptoDigest = (
_ data: UnsafeRawPointer?,
_ length: CC_LONG,
_ md: UnsafeMutablePointer<UInt8>?) -> UnsafeMutablePointer<UInt8>?
/// Represents an algorithm used in crypto.
protocol CryptoAlgorithm {
var length: CC_LONG { get }
var signatureAlgorithm: SecKeyAlgorithm { get }
var encryptionAlgorithm: SecKeyAlgorithm { get }
var digest: CryptoDigest { get }
// Some algorithms require a different format for signature data. This is an injection point for it.
func convertSignatureData(_ data: Data) throws -> Data
}
extension CryptoAlgorithm {
func convertSignatureData(_ data: Data) throws -> Data { return data }
}
extension Data {
/// Calculate the digest with a given algorithm.
///
/// - Parameter algorithm: The algorithm be used. It should provide a digest hash method at least.
/// - Returns: The digest data.
func digest(using algorithm: CryptoAlgorithm) -> Data {
var hash = [UInt8](repeating: 0, count: Int(algorithm.length))
#if swift(>=5.0)
withUnsafeBytes { _ = algorithm.digest($0.baseAddress, CC_LONG(count), &hash) }
return Data(hash)
#else
withUnsafeBytes { _ = algorithm.digest($0, CC_LONG(count), &hash) }
return Data(bytes: hash)
#endif
}
}
| 40.754098 | 104 | 0.716412 |
ff59338028354746ffdb13dc4ca6b1e32cff3f93 | 6,279 | // Copyright © 2014 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import CoreGraphics
///A structure that contains a point in a two-dimensional coordinate system.
public struct Point: Equatable, CustomStringConvertible {
///The x value of the coordinate.
public var x: Double = 0
/// The y value of the coordinate.
public var y: Double = 0
/// Initializes a new point with the coordinates {0,0}
///
/// ````
/// let p = Point()
/// ````
public init() {
}
/// Initializes a new point with the specified coordinates {x,y}
///
/// ````
/// let p = Point(10.5,10.5)
/// ````
///
/// - parameter x: a Double value
/// - parameter y: a Double value
public init(_ x: Double, _ y: Double) {
self.x = x
self.y = y
}
/// Initializes a new point with the specified coordinates {x,y}, converting integer values to doubles
///
/// ````
/// let p = Point(10,10)
/// ````
public init(_ x: Int, _ y: Int) {
self.x = Double(x)
self.y = Double(y)
}
/// Initializes a Point initialized with a CGPoint.
///
/// - parameter point: a previously initialized CGPoint
public init(_ point: CGPoint) {
x = Double(point.x)
y = Double(point.y)
}
/// Returns true if the point's coordinates are {0,0}, otherwise returns false
public func isZero() -> Bool {
return x == 0 && y == 0
}
/// Transforms the point.
///
/// ````
/// var p = Point(10,10)
/// let v = Vector(x: 0, y: 0, z: 1)
/// let t = Transform.makeRotation(Double.pi, axis: v)
/// p.transform(t) // -> {-10.0, -10.0}
/// ````
///
/// - parameter t: A Transform to apply to the point
public mutating func transform(_ t: Transform) {
x = x * t[0, 0] + y * t[0, 1] + t[3, 0]
y = x * t[1, 0] + y * t[1, 1] + t[3, 1]
}
/// A string representation of the point.
///
/// ````
/// let p = Point()
/// println(p)
/// ````
///
/// - returns: A string formatted to look like {x,y}
public var description: String {
return "{\(x), \(y)}"
}
}
/// Translate a point by the given vector.
///
/// - parameter lhs: a Point to translate
/// - parameter rhs: a Vector whose values will be applied to the point
public func += (lhs: inout Point, rhs: Vector) {
lhs.x += rhs.x
lhs.y += rhs.y
}
/// Translate a point by the negative of the given vector
///
/// - parameter lhs: a Point to translate
/// - parameter rhs: a Vector whose values will be applied to the point
public func -= (lhs: inout Point, rhs: Vector) {
lhs.x -= rhs.x
lhs.y -= rhs.y
}
/// Calculate the vector between two points
///
/// - parameter lhs: a Point
/// - parameter rhs: a Point
///
/// - returns: a Vector whose value is the left-hand side _minus_ the right-hand side
public func - (lhs: Point, rhs: Point) -> Vector {
return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
/// Translate a point by the given vector.
///
/// - parameter lhs: a Point to translate
/// - parameter rhs: a Vector whose values will be applied to the point
///
/// - returns: A new point whose coordinates have been translated by the values from the vector (e.g. point.x = lhs.x + rhs.x)
public func + (lhs: Point, rhs: Vector) -> Point {
return Point(lhs.x + rhs.x, lhs.y + rhs.y)
}
/// Translate a point by the negative of the vector.
///
/// - parameter lhs: a Point to translate
/// - parameter rhs: a Vector whose values will be applied to the point
///
/// - returns: A new point whose coordinates have been translated by the negative vector (e.g. point.x = lhs.x - rhs.x)
public func - (lhs: Point, rhs: Vector) -> Point {
return Point(lhs.x - rhs.x, lhs.y - rhs.y)
}
/// Calculates the distance between two points.
///
/// - parameter lhs: left-hand point
/// - parameter rhs: right-hand point
///
/// - returns: The linear distance between two points
public func distance(_ lhs: Point, _ rhs: Point) -> Double {
let dx = rhs.x - lhs.x
let dy = rhs.y - lhs.y
return sqrt(dx*dx + dy*dy)
}
/// Checks to see if two points are equal.
///
/// - parameter lhs: a Point
/// - parameter rhs: a Point
///
/// - returns: true if the two structs have identical coordinates
public func == (lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
/// Linear interpolation.
///
/// For any two points `a` and `b` return a point that is the linear interpolation between a and b
/// for interpolation parameter `param`. For instance, a parameter of 0 will return `a`, a parameter of 1 will return `b`
/// and a parameter of 0.5 will return the midpoint between `a` and `b`.
///
/// - parameter a: the first point
/// - parameter b: the second point
/// - parameter param: a Double value (between 0.0 and 1.0) used to calculate the point between a and b
///
/// - returns: an interpolated point
public func lerp(_ a: Point, _ b: Point, at: Double) -> Point {
return a + (b - a) * at
}
public extension CGPoint {
///Initializes a CGPoint from a Point
init(_ point: Point) {
self.init(x: CGFloat(point.x), y: CGFloat(point.y))
}
}
| 32.365979 | 126 | 0.621914 |
716f66ca62c93c28f634d48698cf0a758e9a7575 | 8,299 | //
// formpertanyaanselectionTableViewCell.swift
// transmedik
//
// Created by Idham Kurniawan on 10/07/21.
//
import UIKit
protocol getheightrow {
func getrow( value : CGFloat)
func selectedrow(row : Int , label : String ,value : Bool)
func selectother(row : Int , label : String ,value : Bool)
func clear_radio()
func endkeyboard()
}
class formpertanyaanselectionTableViewCell: UITableViewCell,getheightrow {
@IBOutlet weak var notif: NSLayoutConstraint!
@IBOutlet weak var tinggi: NSLayoutConstraint!
var radio = false
var jawaban = ""
// var height : [CGFloat] = []{
// didSet{
//
//
// if height.count == listvalue.count{
// var _tmp : CGFloat = 0.0
// for i in 0..<height.count {
// _tmp += height[i]
// if i == height.count - 1{
// tinggi.constant = _tmp
// delegate?.refresh(row: row!)
// }
// }
//
// }
// }
// }
var listvalue : [listvalue] = []{
didSet{
tables.reloadData()
}
}
@IBOutlet weak var header: UILabel!
var row:Int?
var required = false
@IBOutlet weak var tables: UITableView!
@IBOutlet weak var background: UIView!
var delegate :form_pertanyaan_delegate?
override func awakeFromNib() {
super.awakeFromNib()
tables.delegate = self
tables.dataSource = self
tables.isScrollEnabled = false
background.layer.cornerRadius = 10
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
self.tables.reloadData()
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func getrow(value: CGFloat) {
}
func clear_radio(){
if !radio{
return
}
for i in 0..<listvalue.count{
listvalue[i].check = false
}
notif.constant = 0
self.tables.reloadData()
delegate?.set_radio_value_to_master(row: self.row!, value: "", list: nil, status: false, datavalue: listvalue)
}
func selectother(row: Int, label: String, value: Bool) {
if row == listvalue.count - 1 {
jawaban = label
}
if !radio{
var _temp = ""
listvalue[row].check = value
print("pilihan")
for i in 0..<listvalue.count{
if listvalue[i].check {
var jawaban = ""
if listvalue[i].label == "Lainnya"{
jawaban = label
}else{
jawaban = listvalue[i].label
}
print(jawaban)
if _temp.count == 0 {
_temp = jawaban
}else{
_temp = _temp + "|" + jawaban
}
}
}
print("checknox")
print(_temp)
delegate?.set_checkbox_value_to_master(row: self.row!, value: _temp, datavalue: listvalue)
}else{
print("radio")
for i in 0..<listvalue.count{
if i != row {
listvalue[i].check = false
}
}
if listvalue[row].check != value{
listvalue[row].check = value
// tables.reloadData()
}
print(label)
delegate?.set_radio_value_to_master(row: self.row!, value: label, list: row, status: value, datavalue: self.listvalue)
}
var status = false
for i in 0..<listvalue.count{
if listvalue[i].check {
status = true
}
}
if status{
notif.constant = 0
}else{
notif.constant = CGFloat(20)
}
}
func endkeyboard(){
delegate?.endkyeboard()
}
func filter()-> String?{
let _label = listvalue.map {$0.label}
let set2 : Set<String> = Set(_label)
let hasil = jawaban.components(separatedBy: "|")
let set1 : Set<String> = Set(hasil)
print("ini hasillllnya")
print(set1)
print(set2)
var data = listvalue.map {$0.label}
for index in hasil{
if !data.contains(index) {
return index
}
}
return nil
}
func selectedrow(row: Int, label: String ,value : Bool) {
if !radio{
var _temp = ""
listvalue[row].check = value
print("pilihan")
for i in 0..<listvalue.count{
if listvalue[i].check {
var jawaban = ""
if listvalue[i].label == "Lainnya"{
print(filter() ?? "kosong")
jawaban = filter() ?? ""
}else{
jawaban = listvalue[i].label
}
print(jawaban)
if _temp.count == 0 {
_temp = listvalue[i].label
}else{
_temp = _temp + "|" + listvalue[i].label
}
}
}
print("checknox")
delegate?.set_checkbox_value_to_master(row: self.row!, value: _temp, datavalue: listvalue)
}else{
print("radio")
jawaban = label
for i in 0..<listvalue.count{
if i != row {
listvalue[i].check = false
}
}
if listvalue[row].check != value{
listvalue[row].check = value
// tables.reloadData()
}
delegate?.set_radio_value_to_master(row: self.row!, value: label, list: row, status: value, datavalue: self.listvalue)
}
var status = false
for i in 0..<listvalue.count{
if listvalue[i].check {
status = true
}
}
if status{
notif.constant = 0
}else{
notif.constant = CGFloat(20)
}
}
}
extension formpertanyaanselectionTableViewCell : UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listvalue.count
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
self.tinggi.constant = tables.contentSize.height
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if listvalue[indexPath.row].label == "Lainnya" {
let cell = tableView.dequeueReusableCell(withIdentifier: "other", for: indexPath) as! cellotherpertanyaanTableViewCell
cell.row = indexPath.row
print("lainnya masuk")
print( filter() == nil ? "kosong" : filter())
cell.values.text = filter() == nil ? "" : filter()
cell.radio = self.radio
cell.ischeck = listvalue[indexPath.row].check
cell.delegate = self
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: "value", for: indexPath) as! cellvaluepertanyaanTableViewCell
cell.row = indexPath.row
cell.radio = self.radio
cell.ischeck = listvalue[indexPath.row].check
cell.values.text = listvalue[indexPath.row].label
cell.delegate = self
return cell
}
}
}
| 26.599359 | 131 | 0.470057 |
7a9504f2954320dc8786b6802f73402bc7597085 | 224 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol d{protocol a{typealias e
typealias e:d
}let:d
| 28 | 87 | 0.776786 |
08d90173144227ea3dc59bf8128d918176f67637 | 3,032 | //
// PostViewController.swift
// instagram-codepath
//
// Created by Christopher Guan on 2/25/18.
// Copyright © 2018 Christopher Guan. All rights reserved.
//
import UIKit
import Parse
class PostViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var postImageView: UIImageView!
@IBOutlet weak var captionTextField: UITextField!
@IBAction func onCancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func onShare(_ sender: Any) {
Post.postUserImage(image: postImageView.image, withCaption: captionTextField.text, withCompletion: nil)
dismiss(animated: true, completion: nil)
}
@objc func didTap(sender: UITapGestureRecognizer) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
vc.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(vc, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// Get the image captured by the UIImagePickerController
let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage
// Do something with the images
postImageView.image = originalImage
// Dismiss UIImagePickerController
dismiss(animated: true, completion: nil)
}
func resize(image: UIImage, newSize: CGSize) -> UIImage {
let resizeImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
resizeImageView.contentMode = UIViewContentMode.scaleAspectFill
resizeImageView.image = image
UIGraphicsBeginImageContext(resizeImageView.frame.size)
resizeImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTap(sender:)))
postImageView.isUserInteractionEnabled = true
postImageView.addGestureRecognizer(tapGestureRecognizer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 32.602151 | 119 | 0.687335 |
33b2cfa56d35ae9aac9e0e17a90a225caa2a0431 | 7,009 | //
// PPOneDriveService.swift
// PandaNote
//
// Created by Panway on 2021/8/2.
// Copyright © 2021 Panway. All rights reserved.
//
let onedrive_client_id_es = "dedcda2a-3acf-44bb-8baa-17f9ed544d64"
let onedrive_redirect_uri_es = "https://login.microsoftonline.com/common/oauth2/nativeclient"
let onedrive_client_id_pandanote = "064f5b62-97a8-4dae-b5c1-aaf44439939d"
let onedrive_redirect_uri_pandanote = "pandanote://msredirect"
let onedrive_login_url_es = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=dedcda2a-3acf-44bb-8baa-17f9ed544d64&scope=User.Read%20offline_access%20files.readwrite.all&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient&response_type=code"
import UIKit
import FilesProvider
import Alamofire
class PPOneDriveService: PPFilesProvider, PPCloudServiceProtocol {
var url = "https://graph.microsoft.com"
var access_token = ""
var refresh_token = ""
var baseURL: String {
return url
}
var onedrive: OneDriveFileProvider
init(access_token: String,refresh_token: String) {
let userCredential = URLCredential(user: "anonymous",
password: access_token,
persistence: .forSession)
self.access_token = access_token
self.refresh_token = refresh_token
onedrive = OneDriveFileProvider(credential: userCredential)
}
func getNewToken() {
let parameters: [String: String] = [
"client_id": onedrive_client_id_es,
"redirect_uri": onedrive_redirect_uri_es,
"refresh_token": self.refresh_token,
"grant_type": "refresh_token"
]
// debugPrint("getNewToken==\(parameters)")
let url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
AF.request(url, method: .post, parameters: parameters).responseJSON { response in
debugPrint(response.value)
let jsonDic = response.value as? [String : Any]
// let access_token = jsonDic["access_token"] as? String
if let access_token = jsonDic?["access_token"] as? String,let refresh_token = jsonDic?["refresh_token"] as? String {
debugPrint("microsoft access_token is:",access_token)
let userCredential = URLCredential(user: "anonymous",
password: access_token,
persistence: .forSession)
self.refresh_token = refresh_token
self.access_token = access_token
self.onedrive = OneDriveFileProvider(credential: userCredential)
print("=====refresh_token=====\n\(refresh_token)")
print("=====access_token=====\n\(access_token)")
//更新
var serverList = PPUserInfo.shared.pp_serverInfoList
var current = serverList[PPUserInfo.shared.pp_lastSeverInfoIndex]
current["PPWebDAVPassword"] = access_token
current["PPCloudServiceExtra"] = refresh_token
// current["PPCloudServiceExtra"] =
#warning("todo")
// self.refresh_token = current["PPCloudServiceExtra"]!
serverList.remove(at: PPUserInfo.shared.pp_lastSeverInfoIndex)
serverList.insert(current, at: PPUserInfo.shared.pp_lastSeverInfoIndex)
PPUserInfo.shared.pp_serverInfoList = serverList
}
}
return
}
func contentsOfDirectory(_ path: String, completionHandler: @escaping ([PPFileObject], Error?) -> Void) {
contentsOfPathID(path, completionHandler: completionHandler)
}
func contentsOfPathID(_ pathID: String, completionHandler: @escaping ([PPFileObject], Error?) -> Void) {
var requestURL = "https://graph.microsoft.com/v1.0/me/drive/items/\(pathID)/children?%24expand=thumbnails&%24top=200"
if pathID == "/" {
requestURL = "https://graph.microsoft.com/v1.0/me/drive/root/children?%24expand=thumbnails&%24top=200"
}
let headers: HTTPHeaders = [
"Authorization": "bearer " + self.access_token
]
AF.request(requestURL, method: .get,headers: headers).responseJSON { response in
let jsonDic = response.value as? [String : Any]
if response.response?.statusCode == 401 {
self.getNewToken()
return
}
if let fileList = jsonDic?["value"] as? [[String:Any]] {
var dataSource = [PPFileObject]()
for oneDriveFile in fileList {
// debugPrint("----------\(oneDriveFile)")
if let item = PPOneDriveFile(JSON: oneDriveFile) {
item.downloadURL = oneDriveFile["@microsoft.graph.downloadUrl"] as? String ?? ""
if item.folder != nil {
item.isDirectory = true
}
dataSource.append(item)
}
//@microsoft.graph.downloadUrl name size lastModifiedDateTime
}
DispatchQueue.main.async {
completionHandler(dataSource,nil)
}
}
}
/*
onedrive.contentsOfDirectory(path: path, completionHandler: {
contents, error in
let archieveArray = self.myPPFileArrayFrom(contents)
DispatchQueue.main.async {
completionHandler(archieveArray,error)
}
})
*/
}
func contentsOfFile(_ path: String, completionHandler: @escaping (Data?, Error?) -> Void) {
AF.request(path).response { response in
completionHandler(response.data, nil)
}
}
func createDirectory(_ folderName: String, at atPath: String, completionHandler: @escaping (Error?) -> Void) {
onedrive.create(folder: folderName, at: atPath, completionHandler: completionHandler)
}
func createFile(atPath path: String, contents: Data, completionHandler: @escaping (Error?) -> Void) {
onedrive.writeContents(path: path, contents: contents, overwrite: true, completionHandler: completionHandler)
}
func moveItem(atPath srcPath: String, toPath dstPath: String, completionHandler: @escaping (Error?) -> Void) {
onedrive.moveItem(path:srcPath, to: dstPath, completionHandler: completionHandler)
}
func removeItem(atPath path: String, completionHandler: @escaping (Error?) -> Void) {
onedrive.removeItem(path:path, completionHandler: completionHandler)
}
}
| 43 | 287 | 0.589242 |
622d9d231383df9da6e0387ee74ca737aede3f2c | 1,290 | //
// AppDelegate.swift
// FoursquarePlaces
//
// Created by Ali Elsokary on 21/12/2021.
//
//
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.
}
}
| 37.941176 | 176 | 0.786822 |
56f6a8dc4e745e4294c4e584aeb4baedb60cca5b | 342 | //
// Choice.swift
// HardChoice
//
// Created by 杨萧玉 on 15/4/15.
// Copyright (c) 2015年 杨萧玉. All rights reserved.
//
import Foundation
import CoreData
@objc(Choice)
public class Choice: NSManagedObject {
@NSManaged public var name: String
@NSManaged public var weight: NSNumber
@NSManaged public var question: Question
}
| 17.1 | 49 | 0.704678 |
7575d25e0358307943ab0c64690e9ec0a5526592 | 120 | import XCTest
import paperworkTests
var tests = [XCTestCaseEntry]()
tests += paperworkTests.allTests()
XCTMain(tests)
| 15 | 34 | 0.783333 |
dba0f754e414d3a716f239024624da8d09801cbb | 2,548 | // O(N^3)
// Runtime: 472 ms, faster than 16.67% of Swift online submissions for Valid Triangle Number.
// Memory Usage: 22.8 MB, less than 33.33% of Swift online submissions for Valid Triangle Number.
func factorial(from: Int, to: Int) -> Int {
return (from...to).reduce(1, { pre, current in pre * current })
}
func c(all: Int, pick: Int) -> Int {
if all == pick { return 1 }
let k = max(pick, all - pick)
return factorial(from: k+1, to: all) / factorial(from: 1, to: all - k)
}
class Solution {
func triangleNumber(_ nums: [Int]) -> Int {
var counts: [Int:Int] = [:]
nums.filter({ $0 != 0}).forEach({ n in
if let count = counts[n] {
counts[n] = count + 1
} else {
counts[n] = 1
}
})
var total = 0
let indices = Array(counts).map({ $0.key }).sorted(by: >)
for (i, a) in indices.enumerated() {
let aCount = counts[a]!
if aCount >= 3 {
total += c(all: aCount, pick: 3)
}
let fromI = indices.dropFirst(i+1)
for (j, b) in fromI.enumerated() {
let bCount = counts[b]!
if (aCount > 1) {
total += c(all: aCount, pick: 2) * bCount
}
if b * 2 <= a && aCount == 1 { break }
if b * 2 <= a { continue }
if (bCount > 1) {
total += aCount * c(all: bCount, pick: 2)
}
for c in fromI.dropFirst(j+1) {
if b + c <= a { break }
let cCount = counts[c]!
total += aCount * bCount * cCount
}
}
}
return total
}
}
// O(n^2)
// Runtime: 720 ms, faster than 8.33% of Swift online submissions for Valid Triangle Number.
// Memory Usage: 21.4 MB, less than 33.33% of Swift online submissions for Valid Triangle Number.
class Solution {
func triangleNumber(_ nums: [Int]) -> Int {
let sorted = nums.sorted(by: >)
var count = 0
for (i, a) in sorted.dropLast().enumerated() {
var slice = sorted.dropFirst(i+1)
while slice.count >= 2, let b = slice.first, let c = slice.last {
if b + c > a {
count += slice.count - 1
slice = slice.dropFirst()
} else {
slice = slice.dropLast()
}
}
}
return count
}
}
| 31.85 | 97 | 0.467818 |
28392c7c502c0e82334e5b64aa0898e97a11bbd3 | 2,748 | // Copyright (c) 2019 Razeware LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
// distribute, sublicense, create a derivative work, and/or sell copies of the
// Software in any work that is designed, intended, or marketed for pedagogical or
// instructional purposes related to programming, coding, application development,
// or information technology. Permission for such use, copying, modification,
// merger, publication, distribution, sublicensing, creation of derivative works,
// or sale is expressly withheld.
//
// 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 Combine
enum RequestDownloadResult {
case downloadRequestedSuccessfully
case downloadRequestedButQueueInactive
}
enum DownloadActionError: Error {
case downloadNotPermitted
case downloadContentNotFound
case problemRequestingDownload
case unableToCancelDownload
case unableToDeleteDownload
var localizedDescription: String {
switch self {
case .downloadNotPermitted:
return Constants.downloadNotPermitted
case .downloadContentNotFound:
return Constants.downloadContentNotFound
case .problemRequestingDownload:
return Constants.downloadRequestProblem
case .unableToCancelDownload:
return Constants.downloadUnableToCancel
case .unableToDeleteDownload:
return Constants.downloadUnableToDelete
}
}
}
protocol DownloadAction {
func requestDownload(contentId: Int, contentLookup: @escaping ContentLookup) -> AnyPublisher<RequestDownloadResult, DownloadActionError>
func cancelDownload(contentId: Int) -> AnyPublisher<Void, DownloadActionError>
func deleteDownload(contentId: Int) -> AnyPublisher<Void, DownloadActionError>
}
| 42.9375 | 138 | 0.783115 |
9b60942aca9f1b4d5f7c6812a4519c32a0e32449 | 5,044 | //
// MockTransactionRepository.swift
// ZcashLightClientKit-Unit-Tests
//
// Created by Francisco Gindre on 12/6/19.
//
import Foundation
@testable import ZcashLightClientKit
class MockTransactionRepository: TransactionRepository {
var unminedCount: Int
var receivedCount: Int
var sentCount: Int
var transactions: [ConfirmedTransactionEntity] = []
var reference: [Kind] = []
var sentTransactions: [ConfirmedTransaction] = []
var receivedTransactions: [ConfirmedTransaction] = []
var allCount: Int {
receivedCount + sentCount
}
init(unminedCount: Int, receivedCount: Int, sentCount: Int) {
self.unminedCount = unminedCount
self.receivedCount = receivedCount
self.sentCount = sentCount
}
func generate() {
var txArray = [ConfirmedTransactionEntity]()
reference = referenceArray()
for i in 0 ..< reference.count {
txArray.append(mockTx(index: i, kind: reference[i]))
}
transactions = txArray
}
func countAll() throws -> Int {
allCount
}
func countUnmined() throws -> Int {
unminedCount
}
func findBy(id: Int) throws -> TransactionEntity? {
transactions.first(where: {$0.id == id})?.transactionEntity
}
func findBy(rawId: Data) throws -> TransactionEntity? {
transactions.first(where: {$0.rawTransactionId == rawId})?.transactionEntity
}
func findAllSentTransactions(offset: Int, limit: Int) throws -> [ConfirmedTransactionEntity]? {
guard let indices = reference.indices(where: { $0 == .sent }) else { return nil }
let sentTxs = indices.map { (idx) -> ConfirmedTransactionEntity in
transactions[idx]
}
return slice(txs: sentTxs, offset: offset, limit: limit)
}
func findAllReceivedTransactions(offset: Int, limit: Int) throws -> [ConfirmedTransactionEntity]? {
guard let indices = reference.indices(where: { $0 == .received }) else { return nil }
let receivedTxs = indices.map { (idx) -> ConfirmedTransactionEntity in
transactions[idx]
}
return slice(txs: receivedTxs, offset: offset, limit: limit)
}
func findAll(offset: Int, limit: Int) throws -> [ConfirmedTransactionEntity]? {
transactions
}
func lastScannedHeight() throws -> BlockHeight {
return 700000
}
func isInitialized() throws -> Bool {
true
}
func findEncodedTransactionBy(txId: Int) -> EncodedTransaction? {
nil
}
enum Kind {
case sent
case received
}
func referenceArray() -> [Kind] {
var template = [Kind]()
for _ in 0 ..< sentCount {
template.append(.sent)
}
for _ in 0 ..< receivedCount {
template.append(.received)
}
return template.shuffled()
}
func mockTx(index: Int, kind: Kind) -> ConfirmedTransactionEntity {
switch kind {
case .received:
return mockReceived(index)
case .sent:
return mockSent(index)
}
}
func mockSent(_ index: Int) -> ConfirmedTransactionEntity {
ConfirmedTransaction(toAddress: "some_address", expiryHeight: BlockHeight.max, minedHeight: randomBlockHeight(), noteId: index, blockTimeInSeconds: randomTimeInterval(), transactionIndex: index, raw: Data(), id: index, value: Int.random(in: 1 ... ZcashSDK.ZATOSHI_PER_ZEC), memo: nil, rawTransactionId: Data())
}
func mockReceived(_ index: Int) -> ConfirmedTransactionEntity {
ConfirmedTransaction(toAddress: nil, expiryHeight: BlockHeight.max, minedHeight: randomBlockHeight(), noteId: index, blockTimeInSeconds: randomTimeInterval(), transactionIndex: index, raw: Data(), id: index, value: Int.random(in: 1 ... ZcashSDK.ZATOSHI_PER_ZEC), memo: nil, rawTransactionId: Data())
}
func randomBlockHeight() -> BlockHeight {
BlockHeight.random(in: ZcashSDK.SAPLING_ACTIVATION_HEIGHT ... 1_000_000)
}
func randomTimeInterval() -> TimeInterval {
Double.random(in: Date().timeIntervalSince1970 - 1000000.0 ... Date().timeIntervalSince1970)
}
func slice(txs: [ConfirmedTransactionEntity], offset: Int, limit: Int) -> [ConfirmedTransactionEntity] {
guard offset < txs.count else { return [] }
return Array(txs[offset ..< min(offset + limit, txs.count - offset)])
}
}
extension MockTransactionRepository.Kind: Equatable {}
extension Array {
func indices(where f: (_ element: Element) -> Bool) -> [Int]? {
guard self.count > 0 else { return nil }
var idx = [Int]()
for i in 0 ..< self.count {
if f(self[i]) {
idx.append(i)
}
}
guard idx.count > 0 else { return nil }
return idx
}
}
| 31.525 | 318 | 0.609635 |
efa685b443f741625217e308a5aa5da65ed05a4a | 20,393 | //===--- Complex+ElementaryFunctions.swift --------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019-2020 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
//
//===----------------------------------------------------------------------===//
// Implementation goals, in order of priority:
//
// 1. Get the branch cuts right. We should match Kahan's /Much Ado/
// paper for finite values.
// 2. Have good relative accuracy in the complex norm.
// 3. Preserve sign symmetries where possible.
// 4. Handle the point at infinity consistently with basic operations.
// This means diverging from what C and C++ do for non-finite inputs.
// 5. Get good componentwise accuracy /when possible/. I don't know how
// to do that for all of these functions off the top of my head, and
// I don't think that other libraries have tried to do so in general,
// so this is a research project. We should not sacrifice 1-4 for it.
// Note that multiplication and division don't even provide good
// componentwise relative accuracy, so it's _totally OK_ to not get
// it for these functions too. But: it's a dynamite long-term research
// project.
// 6. Give the best performance we can. We should care about performance,
// but with lower precedence than the other considerations.
//
// Except where derivations are given, the expressions used here are all
// adapted from Kahan's 1986 paper "Branch Cuts for Complex Elementary
// Functions; or: Much Ado About Nothing's Sign Bit".
import RealModule
extension Complex: ElementaryFunctions {
// MARK: - exp-like functions
/// The complex exponential function e^z whose base `e` is the base of the
/// natural logarithm.
///
/// Mathematically, this operation can be expanded in terms of the `Real`
/// operations `exp`, `cos` and `sin` as follows:
/// ```
/// exp(x + iy) = exp(x) exp(iy)
/// = exp(x) cos(y) + i exp(x) sin(y)
/// ```
/// Note that naive evaluation of this expression in floating-point would be
/// prone to premature overflow, since `cos` and `sin` both have magnitude
/// less than 1 for most inputs (i.e. `exp(x)` may be infinity when
/// `exp(x) cos(y)` would not be).
@inlinable
public static func exp(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
// If x < log(greatestFiniteMagnitude), then exp(x) does not overflow.
// To protect ourselves against sketchy log or exp implementations in
// an unknown host library, or slight rounding disagreements between
// the two, subtract one from the bound for a little safety margin.
guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {
let halfScale = RealType.exp(z.x/2)
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
return phase.multiplied(by: halfScale).multiplied(by: halfScale)
}
return Complex(.cos(z.y), .sin(z.y)).multiplied(by: .exp(z.x))
}
@inlinable
public static func expMinusOne(_ z: Complex) -> Complex {
// exp(x + iy) - 1 = (exp(x) cos(y) - 1) + i exp(x) sin(y)
// -------- u --------
// Note that the imaginary part is just the usual exp(x) sin(y);
// the only trick is computing the real part ("u"):
//
// u = exp(x) cos(y) - 1
// = exp(x) cos(y) - cos(y) + cos(y) - 1
// = (exp(x) - 1) cos(y) + (cos(y) - 1)
// = expMinusOne(x) cos(y) + cosMinusOne(y)
//
// Note: most implementations of expm1 for complex (e.g. Julia's)
// factor the real part as follows instead:
//
// exp(x) cosMinuxOne(y) + expMinusOne(x)
//
// The other implementation that is sometimes seen is:
//
// expMinusOne(z) = 2*exp(z/2)*sinh(z/2)
//
// All three of these implementations provide good relative error
// bounds _in the complex norm_, but the cosineMinusOne-based
// implementation has the best _componentwise_ error characteristics,
// which is why we use it here:
//
// Implementation | Real | Imaginary |
// ---------------+--------------------+----------------+
// Ours | Hybrid bound | Relative bound |
// Standard | No bound | Relative bound |
// Half Angle | Hybrid bound | Hybrid bound |
//
// FUTURE WORK: devise an algorithm that achieves good _relative_ error
// in the real component as well. Doing this efficiently is a research
// project--exp(x) cos(y) - 1 can be very nearly zero along a curve in
// the complex plane, not only at zero. Evaluating it accurately
// _without_ depending on arbitrary-precision exp and cos is an
// interesting challenge.
guard z.isFinite else { return z }
// If exp(z) is close to the overflow boundary, we don't need to
// worry about the "MinusOne" part of this function; we're just
// computing exp(z). (Even when z.y is near a multiple of π/2,
// it can't be close enough to overcome the scaling from exp(z.x),
// so the -1 term is _always_ negligable). So we simply handle
// these cases exactly the same as exp(z).
guard z.x < RealType.log(.greatestFiniteMagnitude) - 1 else {
let halfScale = RealType.exp(z.x/2)
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
return phase.multiplied(by: halfScale).multiplied(by: halfScale)
}
// Special cases out of the way, evaluate as discussed above.
return Complex(
RealType._mulAdd(.cos(z.y), .expMinusOne(z.x), .cosMinusOne(z.y)),
.exp(z.x) * .sin(z.y)
)
}
// cosh(x + iy) = cosh(x) cos(y) + i sinh(x) sin(y).
//
// Like exp, cosh is entire, so we do not need to worry about where
// branch cuts fall. Also like exp, cancellation never occurs in the
// evaluation of the naive expression, so all we need to be careful
// about is the behavior near the overflow boundary.
//
// Fortunately, if |x| >= -log(ulpOfOne), cosh(x) and sinh(x) are
// both just exp(|x|)/2, and we already know how to compute that.
//
// This function and sinh should stay in sync; if you make a
// modification here, you should almost surely make a parallel
// modification to sinh below.
@inlinable
public static func cosh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
let firstScale = RealType.exp(z.x.magnitude/2)
let secondScale = firstScale/2
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
}
// Future optimization opportunity: expm1 is faster than cosh/sinh
// on most platforms, and division is now commonly pipelined, so we
// might replace the check above with a much more conservative one,
// and then evaluate cosh(x) and sinh(x) as
//
// cosh(x) = 1 + 0.5*expm1(x)*expm1(x) / (1 + expm1(x))
// sinh(x) = expm1(x) + 0.5*expm1(x) / (1 + expm1(x))
//
// This won't be a _big_ win except on platforms with a crappy sinh
// and cosh, and for those we should probably just provide our own
// implementations of _those_, so for now let's keep it simple and
// obviously correct.
return Complex(
RealType.cosh(z.x) * RealType.cos(z.y),
RealType.sinh(z.x) * RealType.sin(z.y)
)
}
// sinh(x + iy) = sinh(x) cos(y) + i cosh(x) sin(y)
//
// See cosh above for algorithm details.
@inlinable
public static func sinh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
let phase = Complex(RealType.cos(z.y), RealType.sin(z.y))
let firstScale = RealType.exp(z.x.magnitude/2)
let secondScale = RealType(signOf: z.x, magnitudeOf: firstScale/2)
return phase.multiplied(by: firstScale).multiplied(by: secondScale)
}
return Complex(
RealType.sinh(z.x) * RealType.cos(z.y),
RealType.cosh(z.x) * RealType.sin(z.y)
)
}
// tanh(z) = sinh(z) / cosh(z)
@inlinable
public static func tanh(_ z: Complex) -> Complex {
guard z.isFinite else { return z }
// Note that when |x| is larger than -log(.ulpOfOne),
// sinh(x + iy) == ±cosh(x + iy), so tanh(x + iy) is just ±1.
guard z.x.magnitude < -RealType.log(.ulpOfOne) else {
return Complex(
RealType(signOf: z.x, magnitudeOf: 1),
RealType(signOf: z.y, magnitudeOf: 0)
)
}
// Now we have z in a vertical strip where exp(x) is reasonable,
// and y is finite, so we can simply evaluate sinh(z) and cosh(z).
//
// TODO: Kahan uses a different expression for evaluation here; it
// isn't strictly necessary for numerics reasons--it's to avoid
// doing the complex division, but it probably provides better
// componentwise error bounds, and is likely more efficient (because
// it avoids the complex division, which is painful even when well-
// scaled). This suffices to get us up and running.
return sinh(z) / cosh(z)
}
// cos(z) = cosh(iz)
@inlinable
public static func cos(_ z: Complex) -> Complex {
return cosh(Complex(-z.y, z.x))
}
// sin(z) = -i*sinh(iz)
@inlinable
public static func sin(_ z: Complex) -> Complex {
let w = sinh(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
// tan(z) = -i*tanh(iz)
@inlinable
public static func tan(_ z: Complex) -> Complex {
let w = tanh(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
// MARK: - log-like functions
@inlinable
public static func log(_ z: Complex) -> Complex {
// If z is zero or infinite, the phase is undefined, so the result is
// the single exceptional value.
guard z.isFinite && !z.isZero else { return .infinity }
// Having eliminated non-finite values and zero, the imaginary part is
// easy; it's just the phase, which is always computed with good
// relative accuracy via atan2.
let θ = z.phase
// The real part of the result is trickier. In exact arithmetic, the
// real part is just log |z|--many implementations of complex functions
// simply use this expression as is. However, there are two problems
// lurking here:
//
// - length can overflow even when log(z) is finite.
//
// - when length is close to 1, catastrophic cancellation is hidden
// in this expression. Consider, e.g. z = 1 + δi for small δ.
//
// Because δ ≪ 1, |z| rounds to 1, and so log |z| produces zero.
// We can expand using Taylor series to see that the result should
// be:
//
// log |z| = log √(1 + δ²)
// = log(1 + δ²)/2
// = δ²/2 + O(δ⁴)
//
// So naively using log |z| results in a total loss of relative
// accuracy for this case. Note that this is _not_ constrained near
// a single point; it occurs everywhere close to the circle |z| = 1.
//
// Note that this case still _does_ deliver a result with acceptable
// relative accuracy in the complex norm, because
//
// Im(log z) ≈ δ ≫ δ²/2 ≈ Re(log z).
//
// There are a number of ways to try to tackle this problem. I'll begin
// with a simple one that solves the first issue, and _sometimes_ the
// second, then analyze when it doesn't work for the second case.
//
// To handle very large arguments without overflow, the standard
// approach is to _rescale_ the problem. We can do this by finding
// whichever of x and y has greater magnitude, and dividing through
// by it. You can think of this as changing coordinates by reflections
// so that we get a new value w = u + iv with |w| = |z| (and hence
// Re(log w) = Re(log z), and 0 ≤ u, 0 ≤ v ≤ u.
let u = max(z.x.magnitude, z.y.magnitude)
let v = min(z.x.magnitude, z.y.magnitude)
// Now expand out log |w|:
//
// log |w| = log(u² + v²)/2
// = log u + log(onePlus: (v/u)²)/2
//
// This looks promising! It handles overflow well, because log(u) is
// finite for every finite u, and we have 0 ≤ v/u ≤ 1, so the second
// term is bounded by 0 ≤ log(1 + (v/u)²)/2 ≤ (log 2)/2. It also
// handles the example I gave above well: we have u = 1, v = δ, and
//
// log(1) + log(onePlus: δ²)/2 = 0 + δ²/2
//
// as expected.
//
// Unfortunately, it does not handle all points close to the unit
// circle so well; it's easy to see why if we look at the two terms
// that contribute to the result. Cancellation occurs when the result
// is close to zero and the terms have opposing signs. By construction,
// the second term is always positive, so the easiest observation is
// that cancellation is only a problem for u < 1 (because otherwise
// log u is also positive, and there can be no cancellation).
//
// We are not trying for sub-ulp accuracy, just a good relative error
// bound, so for our purposes it suffices to have log u dominate the
// result:
if u >= 1 || u >= RealType._mulAdd(u,u,v*v) {
let r = v / u
return Complex(.log(u) + .log(onePlus: r*r)/2, θ)
}
// Here we're in the tricky case; cancellation is likely to occur.
// Instead of the factorization used above, we will want to evaluate
// log(onePlus: u² + v² - 1)/2. This all boils down to accurately
// evaluating u² + v² - 1. To begin, calculate both squared terms
// as exact head-tail products (u is guaranteed to be well scaled,
// v may underflow, but if it does it doesn't matter, the u term is
// all we need).
let (a,b) = Augmented.product(u, u)
let (c,d) = Augmented.product(v, v)
// It would be nice if we could simply use a - 1, but unfortunately
// we don't have a tight enough bound to guarantee that that expression
// is exact; a may be as small as 1/4, so we could lose a single bit
// to rounding if we did that.
var (s,e) = Augmented.sum(large: -1, small: a)
// Now we are ready to assemble the result. If cancellation happens,
// then |c| > |e| > |b|, |d|, so this assembly order is safe. It's
// also possible that |c| and |d| are small, but if that happens then
// there is no significant cancellation, and the exact assembly doesn't
// matter.
s = (s + c) + e + b + d
return Complex(.log(onePlus: s)/2, θ)
}
@inlinable
public static func log(onePlus z: Complex) -> Complex {
// If either |x| or |y| is bounded away from the origin, we don't need
// any extra precision, and can just literally compute log(1+z). Note
// that this includes part of the circle |1+z| = 1 where log(onePlus:)
// vanishes (where x <= -0.5), but on this portion of the circle 1+x
// is always exact by Sterbenz' lemma, so as long as log( ) produces
// a good result, log(1+z) will too.
guard 2*z.x.magnitude < 1 && z.y.magnitude < 1 else { return log(1+z) }
// z is in (±0.5, ±1), so we need to evaluate more carefully.
// The imaginary part is straightforward:
let θ = (1+z).phase
// For the real part, we _could_ use the same approach that we do for
// log( ), but we'd need an extra-precise (1+x)², which can potentially
// be quite painful to calculate. Instead, we can use an approach that
// NevinBR suggested on the Swift forums:
//
// Re(log(1+z)) = (log(1+z) + log(1+z̅)) / 2
// = log((1+z)(1+z̅)) / 2
// = log(1 + z + z̅ + zz̅) / 2
// = log(1 + 2x + x² + y²) / 2
// = log(onePlus: (2+x)x + y²) / 2
//
// So now we need to evaluate (2+x)x + y² accurately. To do this,
// we employ augmented arithmetic; the key observation here is that
// cancellation is only a problem when y² ≈ -(2+x)x
let xp2 = Augmented.sum(large: 2, small: z.x) // Known that 2 > |x|.
let a = Augmented.product(z.x, xp2.head)
let y² = Augmented.product(z.y, z.y)
let s = (a.head + y².head + a.tail + y².tail).addingProduct(z.x, xp2.tail)
return Complex(.log(onePlus: s)/2, θ)
}
@inlinable
public static func acos(_ z: Complex) -> Complex {
Complex(
2*RealType.atan2(y: sqrt(1-z).real, x: sqrt(1+z).real),
RealType.asinh((sqrt(1+z).conjugate * sqrt(1-z)).imaginary)
)
}
@inlinable
public static func asin(_ z: Complex) -> Complex {
Complex(
RealType.atan2(y: z.x, x: (sqrt(1-z) * sqrt(1+z)).real),
RealType.asinh((sqrt(1-z).conjugate * sqrt(1+z)).imaginary)
)
}
// atan(z) = -i*atanh(iz)
@inlinable
public static func atan(_ z: Complex) -> Complex {
let w = atanh(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
@inlinable
public static func acosh(_ z: Complex) -> Complex {
Complex(
RealType.asinh((sqrt(z-1).conjugate * sqrt(z+1)).real),
2*RealType.atan2(y: sqrt(z-1).imaginary, x: sqrt(z+1).real)
)
}
// asinh(z) = -i*asin(iz)
@inlinable
public static func asinh(_ z: Complex) -> Complex {
let w = asin(Complex(-z.y, z.x))
return Complex(w.y, -w.x)
}
@inlinable
public static func atanh(_ z: Complex) -> Complex {
// TODO: Kahan uses a much more complicated expression here; possibly
// simply because he didn't have a complex log(1+z) with good
// characteristics. Investigate tradeoffs further.
//
// Further TODO: decide policy for point at infinity / NaN. Unlike most
// of these functions, atanh doesn't have a pole at infinity; convention
// in C-family languages is use one value in the upper half plane, and
// another in the lower. Requires some thought about the most appropriate
// way to handle this case in Swift.
(log(onePlus: z) - log(onePlus:-z))/2
}
// MARK: - pow-like functions
@inlinable
public static func pow(_ z: Complex, _ w: Complex) -> Complex {
return exp(w * log(z))
}
@inlinable
public static func pow(_ z: Complex, _ n: Int) -> Complex {
if z.isZero { return .zero }
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to RealType. This only effects very extreme
// cases, so we'll leave it alone for now.
//
// Note that this does not have the same problems that a similar
// implementation for a real type would have, because there's no
// parity/sign interaction in the complex plane.
return exp(log(z).multiplied(by: RealType(n)))
}
@inlinable
public static func sqrt(_ z: Complex) -> Complex {
let lengthSquared = z.lengthSquared
if lengthSquared.isNormal {
// If |z|^2 doesn't overflow, then define u and v by:
//
// u = sqrt((|z|+|x|)/2)
// v = y/2u
//
// If x is positive, the result is just w = (u, v). If x is negative,
// the result is (|v|, copysign(u, y)) instead.
let norm = RealType.sqrt(lengthSquared)
let u = RealType.sqrt((norm + abs(z.x))/2)
let v: RealType = z.y / (2*u)
if z.x.sign == .plus {
return Complex(u, v)
} else {
return Complex(abs(v), RealType(signOf: z.y, magnitudeOf: u))
}
}
// Handle edge cases:
if z.isZero { return Complex(0, z.y) }
if !z.isFinite { return z }
// z is finite but badly-scaled. Rescale and replay by factoring out
// the larger of x and y.
let scale = RealType.maximum(abs(z.x), abs(z.y))
return Complex.sqrt(z.divided(by: scale)).multiplied(by: .sqrt(scale))
}
@inlinable
public static func root(_ z: Complex, _ n: Int) -> Complex {
if z.isZero { return .zero }
// TODO: this implementation is not quite correct, because n may be
// rounded in conversion to RealType. This only effects very extreme
// cases, so we'll leave it alone for now.
//
// Note that this does not have the same problems that a similar
// implementation for a real type would have, because there's no
// parity/sign interaction in the complex plane.
return exp(log(z).divided(by: RealType(n)))
}
}
| 42.842437 | 80 | 0.622812 |
e8e31f8b0cba967086011d95a4e99547ddde9cbc | 3,006 | import Foundation
public protocol OpenGraphParser {
func parse(htmlString: String) -> [OpenGraphMetadata: String]
}
extension OpenGraphParser {
func parse(htmlString: String) -> [OpenGraphMetadata: String] {
// extract meta tag
let metatagRegex = try! NSRegularExpression(
pattern: "<meta(?:\".*?\"|\'.*?\'|[^\'\"])*?>",
options: [.dotMatchesLineSeparators]
)
let metaTagMatches = metatagRegex.matches(in: htmlString,
options: [],
range: NSMakeRange(0, htmlString.count))
if metaTagMatches.isEmpty {
return [:]
}
// prepare regular expressions to extract og property and content.
let propertyRegexp = try! NSRegularExpression(
pattern: "\\sproperty=(?:\"|\')*og:([a-zA_Z:]+)(?:\"|\')*",
options: []
)
let contentRegexp = try! NSRegularExpression(
pattern: "\\scontent=\\\\*?\"(.*?)\\\\*?\"",
options: []
)
// create attribute dictionary
let nsString = htmlString as NSString
let attributes = metaTagMatches.reduce([OpenGraphMetadata: String]()) { (attributes, result) -> [OpenGraphMetadata: String] in
var copiedAttributes = attributes
let property = { () -> (name: String, content: String)? in
let metaTag = nsString.substring(with: result.range(at: 0))
let propertyMatches = propertyRegexp.matches(in: metaTag,
options: [],
range: NSMakeRange(0, metaTag.count))
guard let propertyResult = propertyMatches.first else { return nil }
var contentMatches = contentRegexp.matches(in: metaTag, options: [], range: NSMakeRange(0, metaTag.count))
if contentMatches.first == nil {
let contentRegexp = try! NSRegularExpression(
pattern: "\\scontent=\\\\*?'(.*?)\\\\*?'",
options: []
)
contentMatches = contentRegexp.matches(in: metaTag, options: [], range: NSMakeRange(0, metaTag.count))
}
guard let contentResult = contentMatches.first else { return nil }
let nsMetaTag = metaTag as NSString
let property = nsMetaTag.substring(with: propertyResult.range(at: 1))
let content = nsMetaTag.substring(with: contentResult.range(at: 1))
return (name: property, content: content)
}()
if let property = property, let metadata = OpenGraphMetadata(rawValue: property.name) {
copiedAttributes[metadata] = property.content
}
return copiedAttributes
}
return attributes
}
}
| 44.205882 | 134 | 0.522954 |
d702b7e19e441cbadc1a2f44f14856156fc3a725 | 452 | //
// DCDateFormatter+WF.swift
// WFAPPCore
//
// Created by Dario Carlomagno on 02/08/2019.
//
import Foundation
extension DCDateFormatter {
// MARK: - DOB
public func dateOfBirthAsString(from date: Date) -> String {
return string(from: date, format: .readableDateWithSpace)
}
public func dateOfBirth(from string: String) -> Date? {
return date(from: string, format: .readableDateWithSpace)
}
}
| 20.545455 | 65 | 0.650442 |
c1fdb137d4c1c1d3fe3bd7cd6072c552f177372c | 136 | import XCTest
import NohanaImagePickerTests
var tests = [XCTestCaseEntry]()
tests += NohanaImagePickerTests.allTests()
XCTMain(tests)
| 17 | 42 | 0.808824 |
fc2c3b162dd018f512c1b17c53762ed81c21d3e2 | 2,164 | //
// AppDelegate.swift
// TableViewIndentSample
//
// Created by 能登 要 on 2016/01/28.
// Copyright © 2016年 Irimasu Densan Planning. 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:.
}
}
| 46.042553 | 285 | 0.755545 |
2208ccd1af5b502a0b53cba29df573f6900faa2a | 838 | //
// SBWebService+Pilots.swift
// Runway
//
// Created by Jelle Vandenbeeck on 29/09/15.
// Copyright © 2015 Soaring Book. All rights reserved.
//
import Foundation
extension SBWebService {
func fetchPilots(handleUpdatedAt handleUpdatedAt: Bool = true, callback: (SBWebServiceResponse) -> ()) {
var path = "pilots.json"
if let updatedAt = SBConfiguration().pilotsLastUpdatedAt where handleUpdatedAt {
let formattedUpdatedAt = SBDateFormatter.sharedInstance.apiFormatter.stringFromDate(updatedAt)
path = "\(path)?last_updated_at=\(formattedUpdatedAt)"
}
fetchRequest(path: path, callback: callback)
}
func fetchPilotImage(pilot: Pilot, callback: (SBWebServiceResponse) -> ()) {
self.fetchImageRequest(path: pilot.imageURL, callback: callback)
}
} | 34.916667 | 109 | 0.690931 |
ef7177e42982fc1ce852bdac6b035d09cfcf6eb7 | 1,848 | /*
* Copyright 2016 chaoyang805 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
class MenuViewController: UIViewController {
// MARK: - Properties
weak var delegate: MenuViewControllerDelegate?
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - IBActions
@IBAction func inTheaterButtonPressed(_ sender: AnyObject) {
dismiss(animated: false) {
self.delegate?.menuViewController(self, didClickButtonWithType: .now)
}
}
@IBAction func searchButtonPressed(_ sender: AnyObject) {
dismiss(animated: false) {
self.delegate?.menuViewController(self, didClickButtonWithType: .search)
}
}
@IBAction func allMovieButtonPressed(_ sender: AnyObject) {
dismiss(animated: false) {
self.delegate?.menuViewController(self, didClickButtonWithType: .all)
}
}
@IBAction func favoritesButtonPressed(_ sender: AnyObject) {
dismiss(animated: false) {
self.delegate?.menuViewController(self, didClickButtonWithType: .favorite)
}
}
// MARK: - Segues
override func unwindSegue(_ sender: UIStoryboardSegue) {
super.unwindSegue(sender)
}
}
| 29.806452 | 86 | 0.667208 |
bf0565ef89439d14436d8ee362b4250f062a7cec | 777 | // Check a handful of failures in the driver when TMPDIR can't be accessed.
//
// These particular error messages are kind of finicky to hit because they
// depend on what commands the driver needs to execute on each platform, so the
// test is somewhat artificially limited to macOS.
//
// REQUIRES: OS=macosx
// RUN: env TMP="%t/fake/" TMPDIR="%t/fake/" not %target-build-swift -c -driver-filelist-threshold=0 %s 2>&1 | %FileCheck -check-prefix=CHECK-SOURCES %s
// CHECK-SOURCES: - unable to create list of input sources
// RUN: echo > %t.o
// RUN: env TMP="%t/fake/" TMPDIR="%t/fake/" not %target-build-swift -driver-filelist-threshold=0 %t.o 2>&1 | %FileCheck -check-prefix=CHECK-FILELIST %s
// CHECK-FILELIST: - unable to create temporary file for inputs.LinkFileList
| 45.705882 | 152 | 0.722008 |
098e72a5e22fd2b957e8883c4003cf4ba6d8891d | 168 | //
// Package.swift
// Lambda
//
//
import PackageDescription
let package = Package(
name: "Lambda",
targets: [
Target(name: "Lambda", dependencies: []),
]
)
| 10.5 | 43 | 0.619048 |
e4d6f464bb7565984bfe025f0c0492f24d06e3b5 | 14,852 | //
// Copyright © 2016 Schnaub. All rights reserved.
//
import SwiftyGif
import UIKit
protocol AgrumeCellDelegate: AnyObject {
var isSingleImageMode: Bool { get }
func dismissAfterFlick()
func dismissAfterTap()
func toggleOverlayVisibility()
}
final class AgrumeCell: UICollectionViewCell {
var tapBehavior: Agrume.TapBehavior = .dismissIfZoomedOut
var hasPhysics = true
private lazy var scrollView = with(UIScrollView()) { scrollView in
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.delegate = self
scrollView.zoomScale = 1
scrollView.maximumZoomScale = 8
scrollView.isScrollEnabled = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
}
private lazy var imageView = with(UIImageView()) { imageView in
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.layer.allowsEdgeAntialiasing = true
}
private lazy var singleTapGesture = with(UITapGestureRecognizer(target: self, action: #selector(singleTap))) { gesture in
gesture.require(toFail: doubleTapGesture)
gesture.delegate = self
}
private lazy var doubleTapGesture = with(UITapGestureRecognizer(target: self, action: #selector(doubleTap))) { gesture in
gesture.numberOfTapsRequired = 2
}
private lazy var panGesture = with(UIPanGestureRecognizer(target: self, action: #selector(dismissPan))) { gesture in
gesture.maximumNumberOfTouches = 1
gesture.delegate = self
}
private var animator: UIDynamicAnimator?
private var flickedToDismiss = false
private var isDraggingImage = false
private var imageDragStartingPoint: CGPoint!
private var imageDragOffsetFromActualTranslation: UIOffset!
private var imageDragOffsetFromImageCenter: UIOffset!
private var attachmentBehavior: UIAttachmentBehavior?
var image: UIImage? {
didSet {
if image?.imageData != nil, let image = image {
imageView.setGifImage(image)
} else {
imageView.image = image
}
updateScrollViewAndImageViewForCurrentMetrics()
}
}
weak var delegate: AgrumeCellDelegate?
private(set) lazy var swipeGesture = with(UISwipeGestureRecognizer(target: self, action: nil)) { gesture in
gesture.direction = [.left, .right]
gesture.delegate = self
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
contentView.addSubview(scrollView)
scrollView.addSubview(imageView)
setupGestureRecognizers()
if hasPhysics {
animator = UIDynamicAnimator(referenceView: scrollView)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
scrollView.zoomScale = 1
updateScrollViewAndImageViewForCurrentMetrics()
}
private func setupGestureRecognizers() {
contentView.addGestureRecognizer(singleTapGesture)
contentView.addGestureRecognizer(doubleTapGesture)
scrollView.addGestureRecognizer(panGesture)
contentView.addGestureRecognizer(swipeGesture)
}
func cleanup() {
animator = nil
}
}
extension AgrumeCell: UIGestureRecognizerDelegate {
private var notZoomed: Bool {
scrollView.zoomScale == 1
}
private var isImageViewOffscreen: Bool {
let visibleRect = scrollView.convert(contentView.bounds, from: contentView)
return animator?.items(in: visibleRect).isEmpty == true
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if notZoomed, let pan = gestureRecognizer as? UIPanGestureRecognizer {
let velocity = pan.velocity(in: scrollView)
if delegate?.isSingleImageMode == true {
return true
}
return abs(velocity.y) > abs(velocity.x)
} else if notZoomed, gestureRecognizer as? UISwipeGestureRecognizer != nil {
return false
}
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer as? UIPanGestureRecognizer != nil {
return notZoomed
}
return true
}
@objc
private func doubleTap(_ sender: UITapGestureRecognizer) {
let point = scrollView.convert(sender.location(in: sender.view), from: sender.view)
if notZoomed {
zoom(to: point, scale: .targetZoomForDoubleTap)
} else {
zoom(to: .zero, scale: 1)
}
}
private func zoom(to point: CGPoint, scale: CGFloat) {
let factor = 1 / scrollView.zoomScale
let translatedZoom = CGPoint(
x: (point.x + scrollView.contentOffset.x) * factor,
y: (point.y + scrollView.contentOffset.y) * factor
)
let width = scrollView.frame.width / scale
let height = scrollView.frame.height / scale
let destination = CGRect(x: translatedZoom.x - width / 2, y: translatedZoom.y - height / 2, width: width, height: height)
contentView.isUserInteractionEnabled = false
CATransaction.begin()
CATransaction.setCompletionBlock { [weak self] in
self?.contentView.isUserInteractionEnabled = true
}
scrollView.zoom(to: destination, animated: true)
CATransaction.commit()
}
private func contentInsetForScrollView(atScale: CGFloat) -> UIEdgeInsets {
let boundsWidth = scrollView.bounds.width
let boundsHeight = scrollView.bounds.height
let contentWidth = max(image?.size.width ?? 0, boundsWidth)
let contentHeight = max(image?.size.height ?? 0, boundsHeight)
var minContentWidth: CGFloat
var minContentHeight: CGFloat
if contentHeight > contentWidth {
if boundsHeight / boundsWidth < contentHeight / contentWidth {
minContentHeight = boundsHeight
minContentWidth = contentWidth * (minContentHeight / contentHeight)
} else {
minContentWidth = boundsWidth
minContentHeight = contentHeight * (minContentWidth / contentWidth)
}
} else {
if boundsWidth / boundsHeight < contentWidth / contentHeight {
minContentWidth = boundsWidth
minContentHeight = contentHeight * (minContentWidth / contentWidth)
} else {
minContentHeight = boundsHeight
minContentWidth = contentWidth * (minContentHeight / contentHeight)
}
}
minContentWidth *= atScale
minContentHeight *= atScale
if minContentWidth > contentView.bounds.width && minContentHeight > contentView.bounds.height {
return .zero
} else {
let verticalDiff = max(boundsHeight - minContentHeight, 0) / 2
let horizontalDiff = max(boundsWidth - minContentWidth, 0) / 2
return UIEdgeInsets(top: verticalDiff, left: horizontalDiff, bottom: verticalDiff, right: horizontalDiff)
}
}
@objc
private func singleTap() {
switch tapBehavior {
case .dismissIfZoomedOut:
if notZoomed {
dismiss()
}
case .dismissAlways:
dismiss()
case .zoomOut where notZoomed:
dismiss()
case .zoomOut:
zoom(to: .zero, scale: 1)
case .toggleOverlayVisibility:
delegate?.toggleOverlayVisibility()
}
}
private func dismiss() {
if flickedToDismiss {
delegate?.dismissAfterFlick()
} else {
delegate?.dismissAfterTap()
}
}
@objc
private func dismissPan(_ gesture: UIPanGestureRecognizer) {
if !hasPhysics {
return
}
let translation = gesture.translation(in: gesture.view)
let locationInView = gesture.location(in: gesture.view)
let velocity = gesture.velocity(in: gesture.view)
let vectorDistance = sqrt(pow(velocity.x, 2) + pow(velocity.y, 2))
if case .began = gesture.state {
isDraggingImage = imageView.frame.contains(locationInView)
if isDraggingImage {
startImageDragging(locationInView, translationOffset: .zero)
}
} else if case .changed = gesture.state {
if isDraggingImage {
var newAnchor = imageDragStartingPoint
newAnchor?.x += translation.x + imageDragOffsetFromActualTranslation.horizontal
newAnchor?.y += translation.y + imageDragOffsetFromActualTranslation.vertical
attachmentBehavior?.anchorPoint = newAnchor!
} else {
isDraggingImage = imageView.frame.contains(locationInView)
if isDraggingImage {
let translationOffset = UIOffset(horizontal: -1 * translation.x, vertical: -1 * translation.y)
startImageDragging(locationInView, translationOffset: translationOffset)
}
}
} else {
if vectorDistance > .minFlickDismissalVelocity {
if isDraggingImage {
dismissWithFlick(velocity)
} else {
dismiss()
}
} else {
cancelCurrentImageDrag(true)
}
}
}
private func dismissWithFlick(_ velocity: CGPoint) {
flickedToDismiss = true
let push = UIPushBehavior(items: [imageView], mode: .instantaneous)
push.pushDirection = CGVector(dx: velocity.x * 0.1, dy: velocity.y * 0.1)
push.setTargetOffsetFromCenter(imageDragOffsetFromImageCenter, for: imageView)
push.action = pushAction
if let attachmentBehavior = attachmentBehavior {
animator?.removeBehavior(attachmentBehavior)
}
animator?.addBehavior(push)
}
private func pushAction() {
if isImageViewOffscreen {
animator?.removeAllBehaviors()
attachmentBehavior = nil
imageView.removeFromSuperview()
dismiss()
}
}
private func cancelCurrentImageDrag(_ animated: Bool, duration: TimeInterval = 0.7) {
animator?.removeAllBehaviors()
attachmentBehavior = nil
isDraggingImage = false
if !animated {
imageView.transform = .identity
recenterImage(size: scrollView.contentSize)
} else {
UIView.animate(
withDuration: duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [.allowUserInteraction, .beginFromCurrentState],
animations: {
if self.isDraggingImage {
return
}
self.imageView.transform = .identity
if !self.scrollView.isDragging && !self.scrollView.isDecelerating {
self.recenterImage(size: self.scrollView.contentSize)
self.updateScrollViewAndImageViewForCurrentMetrics()
}
}
)
}
}
func recenterDuringRotation(size: CGSize) {
self.recenterImage(size: size)
self.updateScrollViewAndImageViewForCurrentMetrics()
}
func recenterImage(size: CGSize) {
imageView.center = CGPoint(x: size.width / 2, y: size.height / 2)
}
private func updateScrollViewAndImageViewForCurrentMetrics() {
scrollView.frame = contentView.frame
if let image = imageView.image ?? imageView.currentImage {
imageView.frame = resizedFrame(forSize: image.size)
}
scrollView.contentSize = imageView.bounds.size
scrollView.contentInset = contentInsetForScrollView(atScale: scrollView.zoomScale)
}
private func resizedFrame(forSize size: CGSize) -> CGRect {
var frame = contentView.bounds
let screenWidth = frame.width * scrollView.zoomScale
let screenHeight = frame.height * scrollView.zoomScale
var targetWidth = screenWidth
var targetHeight = screenHeight
let nativeWidth = max(size.width, screenWidth)
let nativeHeight = max(size.height, screenHeight)
if nativeHeight > nativeWidth {
if screenHeight / screenWidth < nativeHeight / nativeWidth {
targetWidth = screenHeight / (nativeHeight / nativeWidth)
} else {
targetHeight = screenWidth / (nativeWidth / nativeHeight)
}
} else {
if screenWidth / screenHeight < nativeWidth / nativeHeight {
targetHeight = screenWidth / (nativeWidth / nativeHeight)
} else {
targetWidth = screenHeight / (nativeHeight / nativeWidth)
}
}
frame.size = CGSize(width: targetWidth, height: targetHeight)
return frame.integral
}
private func startImageDragging(_ locationInView: CGPoint, translationOffset: UIOffset) {
imageDragStartingPoint = locationInView
imageDragOffsetFromActualTranslation = translationOffset
let anchor = imageDragStartingPoint
let imageCenter = imageView.center
let offset = UIOffset(horizontal: locationInView.x - imageCenter.x, vertical: locationInView.y - imageCenter.y)
imageDragOffsetFromImageCenter = offset
if hasPhysics {
attachmentBehavior = UIAttachmentBehavior(item: imageView, offsetFromCenter: offset, attachedToAnchor: anchor!)
animator!.addBehavior(attachmentBehavior!)
let modifier = UIDynamicItemBehavior(items: [imageView])
modifier.angularResistance = angularResistance(in: imageView)
modifier.density = density(in: imageView)
animator!.addBehavior(modifier)
}
}
private func angularResistance(in view: UIView) -> CGFloat {
let defaultResistance: CGFloat = 4
return appropriateValue(defaultValue: defaultResistance) * factor(forView: view)
}
private func density(in view: UIView) -> CGFloat {
let defaultDensity: CGFloat = 0.5
return appropriateValue(defaultValue: defaultDensity) * factor(forView: view)
}
private func appropriateValue(defaultValue: CGFloat) -> CGFloat {
let screenWidth = UIApplication.shared.windows.first?.bounds.width ?? UIScreen.main.bounds.width
let screenHeight = UIApplication.shared.windows.first?.bounds.height ?? UIScreen.main.bounds.height
// Default value that works well for the screenSize adjusted for the actual size of the device
return defaultValue * ((320 * 480) / (screenWidth * screenHeight))
}
private func factor(forView view: UIView) -> CGFloat {
let actualArea = contentView.bounds.height * view.bounds.height
let referenceArea = contentView.bounds.height * contentView.bounds.width
return referenceArea / actualArea
}
}
extension AgrumeCell: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
scrollView.contentInset = contentInsetForScrollView(atScale: scrollView.zoomScale)
if !scrollView.isScrollEnabled {
scrollView.isScrollEnabled = true
}
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollView.isScrollEnabled = scale > 1
scrollView.contentInset = contentInsetForScrollView(atScale: scale)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let highVelocity: CGFloat = .highScrollVelocity
let velocity = scrollView.panGestureRecognizer.velocity(in: scrollView.panGestureRecognizer.view)
if notZoomed && (abs(velocity.x) > highVelocity || abs(velocity.y) > highVelocity) {
dismiss()
}
}
}
| 33.300448 | 125 | 0.707177 |
9bacadaa7152670ce5db2e1ec579f481202fc170 | 254 | // class_43
internal class class_43{
var foo = [String]()
var bar = [String:[String]]()
internal init(){
foo.append("hello world")
bar["foo"] = foo
}
internal func helloWorld() -> String {
return bar["foo"]![0]
}
}
| 15.875 | 41 | 0.551181 |
762d4f5db5976725c19399186da7660c40433dca | 958 | //
// Easy_Game_Center_SwiftTests.swift
// Easy-Game-Center-SwiftTests
//
// Created by DaRk-_-D0G on 19/03/2558 E.B..
// Copyright (c) 2558 ère b. DaRk-_-D0G. All rights reserved.
//
import UIKit
import XCTest
class Easy_Game_Center_SwiftTests: 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.891892 | 111 | 0.625261 |
50c9450dacb4a8b635640d65476a3dac9a63fe7a | 9,999 | //
// UserAccessControlViewController.swift
// MyMapKit
//
// Created by Vũ Quý Đạt on 17/12/2020.
//
import UIKit
class UserAccessControlViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var csTopContainerView: NSLayoutConstraint!
@IBOutlet weak var csTopSigninView: NSLayoutConstraint!
@IBOutlet weak var welcomeScrollView: UIScrollView!
@IBOutlet weak var contentStackView: UIStackView!
@IBOutlet weak var signinView: UIView!
@IBOutlet weak var layerUsernameTextField: UIView!
@IBOutlet weak var usernameTextFieldContainer: UIView!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var layerPasswordTextField: UIView!
@IBOutlet weak var passwordTextFieldContainer: UIView!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var animationLoadingView: NVActivityIndicatorView!
// @IBOutlet weak var testanimation: NVActivityIndicatorView!
var keyboardHeight: CGFloat = 0.0
var isChangePageByPageControl = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
usernameTextField.delegate = self
passwordTextField.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
pageControl.addTarget(self, action: #selector(touchDragOutsidePageControl), for: UIControl.Event.touchDragOutside)
pageControl.addTarget(self, action: #selector(touchUpInsidePageControl), for: UIControl.Event.touchUpInside)
pageControl.addTarget(self, action: #selector(touchUpOutsidePageControl), for: UIControl.Event.touchUpOutside)
// set up UI
animationLoadingView.type = .cubeTransition
pageControl.numberOfPages = Int(contentStackView.frame.size.width / self.view.frame.size.width)
pageControl.currentPage = 0
layerUsernameTextField.border()
layerUsernameTextField.dropShadow()
usernameTextFieldContainer.border()
usernameTextFieldContainer.dropShadow()
layerPasswordTextField.border()
layerPasswordTextField.dropShadow()
passwordTextFieldContainer.border()
passwordTextFieldContainer.dropShadow()
}
// MARK: - Common methods
func edditingUserName() {
UIView.animate(withDuration: 0.3,
delay: 0.1,
options: [.curveEaseIn],
animations: { [weak self] in
self!.csTopContainerView.constant = self!.view.frame.height / 2
self?.view.layoutIfNeeded()
}, completion: nil)
}
func endEdditingUserName() {
}
func edditingPassword() {
}
func endEdditingPassword() {
}
func startLoading(_ handler: @escaping () -> Void) {
startLoadingAnimation()
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
handler()
self.stopLoadingAnimation()
}
}
func startLoadingAnimation () {
UIView.animate(withDuration: 0.3,
delay: 0.1,
options: [.curveEaseIn],
animations: { [weak self] in
self!.view.endEditing(true)
self!.loadingView.isHidden = false
self!.view.bringSubviewToFront(self!.loadingView)
self!.loadingView.alpha = 1
self!.animationLoadingView.startAnimating()
}, completion: nil)
}
func stopLoadingAnimation () {
UIView.animate(withDuration: 1,
delay: 0.5,
options: [.curveEaseIn],
animations: { [weak self] in
self!.loadingView.alpha = 0
}, completion: {_ in
self.loadingView.isHidden = true
self.view.sendSubviewToBack(self.loadingView)
self.animationLoadingView.stopAnimating()
})
}
// MARK: IBAction
@IBAction func pageControlChange(_ sender: UIPageControl) {
welcomeScrollView.setContentOffset(CGPoint(x: welcomeScrollView.frame.size.width * CGFloat(sender.currentPage), y: welcomeScrollView.frame.origin.y), animated: true)
isChangePageByPageControl = true
}
@IBAction func loginButtonTap(_ sender: UIButton) {
guard let username = usernameTextField.text, !username.isEmpty else {
ErrorPresenter.showError(message: "Please enter your username", on: self)
return
}
guard let password = passwordTextField.text, !password.isEmpty else {
ErrorPresenter.showError(message: "Please enter your password", on: self)
return
}
Auth().login(username: username, password: password) { result in
switch result {
case .success:
DispatchQueue.main.async { [self] in
startLoading {
// let appDelegate = UIApplication.shared.delegate as? SceneDelegate
// appDelegate?.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
// self.addChild(UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!)
// using with storyboard reference
// startLoading {
// self.performSegue(withIdentifier: "didLogin", sender: nil)
// }
let vc = UIStoryboard(name: "Messager", bundle: nil).instantiateInitialViewController()!
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated:true, completion:nil)
}
}
case .failure:
let message = "Could not login. Check your credentials and try again"
ErrorPresenter.showError(message: message, on: self)
}
}
// DidRequestServer.successful(on:self)
// startLoading {
// self.performSegue(withIdentifier: "didLogin", sender: nil)
// }
}
@IBAction func hideKeyBoardTap(_ sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
@IBAction func pageControlTapped(_ sender: UIPageControl) {
}
@IBAction func typingUsername(_ sender: UITextField) {
}
@IBAction func endTypingUsername(_ sender: UITextField) {
}
@IBAction func typingPassword(_ sender: Any) {
}
@IBAction func endTypingPassword(_ sender: UITextField) {
}
@IBAction func customIpAction(_ sender: UIButton) {
ip = usernameTextField.text!
if passwordTextField.text == "true" {
demo = true
} else {
demo = false
}
}
// MARK: Observer methods
@objc func touchDragOutsidePageControl() {
isChangePageByPageControl = false
}
@objc func touchUpInsidePageControl() {
isChangePageByPageControl = false
}
@objc func touchUpOutsidePageControl() {
isChangePageByPageControl = false
}
// MARK: - Delegate methods
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !isChangePageByPageControl {
pageControl.currentPage = Int(scrollView.contentOffset.x / self.view.frame.size.width)
}
}
/*
// 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.
}
*/
}
//MARK: Keyboard.
extension UserAccessControlViewController: UITextFieldDelegate {
@objc func keyboardWillShow(_ notification: NSNotification) {
if let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
keyboardHeight = keyboardRect.height
UIView.animate(withDuration: 0.3,
delay: 0.1,
options: [.curveEaseIn],
animations: { [weak self] in
let a = (self!.view.frame.height - self!.keyboardHeight) / 2
let b = self!.welcomeScrollView.frame.size.height + self!.signinView.frame.origin.x + self!.signinView.frame.size.height / 2
self!.csTopContainerView.constant = a - b
self?.view.layoutIfNeeded()
}, completion: nil)
}
}
@objc func keyboardWillHide(notification: NSNotification) {
csTopContainerView.constant = 0
view.layoutIfNeeded()
// if let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
// UIView.animate(withDuration: 0.3,
// delay: 0.1,
// options: [.curveEaseIn],
// animations: { [weak self] in
// }, completion: nil)
}
}
| 38.906615 | 173 | 0.592759 |
642fc902e73bff0b64955747d47c4ccc70b8262d | 733 | // Created by eric_horacek on 1/21/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import Epoxy
import UIKit
/// Source code for `EpoxyBars` "Bottom Button" example from `README.md`:
class BottomButtonViewController: UIViewController {
// MARK: Internal
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
bottomBarInstaller.install()
}
// MARK: Private
private lazy var bottomBarInstaller = BottomBarInstaller(
viewController: self,
bars: bars)
@BarModelBuilder private var bars: [BarModeling] {
ButtonRow.barModel(
content: .init(text: "Click me!"),
behaviors: .init(didTap: {
// Handle button selection
}))
}
}
| 22.90625 | 73 | 0.690314 |
ebddc36b93ec3f94c8351aedaead9581c1186ec9 | 1,335 | //
// XKCDStrip+FromJSONDictionary.swift
// EasyDi
//
// Created by Andrey Zarembo
//
import Foundation
extension Dictionary where Key: TextOutputStream, Value: Any {
var xkcdStrip: XKCDStrip? {
guard let jsonDictionary = self as? [String: Any] else {
return nil
}
guard
let stripId = jsonDictionary["num"] as? Int,
let title = jsonDictionary["title"] as? String,
let imgURLString = jsonDictionary["img"] as? String, let imgURL = URL(string: imgURLString),
let notes = jsonDictionary["alt"] as? String,
let yearString = jsonDictionary["year"] as? String, let year = Int(yearString),
let monthString = jsonDictionary["month"] as? String, let month = Int(monthString),
let dayString = jsonDictionary["day"] as? String, let day = Int(dayString)
else {
return nil
}
let calendar = Calendar(identifier: .gregorian)
let components = DateComponents(calendar: calendar, year: year, month: month, day: day)
guard let date = components.date else {
return nil
}
return XKCDStrip(id: stripId, date: date, title: title, notes: notes, imgURL: imgURL)
}
}
| 31.785714 | 104 | 0.577528 |
79cca6844e2565944b961da0cf1adcccb9965b4b | 2,174 | //
// AppDelegate.swift
// XMPPClient
//
// Created by Ali Gangji on 06/18/2016.
// Copyright (c) 2016 Ali Gangji. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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.255319 | 285 | 0.75391 |
1ca4d01ee8ad2119aabe5278ade89838ff39d2b2 | 176 | //
// DBUtils.swift
// ListaItens
//
// Created by Cristiano Diniz Pinto on 07/06/17.
// Copyright © 2017 Cristiano Diniz Pinto. All rights reserved.
//
import Foundation
| 17.6 | 64 | 0.698864 |
d6d6bac5a41a824472afe9f038ede934dd2b96f9 | 1,587 | //
// ViewController+Problem18.swift
// BinaryTree
//
// Created by Manish Rathi on 13/03/2022.
//
import Foundation
/*
530. Minimum Absolute Difference in BST
https://leetcode.com/problems/minimum-absolute-difference-in-bst/
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
*/
extension ViewController {
func solve18() {
print("Setting up Problem18 input!")
let root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.left?.left = TreeNode(1)
root.left?.right = TreeNode(3)
let output = Solution().getMinimumDifference(root)
print("Output: \(output)")
}
}
fileprivate class Solution {
private var minimumDifference = Int.max
private var previousNode: TreeNode? = nil
func getMinimumDifference(_ root: TreeNode?) -> Int {
findMinimumDifference(root)
return minimumDifference
}
private func findMinimumDifference(_ currentNode: TreeNode?) {
guard let currentNode = currentNode else { return }
findMinimumDifference(currentNode.left)
if previousNode != nil {
let currentDifference = abs(previousNode!.val - currentNode.val)
minimumDifference = min(minimumDifference, currentDifference)
}
previousNode = currentNode
findMinimumDifference(currentNode.right)
}
}
| 25.596774 | 144 | 0.666667 |
e60406261d5ebf38e621f2cbbd4ee394cbb86439 | 450 | import XCTest
@testable import YAMLSerialization
import yaml
final class YAMLSerializationTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
//XCTAssertEqual(YAMLSerialization().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 26.470588 | 87 | 0.671111 |
e0ada71f134c94ecee5d881bf15d985c0b3d7a7a | 449 | // 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 --crash %target-swift-frontend %s -parse
// REQUIRES: asserts
var d:Collection{for c d in
| 40.818182 | 78 | 0.74833 |
16a6951f3c716ce45e6d670ede9864dbd25bcdf9 | 3,254 | //
// TransactionTests.swift
// web3swift
//
// Created by Miguel on 11/07/2018.
// Copyright © 2018 Argent Labs Limited. All rights reserved.
//
import XCTest
import BigInt
@testable import web3
class TransactionTests: XCTestCase {
let withoutChainID: EthereumTransaction = EthereumTransaction(from: EthereumAddress("0x2639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7173"),
to: EthereumAddress("0x1639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7174"),
value: 0,
data: Data(),
nonce: 1,
gasPrice: 10,
gasLimit: 400000,
chainId: nil)
func test_GivenLocalTransaction_WhenTransactionOnlyWithToAndData_HashIsNil() {
let transaction = EthereumTransaction(to: EthereumAddress("0x2639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7173"),
data: Data())
XCTAssertNil(transaction.hash)
}
func test_GivenLocalTransaction_WhenTransactionDoesNotHaveNonce_HashIsNil() {
let transaction = EthereumTransaction(from: EthereumAddress("0x2639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7173"),
to: EthereumAddress("0x1639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7174"),
data: Data(),
gasPrice: 10,
gasLimit: 400000)
XCTAssertNil(transaction.hash)
}
func test_GivenLocalTransaction_WhenTransactionWithNonce_HashIsCorrect() {
let transaction = EthereumTransaction(from: EthereumAddress("0x2639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7173"),
to: EthereumAddress("0x1639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde7174"),
value: 0,
data: Data(),
nonce: 1,
gasPrice: 10,
gasLimit: 400000,
chainId: 3)
XCTAssertEqual(transaction.hash?.web3.hexString, "0xec010a83061a80a01639f727ded571d584643895d43d02a7a190f8249748a2c32200cfc12dde71748080038080")
}
func test_GivenLocalTransaction_WhenTransactionWithoutChainID_HashIsNil() {
XCTAssertNil(withoutChainID.hash)
}
func test_GivenTransactionWithoutChainID_WhenChainIDIsSet_HashIsCorrect() {
var withChainId = withoutChainID
withChainId.chainId = 3
XCTAssertEqual(withChainId.hash?.web3.hexString, "0x91f25d392d2b9cb70acdd14bcaa08b596b16661e26fbf2fa8a05f68edf19fcea")
}
}
| 52.483871 | 158 | 0.549785 |
dbbbeb78079bbbe308ba055c5c814b16b1bb733e | 2,209 | import Cocoa
public class TooltipController: NSWindowController {
private let backgroundColor = NSColor(calibratedHue: 0.16, saturation: 0.22, brightness: 0.97, alpha: 1.0)
private var messageTextField: NSTextField
private var tooltip: String = "" {
didSet {
messageTextField.stringValue = tooltip
adjustSize()
}
}
public init() {
let contentRect = NSRect(x: 128.0, y: 128.0, width: 300.0, height: 20.0)
let styleMask: NSWindow.StyleMask = [.borderless, .nonactivatingPanel]
let panel = NSPanel(contentRect: contentRect, styleMask: styleMask, backing: .buffered, defer: false)
panel.level = NSWindow.Level(Int(kCGPopUpMenuWindowLevel) + 1)
panel.hasShadow = true
messageTextField = NSTextField()
messageTextField.isEditable = false
messageTextField.isSelectable = false
messageTextField.isBezeled = false
messageTextField.textColor = .black
messageTextField.drawsBackground = true
messageTextField.backgroundColor = backgroundColor
messageTextField.font = .systemFont(ofSize: NSFont.systemFontSize(for: .small))
panel.contentView?.addSubview(messageTextField)
super.init(window: panel)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc(showTooltip:atPoint:)
public func show(tooltip: String, at point: NSPoint) {
self.tooltip = tooltip
window?.orderFront(nil)
set(windowLocation: point)
}
@objc
public func hide() {
window?.orderOut(nil)
}
private func set(windowLocation location: NSPoint) {
var newPoint = location
if location.y > 5 {
newPoint.y -= 5
}
window?.setFrameTopLeftPoint(newPoint)
}
private func adjustSize() {
let attrString = messageTextField.attributedStringValue;
var rect = attrString.boundingRect(with: NSSize(width: 1600.0, height: 1600.0), options: .usesLineFragmentOrigin)
rect.size.width += 10
messageTextField.frame = rect
window?.setFrame(rect, display: true)
}
}
| 33.469697 | 121 | 0.653237 |
222eb4b6f10d47bc00c14b2bd3929259585ee76d | 4,585 | //
// MainViewControllerTest.swift
// CANNavApp
//
// Created by Tri Vo on 7/17/16.
// Copyright © 2016 acumenvn. All rights reserved.
//
import XCTest
import Nimble
import GoogleMaps
import CoreLocation
class MainViewControllerTest: XCTestCase {
var mVC : MainViewController?
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
self.mVC = MainViewController(nibName: "MainViewController", bundle: nil)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
self.mVC = nil
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
func testInit() {
expect(self.mVC).notTo(equal(nil))
self.mVC?.loadView()
// mLocationManager
if CLLocationManager.locationServicesEnabled() == true {
expect(self.mVC?.mLocationManager).notTo(equal(nil))
expect(self.mVC?.mLocationManager?.desiredAccuracy == kCLLocationAccuracyKilometer).to(equal(true))
expect(self.mVC?.mLocationManager?.delegate != nil).to(equal(true))
}
// mCurrentUserLocation
expect(self.mVC?.mCurrentUserLocation).notTo(equal(nil))
// bDidGetUserLocationFirstTime
expect(self.mVC?.bDidGetUserLocationFirstTime).to(equal(false))
// mMarkerFrom
expect(self.mVC?.mMarkerFrom).to(equal(nil))
// mMarkerTo
expect(self.mVC?.mMarkerTo).to(equal(nil))
// mMarkerUserLocation
expect(self.mVC?.mMarkerUserLocation).to(equal(nil))
// mLocationFrom
expect(self.mVC?.mLocationFrom).to(equal(nil))
// mLocationTo
expect(self.mVC?.mLocationTo).to(equal(nil))
// mSearchViewControllerFrom
expect(self.mVC?.mSearchViewControllerFrom).to(equal(nil))
// mSearchViewControllerTo
expect(self.mVC?.mSearchViewControllerTo).to(equal(nil))
// mCurrentMovingMode
expect(self.mVC?.mCurrentMovingMode.rawValue).to(equal("driving"))
// mCurrentDirection
expect(self.mVC?.mCurrentDirection == nil).to(equal(true))
// mDirectionDictionary
expect(self.mVC?.mDirectionDictionary).to(equal(nil))
// mCurrentPolyline
expect(self.mVC?.mCurrentPolyline == nil).to(equal(true))
// mSelectedColor
expect(self.mVC?.mSelectedColor).notTo(equal(nil))
// mMapView
expect(self.mVC?.mMapView).notTo(equal(nil))
// mViewFrom
expect(self.mVC?.mViewFrom).notTo(equal(nil))
// mViewTo
expect(self.mVC?.mViewTo).notTo(equal(nil))
// mTxtFrom
expect(self.mVC?.mTxtFrom).notTo(equal(nil))
// mTxtTo
expect(self.mVC?.mTxtTo).notTo(equal(nil))
// mViewCurrentLocation
expect(self.mVC?.mViewCurrentLocation).notTo(equal(nil))
// mViewMovingModeCar
expect(self.mVC?.mViewMovingModeCar).notTo(equal(nil))
// mViewMovingModeWalking
expect(self.mVC?.mViewMovingModeWalking).notTo(equal(nil))
// mLblDistance
expect(self.mVC?.mLblDistance).notTo(equal(nil))
// mLblDuration
expect(self.mVC?.mLblDuration).notTo(equal(nil))
// mViewDistanceAndDuration
expect(self.mVC?.mViewDistanceAndDuration).notTo(equal(nil))
// mViewVehicleBottomConstraint
expect(self.mVC?.mViewVehicleBottomConstraint).notTo(equal(nil))
}
func testConformingToSearchViewControllerDeleagate() {
expect(self.mVC).notTo(equal(nil))
expect(self.mVC?.conformsToProtocol(SearchViewControllerDelegate)).to(equal(true))
}
func testConformingToLocationManagerDelegate() {
expect(self.mVC).notTo(equal(nil))
expect(self.mVC?.conformsToProtocol(CLLocationManagerDelegate)).to(equal(true))
}
}
| 31.62069 | 111 | 0.61374 |
4ae7bab6224c2460acf97a9152d813e04b5a29f0 | 685 | //
// MockURLSession.swift
// MagiSkyTests
//
// Created by 安然 on 2018/7/6.
// Copyright © 2018年 anran. All rights reserved.
//
import Foundation
@testable import MagiSky
class MockURLSession: URLSessionProtocol {
var sessionDataTask = MockURLSessionDataTask()
var responseData: Data?
var responseHeader: HTTPURLResponse?
var responseError: Error?
/// 测试的时候将异步改为同步
func dataTask(
with request: URLRequest,
completionHandler: @escaping URLSessionProtocol.DataTaskHandler)
-> URLSessionDataTaskProtocol {
completionHandler(responseData, responseHeader, responseError)
return sessionDataTask
}
}
| 24.464286 | 74 | 0.69781 |
e53d5019632936620bd495c63e60eeeafc0bfc61 | 4,183 | //
// ReceiveCardInteractorMock.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 10/7/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import RxSwift
import WavesSDKCrypto
final class ReceiveCardInteractor: ReceiveCardInteractorProtocol {
private let auth = FactoryInteractors.instance.authorization
private let coinomatRepository = FactoryRepositories.instance.coinomatRepository
private let accountBalance = FactoryInteractors.instance.accountBalance
func getInfo(fiatType: ReceiveCard.DTO.FiatType) -> Observable<ResponseType<ReceiveCard.DTO.Info>> {
let amount = getAmountInfo(fiat: fiatType)
return Observable.zip(getWavesBalance(), amount, getMyAddress())
.flatMap({ (assetBalance, amountInfo, address) -> Observable<ResponseType<ReceiveCard.DTO.Info>> in
let info = ReceiveCard.DTO.Info(asset: assetBalance, amountInfo: amountInfo, address: address)
return Observable.just(ResponseType(output: info, error: nil))
})
.catchError({ (error) -> Observable<ResponseType<ReceiveCard.DTO.Info>> in
if let networkError = error as? NetworkError {
return Observable.just(ResponseType(output: nil, error: networkError))
}
return Observable.just(ResponseType(output: nil, error: NetworkError.error(by: error)))
})
}
func getWavesAmount(fiatAmount: Money, fiatType: ReceiveCard.DTO.FiatType) -> Observable<ResponseType<Money>> {
let authAccount = FactoryInteractors.instance.authorization
return authAccount
.authorizedWallet()
.flatMap({ [weak self] (wallet) -> Observable<ResponseType<Money>> in
guard let self = self else { return Observable.empty() }
return self.coinomatRepository.getPrice(address: wallet.address, amount: fiatAmount, type: fiatType.id)
.map({ (money) -> ResponseType<Money> in
return ResponseType(output: money, error: nil)
})
.catchError({ (error) -> Observable<ResponseType<Money>> in
if let error = error as? NetworkError {
return Observable.just(ResponseType(output: nil, error: error))
}
return Observable.just(ResponseType(output: nil, error: NetworkError.error(by: error)))
})
})
}
}
private extension ReceiveCardInteractor {
func getWavesBalance() -> Observable<DomainLayer.DTO.SmartAssetBalance> {
//TODO: need optimize
return accountBalance.balances().flatMap({ balances -> Observable<DomainLayer.DTO.SmartAssetBalance> in
guard let wavesAsset = balances.first(where: {$0.asset.wavesId == WavesSDKCryptoConstants.wavesAssetId}) else {
return Observable.empty()
}
return Observable.just(wavesAsset)
})
}
func getMyAddress() -> Observable<String> {
return auth.authorizedWallet().flatMap { signedWallet -> Observable<String> in
return Observable.just(signedWallet.address)
}
}
func getAmountInfo(fiat: ReceiveCard.DTO.FiatType) -> Observable<ReceiveCard.DTO.AmountInfo> {
return auth.authorizedWallet().flatMap({ [weak self] (wallet) -> Observable<ReceiveCard.DTO.AmountInfo> in
guard let self = self else { return Observable.empty() }
return self.coinomatRepository.cardLimits(address: wallet.address, fiat: fiat.id)
.flatMap({ (limit) -> Observable<ReceiveCard.DTO.AmountInfo> in
let amountInfo = ReceiveCard.DTO.AmountInfo(type: fiat,
minAmount: limit.min,
maxAmount: limit.max)
return Observable.just(amountInfo)
})
})
}
}
| 44.031579 | 123 | 0.600765 |
ff72c28d6dd56496b497b5e1e25ef91f4d250983 | 4,187 | /**
* Copyright IBM Corporation 2018
*
* 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
/** A classifier for natural language phrases. */
public struct Classifier {
/// The state of the classifier.
public enum Status: String {
case nonExistent = "Non Existent"
case training = "Training"
case failed = "Failed"
case available = "Available"
case unavailable = "Unavailable"
}
/// User-supplied name for the classifier.
public var name: String?
/// Link to the classifier.
public var url: String
/// The state of the classifier.
public var status: String?
/// Unique identifier for this classifier.
public var classifierID: String
/// Date and time (UTC) the classifier was created.
public var created: String?
/// Additional detail about the status.
public var statusDescription: String?
/// The language used for the classifier.
public var language: String?
/**
Initialize a `Classifier` with member variables.
- parameter url: Link to the classifier.
- parameter classifierID: Unique identifier for this classifier.
- parameter name: User-supplied name for the classifier.
- parameter status: The state of the classifier.
- parameter created: Date and time (UTC) the classifier was created.
- parameter statusDescription: Additional detail about the status.
- parameter language: The language used for the classifier.
- returns: An initialized `Classifier`.
*/
public init(url: String, classifierID: String, name: String? = nil, status: String? = nil, created: String? = nil, statusDescription: String? = nil, language: String? = nil) {
self.url = url
self.classifierID = classifierID
self.name = name
self.status = status
self.created = created
self.statusDescription = statusDescription
self.language = language
}
}
extension Classifier: Codable {
private enum CodingKeys: String, CodingKey {
case name = "name"
case url = "url"
case status = "status"
case classifierID = "classifier_id"
case created = "created"
case statusDescription = "status_description"
case language = "language"
static let allValues = [name, url, status, classifierID, created, statusDescription, language]
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name)
url = try container.decode(String.self, forKey: .url)
status = try container.decodeIfPresent(String.self, forKey: .status)
classifierID = try container.decode(String.self, forKey: .classifierID)
created = try container.decodeIfPresent(String.self, forKey: .created)
statusDescription = try container.decodeIfPresent(String.self, forKey: .statusDescription)
language = try container.decodeIfPresent(String.self, forKey: .language)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(name, forKey: .name)
try container.encode(url, forKey: .url)
try container.encodeIfPresent(status, forKey: .status)
try container.encode(classifierID, forKey: .classifierID)
try container.encodeIfPresent(created, forKey: .created)
try container.encodeIfPresent(statusDescription, forKey: .statusDescription)
try container.encodeIfPresent(language, forKey: .language)
}
}
| 37.383929 | 179 | 0.687366 |
e46a18286be7cb7f0d7690cc9285803cd6150463 | 218 | //
// Images.swift
// WhatsAppLikeImageGrouping
//
// Created by Jigar on 26/04/19.
// Copyright © 2019 Jigar. All rights reserved.
//
import Foundation
struct listOfImages {
var imageNameList : [String]
}
| 13.625 | 48 | 0.683486 |
ac5217063ab10865db214e233ccdf76fc70ea9f5 | 1,311 | //
// Copyright (C) 2005-2020 Alfresco Software Limited.
//
// This file is part of the Alfresco Content Mobile iOS App.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import AlfrescoCore
struct GetContentServicesProfile: APIRequest {
typealias Response = StatusCodeResponse
let authenticationProvider: BasicAuthenticationProvider
var path: String {
return APIConstants.Path.getProfile
}
var method: HttpMethod {
return .get
}
var headers: [String: String] {
return authenticationProvider.authorizationHeader()
}
var parameters: [String: String] {
return [:]
}
init(with authenticationProvider: BasicAuthenticationProvider) {
self.authenticationProvider = authenticationProvider
}
}
| 29.133333 | 76 | 0.719298 |
7a12426720f2d6f1e92484776a4c8904e9b56752 | 4,305 | //
// PlatformExtensions.swift
// DominantColor
//
// Created by Indragie on 12/25/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
#if os(OSX)
import Cocoa
public extension NSImage {
/**
Computes the dominant colors in the receiver
- parameter maxSampledPixels: Maximum number of pixels to sample in the image. If
the total number of pixels in the image exceeds this
value, it will be downsampled to meet the constraint.
- parameter accuracy: Level of accuracy to use when grouping similar colors.
Higher accuracy will come with a performance tradeoff.
- parameter seed: Seed to use when choosing the initial points for grouping
of similar colors. The same seed is guaranteed to return
the same colors every time.
- parameter memoizeConversions: Whether to memoize conversions from RGB to the LAB color
space (used for grouping similar colors). Memoization
will only yield better performance for large values of
`maxSampledPixels` in images that are primarily comprised
of flat colors. If this information about the image is
not known beforehand, it is best to not memoize.
- returns: A list of dominant colors in the image sorted from most dominant to
least dominant.
*/
public func dominantColors(
maxSampledPixels: Int = DefaultParameterValues.maxSampledPixels,
accuracy: GroupingAccuracy = DefaultParameterValues.accuracy,
seed: UInt64 = DefaultParameterValues.seed,
memoizeConversions: Bool = DefaultParameterValues.memoizeConversions
) -> [NSColor] {
let image = cgImage(forProposedRect: nil, context: nil, hints: nil)!
let colors = dominantColorsInImage(image, maxSampledPixels: maxSampledPixels, accuracy: accuracy, seed: seed, memoizeConversions: memoizeConversions)
return colors.map { NSColor(cgColor: $0)! }
}
}
#elseif os(iOS)
import UIKit
public extension UIImage {
/**
Computes the dominant colors in the receiver
- parameter maxSampledPixels: Maximum number of pixels to sample in the image. If
the total number of pixels in the image exceeds this
value, it will be downsampled to meet the constraint.
- parameter accuracy: Level of accuracy to use when grouping similar colors.
Higher accuracy will come with a performance tradeoff.
- parameter seed: Seed to use when choosing the initial points for grouping
of similar colors. The same seed is guaranteed to return
the same colors every time.
- parameter memoizeConversions: Whether to memoize conversions from RGB to the LAB color
space (used for grouping similar colors). Memoization
will only yield better performance for large values of
`maxSampledPixels` in images that are primarily comprised
of flat colors. If this information about the image is
not known beforehand, it is best to not memoize.
- returns: A list of dominant colors in the image sorted from most dominant to
least dominant.
*/
public func dominantColors(
_ maxSampledPixels: Int = DefaultParameterValues.maxSampledPixels,
accuracy: GroupingAccuracy = DefaultParameterValues.accuracy,
seed: UInt64 = DefaultParameterValues.seed,
memoizeConversions: Bool = DefaultParameterValues.memoizeConversions
) -> [UIColor] {
if let CGImage = self.cgImage {
let colors = dominantColorsInImage(CGImage, maxSampledPixels: maxSampledPixels, accuracy: accuracy, seed: seed, memoizeConversions: memoizeConversions)
return colors.map { UIColor(cgColor: $0) }
} else {
return []
}
}
}
#endif
| 48.920455 | 163 | 0.62137 |
1a5b3adbfe77ae1248674942c3b3bc5c408d796e | 10,594 | //
// HOTPMechanismTests.swift
// FRAuthenticatorTests
//
// Copyright (c) 2020 ForgeRock. All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
import XCTest
class HOTPMechanismTests: FRABaseTests {
func test_01_hotpmechanism_init_success() {
let qrCode = URL(string: "otpauth://hotp/ForgeRock:demo?secret=IJQWIZ3FOIQUEYLE&issuer=ForgeRock&counter=0&algorithm=SHA256")!
do {
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
XCTAssertNotNil(mechanism.mechanismUUID)
XCTAssertNotNil(mechanism.issuer)
XCTAssertNotNil(mechanism.type)
XCTAssertNotNil(mechanism.version)
XCTAssertNotNil(mechanism.accountName)
XCTAssertNotNil(mechanism.secret)
XCTAssertNotNil(mechanism.algorithm)
XCTAssertNotNil(mechanism.timeAdded)
XCTAssertEqual(mechanism.issuer, "ForgeRock")
XCTAssertEqual(mechanism.type, "hotp")
XCTAssertEqual(mechanism.accountName, "demo")
XCTAssertEqual(mechanism.secret, "IJQWIZ3FOIQUEYLE")
XCTAssertEqual(mechanism.algorithm.rawValue, "sha256")
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
func test_02_archive_obj() {
let qrCode = URL(string: "otpauth://hotp/Forgerock:demo?secret=IJQWIZ3FOIQUEYLE&issuer=Forgerock&counter=0&algorithm=SHA256")!
do {
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
if #available(iOS 11.0, *) {
if let mechanismData = try? NSKeyedArchiver.archivedData(withRootObject: mechanism, requiringSecureCoding: true) {
let mechanismFromData = NSKeyedUnarchiver.unarchiveObject(with: mechanismData) as? HOTPMechanism
XCTAssertNotNil(mechanismFromData)
XCTAssertEqual(mechanism.mechanismUUID, mechanismFromData?.mechanismUUID)
XCTAssertEqual(mechanism.issuer, mechanismFromData?.issuer)
XCTAssertEqual(mechanism.type, mechanismFromData?.type)
XCTAssertEqual(mechanism.secret, mechanismFromData?.secret)
XCTAssertEqual(mechanism.version, mechanismFromData?.version)
XCTAssertEqual(mechanism.accountName, mechanismFromData?.accountName)
XCTAssertEqual(mechanism.algorithm, mechanismFromData?.algorithm)
XCTAssertEqual(mechanism.digits, mechanismFromData?.digits)
XCTAssertEqual(mechanism.counter, mechanismFromData?.counter)
XCTAssertEqual(mechanism.timeAdded.timeIntervalSince1970, mechanismFromData?.timeAdded.timeIntervalSince1970)
}
else {
XCTFail("Failed to serialize HOTPMechnaism object with Secure Coding")
}
} else {
let mechanismData = NSKeyedArchiver.archivedData(withRootObject: mechanism)
let mechanismFromData = NSKeyedUnarchiver.unarchiveObject(with: mechanismData) as? HOTPMechanism
XCTAssertNotNil(mechanismFromData)
XCTAssertEqual(mechanism.mechanismUUID, mechanismFromData?.mechanismUUID)
XCTAssertEqual(mechanism.issuer, mechanismFromData?.issuer)
XCTAssertEqual(mechanism.type, mechanismFromData?.type)
XCTAssertEqual(mechanism.secret, mechanismFromData?.secret)
XCTAssertEqual(mechanism.version, mechanismFromData?.version)
XCTAssertEqual(mechanism.accountName, mechanismFromData?.accountName)
XCTAssertEqual(mechanism.algorithm, mechanismFromData?.algorithm)
XCTAssertEqual(mechanism.digits, mechanismFromData?.digits)
XCTAssertEqual(mechanism.counter, mechanismFromData?.counter)
XCTAssertEqual(mechanism.timeAdded.timeIntervalSince1970, mechanismFromData?.timeAdded.timeIntervalSince1970)
}
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
func test_03_hotp_mechanism_identifier() {
let qrCode = URL(string: "otpauth://hotp/Forgerock:demo?secret=IJQWIZ3FOIQUEYLE&issuer=Forgerock&counter=0&algorithm=SHA256")!
do {
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
XCTAssertNotNil(mechanism)
XCTAssertEqual(mechanism.identifier, "Forgerock-demo-hotp")
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
func test_04_hotp_mechanism_counter() {
let qrCode = URL(string: "otpauth://hotp/Forgerock:demo?secret=IJQWIZ3FOIQUEYLE&issuer=Forgerock&counter=4&algorithm=SHA256")!
do {
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
XCTAssertNotNil(mechanism)
XCTAssertEqual(mechanism.counter, 4)
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
func test_05_hotp_mechanism_default_counter() {
let qrCode = URL(string: "otpauth://hotp/Forgerock:demo?secret=IJQWIZ3FOIQUEYLE&issuer=Forgerock")!
do {
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
XCTAssertNotNil(mechanism)
XCTAssertEqual(mechanism.counter, 0)
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
func test_06_hotp_mechanism_invalid_secret() {
let qrCode = URL(string: "otpauth://hotp/Forgerock:demo?secret=invalidSecret&issuer=Forgerock&counter=4&algorithm=SHA256")!
do {
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
XCTAssertNotNil(mechanism)
XCTAssertEqual(mechanism.counter, 4)
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
func test_07_hotp_mechanism_generate_code_in_sequence() {
let qrCode = URL(string: "otpauth://hotp/Forgerock:demo?secret=IJQWIZ3FOIQUEYLE&issuer=Forgerock&counter=0&algorithm=SHA256")!
do {
// Init SDK
FRAClient.start()
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
XCTAssertNotNil(mechanism)
let expected: [String] = ["185731", "773759", "684879", "952500", "430844", "344487", "866561"]
for index in 0...6 {
let code = try mechanism.generateCode()
XCTAssertEqual(code.code, expected[index])
let thisMechanism = FRAClient.storage.getMechanismForUUID(uuid: mechanism.mechanismUUID) as? HOTPMechanism
XCTAssertEqual(thisMechanism?.counter, index + 1)
}
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
func test_08_hotp_mechanism_generate_code_in_sequence_and_failure() {
let qrCode = URL(string: "otpauth://hotp/Forgerock:demo?secret=IJQWIZ3FOIQUEYLE&issuer=Forgerock&counter=0&algorithm=SHA256")!
var tmpMechanism: HOTPMechanism?
do {
// Init SDK
let storageClient = DummyStorageClient()
FRAClient.storage = storageClient
FRAClient.start()
let parser = try OathQRCodeParser(url: qrCode)
let mechanism = HOTPMechanism(issuer: parser.issuer, accountName: parser.label, secret: parser.secret, algorithm: parser.algorithm, counter: parser.counter, digits: parser.digits)
XCTAssertNotNil(mechanism)
tmpMechanism = mechanism
let expected: [String] = ["185731", "773759", "684879", "952500", "952500", "430844", "344487", "866561"]
for index in 0...7 {
if index == 3 {
storageClient.setMechanismResult = false
let _ = try mechanism.generateCode()
}
else {
let code = try mechanism.generateCode()
XCTAssertEqual(code.code, expected[index])
let thisMechanism = FRAClient.storage.getMechanismForUUID(uuid: mechanism.mechanismUUID) as? HOTPMechanism
XCTAssertEqual(thisMechanism?.counter, index + 1)
}
}
}
catch MechanismError.failedToUpdateInformation {
if let thisMechanism = tmpMechanism {
XCTAssertEqual(thisMechanism.counter, 3)
}
if let storageClient = FRAClient.storage as? DummyStorageClient {
storageClient.setMechanismResult = nil
}
}
catch {
XCTFail("Failed with unexpected error: \(error.localizedDescription)")
}
}
}
| 47.294643 | 192 | 0.632433 |
8f77ac50bb9388766f618f15006760bf5c634f4a | 1,540 | //
// ViewController3.swift
// Animations
//
// Created by Alessandro Marzoli on 26/04/19.
// Copyright © 2019 Alessandro Marzoli. All rights reserved.
//
import UIKit
class ViewController3: UIViewController {
private let secondLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let frame = view.frame
let path = UIBezierPath()
path.addArc(withCenter: CGPoint(x: frame.midX, y: frame.midY),
radius: frame.width / 2.0 - 20.0,
startAngle: -(CGFloat.pi / 2),
endAngle: CGFloat.pi + CGFloat.pi / 2,
clockwise: true)
secondLayer.path = path.cgPath
secondLayer.strokeColor = UIColor.black.cgColor
secondLayer.fillColor = UIColor.clear.cgColor
secondLayer.speed = 0.0
view.layer.addSublayer(secondLayer)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 60.0
secondLayer.add(animation, forKey: "strokeCircle")
let displayLink = CADisplayLink(target: self, selector: #selector(update(_:)))
displayLink.preferredFramesPerSecond = 60
displayLink.add(to: RunLoop.current, forMode: .common)
}
@objc func update(_ displayLink: CADisplayLink) {
let time = Date().timeIntervalSince1970
let seconds = floor(time).truncatingRemainder(dividingBy: 60)
let milliseconds = time - floor(time)
secondLayer.timeOffset = seconds + milliseconds
}
}
| 31.428571 | 82 | 0.677922 |
38d24d0ef6d78e844feb35ef66c3718e326bfa8e | 17,860 | import Foundation
import MapboxMobileEvents
import MapboxDirections
let NavigationEventTypeRouteRetrieval = "mobile.performance_trace"
/**
The `EventsManagerDataSource` protocol declares values required for recording route following events.
*/
public protocol EventsManagerDataSource: class {
var routeProgress: RouteProgress { get }
var router: Router! { get }
var desiredAccuracy: CLLocationAccuracy { get }
var locationProvider: NavigationLocationManager.Type { get }
}
@available(swift, obsoleted: 0.1, renamed: "NavigationEventsManager")
public typealias EventsManager = NSObject
/**
The `NavigationEventsManager` is responsible for being the liaison between MapboxCoreNavigation and the Mapbox telemetry framework.
*/
open class NavigationEventsManager {
var sessionState: SessionState?
var outstandingFeedbackEvents = [CoreFeedbackEvent]()
weak var dataSource: EventsManagerDataSource?
/**
Indicates whether the application depends on MapboxNavigation in addition to MapboxCoreNavigation.
*/
var usesDefaultUserInterface = {
return Bundle.mapboxNavigationIfInstalled != nil
}()
/// :nodoc: the internal lower-level mobile events manager is an implementation detail which should not be manipulated directly
private var mobileEventsManager: MMEEventsManager!
lazy var accessToken: String = {
guard let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject],
let token = dict["MGLMapboxAccessToken"] as? String else {
//we can assert here because if the token was passed in, it would of overriden this closure.
//we return an empty string so we don't crash in production (in keeping with behavior of `assert`)
assertionFailure("`accessToken` must be set in the Info.plist as `MGLMapboxAccessToken` or the `Route` passed into the `NavigationService` must have the `accessToken` property set.")
return ""
}
return token
}()
public required init(dataSource source: EventsManagerDataSource?, accessToken possibleToken: String? = nil, mobileEventsManager: MMEEventsManager = .shared()) {
dataSource = source
if let tokenOverride = possibleToken {
accessToken = tokenOverride
}
self.mobileEventsManager = mobileEventsManager
start()
resumeNotifications()
}
deinit {
suspendNotifications()
sessionState = nil
}
private func resumeNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate(_:)), name: UIApplication.willTerminateNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didChangeOrientation(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didChangeApplicationState(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didChangeApplicationState(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
private func suspendNotifications() {
NotificationCenter.default.removeObserver(self)
}
/**
When set to `false`, flushing of telemetry events is not delayed. Is set to `true` by default.
*/
public var delaysEventFlushing = true
func start() {
let userAgent = usesDefaultUserInterface ? "mapbox-navigation-ui-ios" : "mapbox-navigation-ios"
mobileEventsManager.initialize(withAccessToken: accessToken, userAgentBase: userAgent, hostSDKVersion: String(describing: Bundle.mapboxCoreNavigation.object(forInfoDictionaryKey: "CFBundleShortVersionString")!))
mobileEventsManager.disableLocationMetrics()
mobileEventsManager.sendTurnstileEvent()
}
func navigationCancelEvent(rating potentialRating: Int? = nil, comment: String? = nil) -> NavigationEventDetails? {
guard let dataSource = dataSource, let sessionState = sessionState else { return nil }
let rating = potentialRating ?? MMEEventsManager.unrated
var event = NavigationEventDetails(dataSource: dataSource, session: sessionState, defaultInterface: usesDefaultUserInterface)
event.event = MMEEventTypeNavigationCancel
event.arrivalTimestamp = sessionState.arrivalTimestamp
let validRating: Bool = (rating >= MMEEventsManager.unrated && rating <= 100)
assert(validRating, "MMEEventsManager: Invalid Rating. Values should be between \(MMEEventsManager.unrated) (none) and 100.")
guard validRating else { return event }
event.rating = rating
event.comment = comment
return event
}
func navigationRouteRetrievalEvent() -> PerformanceEventDetails? {
guard let sessionState = sessionState,
let responseEndDate = sessionState.currentRoute.responseEndDate,
let fetchStartDate = sessionState.currentRoute.fetchStartDate else {
return nil
}
var event = PerformanceEventDetails(event: NavigationEventTypeRouteRetrieval, session: sessionState, createdOn: sessionState.currentRoute.responseEndDate)
event.counters.append(PerformanceEventDetails.Counter(name: "elapsed_time",
value: responseEndDate.timeIntervalSince(fetchStartDate)))
if let routeIdentifier = sessionState.currentRoute.routeIdentifier {
event.attributes.append(PerformanceEventDetails.Attribute(name: "route_uuid", value: routeIdentifier))
}
return event
}
func navigationDepartEvent() -> NavigationEventDetails? {
guard let dataSource = dataSource, let sessionState = sessionState else { return nil }
var event = NavigationEventDetails(dataSource: dataSource, session: sessionState, defaultInterface: usesDefaultUserInterface)
event.event = MMEEventTypeNavigationDepart
return event
}
func navigationArriveEvent() -> NavigationEventDetails? {
guard let dataSource = dataSource, let sessionState = sessionState else { return nil }
var event = NavigationEventDetails(dataSource: dataSource, session: sessionState, defaultInterface: usesDefaultUserInterface)
event.event = MMEEventTypeNavigationArrive
event.arrivalTimestamp = dataSource.router.rawLocation?.timestamp ?? Date()
return event
}
func navigationFeedbackEventWithLocationsAdded(event: CoreFeedbackEvent) -> [String: Any] {
var eventDictionary = event.eventDictionary
eventDictionary["feedbackId"] = event.id.uuidString
eventDictionary["locationsBefore"] = sessionState?.pastLocations.allObjects.filter { $0.timestamp <= event.timestamp}.map {$0.dictionaryRepresentation}
eventDictionary["locationsAfter"] = sessionState?.pastLocations.allObjects.filter {$0.timestamp > event.timestamp}.map {$0.dictionaryRepresentation}
return eventDictionary
}
func navigationFeedbackEvent(type: FeedbackType, description: String?) -> NavigationEventDetails? {
guard let dataSource = dataSource, let sessionState = sessionState else { return nil }
var event = NavigationEventDetails(dataSource: dataSource, session: sessionState, defaultInterface: usesDefaultUserInterface)
event.event = MMEEventTypeNavigationFeedback
event.userId = UIDevice.current.identifierForVendor?.uuidString
event.feedbackType = type.description
event.description = description
event.screenshot = captureScreen(scaledToFit: 250)?.base64EncodedString()
return event
}
func navigationRerouteEvent(eventType: String = MMEEventTypeNavigationReroute) -> NavigationEventDetails? {
guard let dataSource = dataSource, let sessionState = sessionState else { return nil }
let timestamp = dataSource.router.rawLocation?.timestamp ?? Date()
var event = NavigationEventDetails(dataSource: dataSource, session: sessionState, defaultInterface: usesDefaultUserInterface)
event.event = eventType
event.created = timestamp
if let lastRerouteDate = sessionState.lastRerouteDate {
event.secondsSinceLastReroute = round(timestamp.timeIntervalSince(lastRerouteDate))
} else {
event.secondsSinceLastReroute = -1
}
// These are placeholders until the route controller's RouteProgress is updated after rerouting
event.newDistanceRemaining = -1
event.newDurationRemaining = -1
event.newGeometry = nil
event.screenshot = captureScreen(scaledToFit: 250)?.base64EncodedString()
return event
}
public func sendCarPlayConnectEvent() {
let date = Date()
mobileEventsManager.enqueueEvent(withName: MMEventTypeNavigationCarplayConnect, attributes: [MMEEventKeyEvent: MMEventTypeNavigationCarplayConnect, MMEEventKeyCreated: date.ISO8601])
mobileEventsManager.flush()
}
public func sendCarPlayDisconnectEvent() {
let date = Date()
mobileEventsManager.enqueueEvent(withName: MMEventTypeNavigationCarplayDisconnect, attributes: [MMEEventKeyEvent: MMEventTypeNavigationCarplayDisconnect, MMEEventKeyCreated: date.ISO8601])
mobileEventsManager.flush()
}
func sendRouteRetrievalEvent() {
guard let attributes = (try? navigationRouteRetrievalEvent()?.asDictionary()) as [String: Any]?? else { return }
mobileEventsManager.enqueueEvent(withName: NavigationEventTypeRouteRetrieval, attributes: attributes ?? [:])
mobileEventsManager.flush()
}
func sendDepartEvent() {
guard let attributes = (try? navigationDepartEvent()?.asDictionary()) as [String: Any]?? else { return }
mobileEventsManager.enqueueEvent(withName: MMEEventTypeNavigationDepart, attributes: attributes ?? [:])
mobileEventsManager.flush()
}
func sendArriveEvent() {
guard let attributes = (try? navigationArriveEvent()?.asDictionary()) as [String: Any]?? else { return }
mobileEventsManager.enqueueEvent(withName: MMEEventTypeNavigationArrive, attributes: attributes ?? [:])
mobileEventsManager.flush()
}
func sendCancelEvent(rating: Int? = nil, comment: String? = nil) {
guard let attributes = (try? navigationCancelEvent(rating: rating, comment: comment)?.asDictionary()) as [String: Any]?? else { return }
mobileEventsManager.enqueueEvent(withName: MMEEventTypeNavigationCancel, attributes: attributes ?? [:])
mobileEventsManager.flush()
}
func sendFeedbackEvents(_ events: [CoreFeedbackEvent]) {
events.forEach { event in
// remove from outstanding event queue
if let index = outstandingFeedbackEvents.firstIndex(of: event) {
outstandingFeedbackEvents.remove(at: index)
}
let eventName = event.eventDictionary["event"] as! String
let eventDictionary = navigationFeedbackEventWithLocationsAdded(event: event)
mobileEventsManager.enqueueEvent(withName: eventName, attributes: eventDictionary)
}
mobileEventsManager.flush()
}
func enqueueFeedbackEvent(type: FeedbackType, description: String?) -> UUID? {
guard let eventDictionary = (try? navigationFeedbackEvent(type: type, description: description)?.asDictionary()) as [String: Any]?? else { return nil }
let event = FeedbackEvent(timestamp: Date(), eventDictionary: eventDictionary ?? [:])
outstandingFeedbackEvents.append(event)
return event.id
}
func enqueueRerouteEvent() {
guard let eventDictionary = (try? navigationRerouteEvent()?.asDictionary()) as [String: Any]?? else { return }
let timestamp = dataSource?.router.location?.timestamp ?? Date()
sessionState?.lastRerouteDate = timestamp
sessionState?.numberOfReroutes += 1
let event = RerouteEvent(timestamp: timestamp, eventDictionary: eventDictionary ?? [:])
outstandingFeedbackEvents.append(event)
}
func resetSession() {
guard let dataSource = dataSource else { return }
let route = dataSource.routeProgress.route
sessionState = SessionState(currentRoute: route, originalRoute: route)
}
func enqueueFoundFasterRouteEvent() {
guard let eventDictionary = (try? navigationRerouteEvent(eventType: FasterRouteFoundEvent)?.asDictionary()) as [String: Any]?? else { return }
let timestamp = Date()
sessionState?.lastRerouteDate = timestamp
let event = RerouteEvent(timestamp: Date(), eventDictionary: eventDictionary ?? [:])
outstandingFeedbackEvents.append(event)
}
func sendOutstandingFeedbackEvents(forceAll: Bool) {
let flushAll = forceAll || !shouldDelayEvents()
let eventsToPush = eventsToFlush(flushAll: flushAll)
sendFeedbackEvents(eventsToPush)
}
func eventsToFlush(flushAll: Bool) -> [CoreFeedbackEvent] {
let now = Date()
let eventsToPush = flushAll ? outstandingFeedbackEvents : outstandingFeedbackEvents.filter {
now.timeIntervalSince($0.timestamp) > SecondsBeforeCollectionAfterFeedbackEvent
}
return eventsToPush
}
private func shouldDelayEvents() -> Bool {
return delaysEventFlushing
}
/**
Send feedback about the current road segment/maneuver to the Mapbox data team.
You can pair this with a custom feedback UI in your app to flag problems during navigation such as road closures, incorrect instructions, etc.
@param type A `FeedbackType` used to specify the type of feedback
@param description A custom string used to describe the problem in detail.
@return Returns a UUID used to identify the feedback event
If you provide a custom feedback UI that lets users elaborate on an issue, you should call this before you show the custom UI so the location and timestamp are more accurate.
You can then call `updateFeedback(uuid:type:source:description:)` with the returned feedback UUID to attach any additional metadata to the feedback.
*/
public func recordFeedback(type: FeedbackType = .general, description: String? = nil) -> UUID? {
return enqueueFeedbackEvent(type: type, description: description)
}
/**
Update the feedback event with a specific feedback identifier. If you implement a custom feedback UI that lets a user elaborate on an issue, you can use this to update the metadata.
Note that feedback is sent 20 seconds after being recorded, so you should promptly update the feedback metadata after the user discards any feedback UI.
*/
public func updateFeedback(uuid: UUID, type: FeedbackType, source: FeedbackSource, description: String?) {
if let lastFeedback = outstandingFeedbackEvents.first(where: { $0.id == uuid}) as? FeedbackEvent {
lastFeedback.update(type: type, source: source, description: description)
}
}
/**
Discard a recorded feedback event, for example if you have a custom feedback UI and the user canceled feedback.
*/
public func cancelFeedback(uuid: UUID) {
if let index = outstandingFeedbackEvents.firstIndex(where: {$0.id == uuid}) {
outstandingFeedbackEvents.remove(at: index)
}
}
//MARK: - Session State Management
@objc private func didChangeOrientation(_ notification: NSNotification) {
sessionState?.reportChange(to: UIDevice.current.orientation)
}
@objc private func didChangeApplicationState(_ notification: NSNotification) {
sessionState?.reportChange(to: UIApplication.shared.applicationState)
}
@objc private func applicationWillTerminate(_ notification: NSNotification) {
if sessionState?.terminated == false {
sendCancelEvent(rating: nil, comment: nil)
sessionState?.terminated = true
}
sendOutstandingFeedbackEvents(forceAll: true)
}
func reportReroute(progress: RouteProgress, proactive: Bool) {
let route = progress.route
// if the user has already arrived and a new route has been set, restart the navigation session
if sessionState?.arrivalTimestamp != nil {
resetSession()
} else {
sessionState?.currentRoute = route
}
if (proactive) {
enqueueFoundFasterRouteEvent()
}
let latestReroute = outstandingFeedbackEvents.compactMap({ $0 as? RerouteEvent }).last
latestReroute?.update(newRoute: route)
}
func update(progress: RouteProgress) {
defer {
// ensure we always flush, irrespective of how the method exits
sendOutstandingFeedbackEvents(forceAll: false)
}
if sessionState?.arrivalTimestamp == nil,
progress.currentLegProgress.userHasArrivedAtWaypoint {
sessionState?.arrivalTimestamp = dataSource?.router.location?.timestamp ?? Date()
sendArriveEvent()
return
}
if sessionState?.departureTimestamp == nil {
sessionState?.departureTimestamp = dataSource?.router.location?.timestamp ?? Date()
sendDepartEvent()
}
}
}
| 46.030928 | 219 | 0.693281 |
f938f84af25570fdf689a129cfbde69975e79ffd | 1,243 | //
// URLSession+Extensions.swift
// Pods-YFZSwiftExtensions_Example
//
// Created by YosiFZ on 28/06/2020.
//
import Foundation
@available(iOS 11.0, tvOS 11.0, *)
public extension URLSession {
func makeHTTPReqest(url:URL, method:String = "GET", completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> () {
var request = URLRequest(url: url)
request.httpMethod = method
URLSession.shared.dataTask(with: request, completionHandler: completionHandler).resume()
}
func makeHTTPReqest(url:String, method:String = "GET", completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> () {
guard let url = URL(string: url) else {
completionHandler(nil,nil,URLError(URLError.Code.init(rawValue: -159159)))
return;
}
var request = URLRequest(url: url)
request.httpMethod = method
URLSession.shared.dataTask(with: request, completionHandler: completionHandler).resume()
}
func makeHTTPReqest(request: URLRequest, with completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
URLSession.shared.dataTask(with: request, completionHandler: completion).resume()
}
}
| 35.514286 | 134 | 0.654063 |
75d6e5c7449757f536dea806a998d2fbd849f852 | 458 | //
// PostStoreService.swift
// Posts
//
// Created by Joshua Simmons on 19/03/2019.
// Copyright © 2019 Joshua. All rights reserved.
//
import Foundation
import RxSwift
import RealmSwift
protocol PostStoredDataProvider: ObjectStoredDataProvider {
func getPosts() -> [Post]
}
class PostStoreService: PostStoredDataProvider {
func getPosts() -> [Post] {
let posts = Realm.default.objects(Post.self)
return Array(posts)
}
}
| 19.083333 | 59 | 0.696507 |
e41efaec4aba95d15a06bc6a2471e905667f5400 | 6,230 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// Triple - Helper class for working with Destination.target values
///
/// Used for parsing values such as x86_64-apple-macosx10.10 into
/// set of enums. For os/arch/abi based conditions in build plan.
///
/// @see Destination.target
/// @see https://github.com/apple/swift-llvm/blob/stable/include/llvm/ADT/Triple.h
///
public struct Triple: Encodable {
public let tripleString: String
public let arch: Arch
public let vendor: Vendor
public let os: OS
public let abi: ABI
public enum Error: Swift.Error {
case badFormat
case unknownArch
case unknownOS
}
public enum Arch: String, Encodable {
case x86_64
case i686
case powerpc64le
case s390x
case aarch64
case armv7
case arm
}
public enum Vendor: String, Encodable {
case unknown
case apple
}
public enum OS: String, Encodable {
case darwin
case macOS = "macosx"
case linux
case windows
fileprivate static let allKnown:[OS] = [
.darwin,
.macOS,
.linux,
.windows
]
}
public enum ABI: String, Encodable {
case unknown
case android
}
public init(_ string: String) throws {
let components = string.split(separator: "-").map(String.init)
guard components.count == 3 || components.count == 4 else {
throw Error.badFormat
}
guard let arch = Arch(rawValue: components[0]) else {
throw Error.unknownArch
}
let vendor = Vendor(rawValue: components[1]) ?? .unknown
guard let os = Triple.parseOS(components[2]) else {
throw Error.unknownOS
}
let abi = components.count > 3 ? Triple.parseABI(components[3]) : nil
self.tripleString = string
self.arch = arch
self.vendor = vendor
self.os = os
self.abi = abi ?? .unknown
}
fileprivate static func parseOS(_ string: String) -> OS? {
for candidate in OS.allKnown {
if string.hasPrefix(candidate.rawValue) {
return candidate
}
}
return nil
}
fileprivate static func parseABI(_ string: String) -> ABI? {
if string.hasPrefix(ABI.android.rawValue) {
return ABI.android
}
return nil
}
public func isAndroid() -> Bool {
return os == .linux && abi == .android
}
public func isDarwin() -> Bool {
return vendor == .apple || os == .macOS || os == .darwin
}
public func isLinux() -> Bool {
return os == .linux
}
public func isWindows() -> Bool {
return os == .windows
}
/// Returns the triple string for the given platform version.
///
/// This is currently meant for Apple platforms only.
public func tripleString(forPlatformVersion version: String) -> String {
precondition(isDarwin())
return self.tripleString + version
}
public static let macOS = try! Triple("x86_64-apple-macosx")
public static let x86_64Linux = try! Triple("x86_64-unknown-linux-gnu")
public static let i686Linux = try! Triple("i686-unknown-linux")
public static let ppc64leLinux = try! Triple("powerpc64le-unknown-linux")
public static let s390xLinux = try! Triple("s390x-unknown-linux")
public static let arm64Linux = try! Triple("aarch64-unknown-linux-gnu")
public static let armLinux = try! Triple("armv7-unknown-linux-gnueabihf")
public static let armAndroid = try! Triple("armv7a-unknown-linux-androideabi")
public static let arm64Android = try! Triple("aarch64-unknown-linux-android")
public static let x86_64Android = try! Triple("x86_64-unknown-linux-android")
public static let i686Android = try! Triple("i686-unknown-linux-android")
public static let windows = try! Triple("x86_64-unknown-windows-msvc")
#if os(macOS)
public static let hostTriple: Triple = .macOS
#elseif os(Windows)
public static let hostTriple: Triple = .windows
#elseif os(Linux)
#if arch(x86_64)
public static let hostTriple: Triple = .x86_64Linux
#elseif arch(i386)
public static let hostTriple: Triple = .i686Linux
#elseif arch(powerpc64le)
public static let hostTriple: Triple = .ppc64leLinux
#elseif arch(s390x)
public static let hostTriple: Triple = .s390xLinux
#elseif arch(arm64)
public static let hostTriple: Triple = .arm64Linux
#elseif arch(arm)
public static let hostTriple: Triple = .armLinux
#endif
#elseif os(Android)
#if arch(arm)
public static let hostTriple: Triple = .armAndroid
#elseif arch(arm64)
public static let hostTriple: Triple = .arm64Android
#elseif arch(x86_64)
public static let hostTriple: Triple = .x86_64Android
#elseif arch(i386)
public static let hostTriple: Triple = .i686Android
#endif
#endif
}
extension Triple {
/// The file extension for dynamic libraries (eg. `.dll`, `.so`, or `.dylib`)
public var dynamicLibraryExtension: String {
switch os {
case .darwin, .macOS:
return ".dylib"
case .linux:
return ".so"
case .windows:
return ".dll"
}
}
public var executableExtension: String {
switch os {
case .darwin, .macOS:
return ""
case .linux:
return ""
case .windows:
return ".exe"
}
}
/// The file extension for Foundation-style bundle.
public var nsbundleExtension: String {
switch os {
case .darwin, .macOS:
return ".bundle"
default:
// See: https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/FHS%20Bundles.md
return ".resources"
}
}
}
| 29.248826 | 104 | 0.620546 |
f897705ec1681db6b55165abac4444de1520aa3e | 2,139 | //
// AppDelegate.swift
// iOS-Animations
//
// Created by race on 15/11/8.
// Copyright © 2015年 alfredcc. 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.753623 |
d51c229434e312171908a5b839b1e74b41bb5983 | 3,731 | //
// AppDelegate.swift
// Recipes App
//
// Created by Eliu Efraín Díaz Bravo on 31/07/20.
// Copyright © 2020 Eliu Efraín Díaz Bravo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
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.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Recipes_App")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 44.951807 | 199 | 0.670062 |
d6cda0c2f3c0c7d2a0a8bc4799b2682e5f91a8b3 | 1,441 | //
// PLDB+Model.swift
// PLDB
//
// Created by Plumk on 2021/7/28.
//
import Foundation
/// 数据表模型
public protocol PLDBModel: PLDBFieldType {
init()
/// 唯一Id 用于更新删除 返回字段名 字段值
var uniqueId: (String, Int) { get }
/// 表名
static var tableName: String { get }
}
extension PLDBModel {
/// 获取model中的数据库字段
/// - Returns:
func extractFields() -> [PLDB.FieldDescription] {
var descriptions = [PLDB.FieldDescription]()
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if var name = child.label,
let property = child.value as? PLDBFieldWrapper {
let desc = property.fieldDescription
if desc.fieldName == nil {
name.removeFirst()
desc.fieldName = name
}
descriptions.append(desc)
}
}
return descriptions
}
func update(_ dict: [AnyHashable: Any]?) {
guard let dict = dict else {
return
}
let fds = self.extractFields()
for fd in fds {
guard let fieldName = fd.fieldName else {
continue
}
if let value = dict[fieldName] {
fd.setValue(value)
}
}
}
}
| 21.507463 | 64 | 0.472588 |
90a541208ba9cd441473d7dd7f656cf8a4e99877 | 4,647 | //
// MoviesResultTableViewController.swift
// Movie Database App
//
// Created by Pyramid on 26/12/21.
//
import UIKit
// This protocol helps inform ViewController that a suggested search or movie was selected.
protocol SuggestedSearch: AnyObject {
// A Movie was selected; inform our delgeate that a movie was selected to view.
func didSelectMovie(_ movie: MoviesModel)
}
class MoviesResultTableViewController: UITableViewController {
//MARK: Properties
///This properties used for both seach results and list based on category like year/actors
var filteredMovies = [MoviesModel]()
var sections = [Section]()
var isDashboardList:Bool = false
var selectedListValue:String = ""
// Your delegate to receive suggested search .
weak var suggestedSearchDelegate: SuggestedSearch?
var showSuggestedSearches: Bool = false {
didSet {
if oldValue != showSuggestedSearches {
tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if isDashboardList
{
loadData()
}
}
//MARK: - Load/Setup Data
func loadData()
{
var groupedDictionary = [String : [MoviesModel]]()
switch selectedListValue {
case CategoryNames.Year:
groupedDictionary = Dictionary(grouping: (self.filteredMovies), by: {String($0.Year)})
case CategoryNames.Genre:
groupedDictionary = Dictionary(grouping: (self.filteredMovies), by: {String($0.Genre)})
case CategoryNames.Actors:
groupedDictionary = Dictionary(grouping: (self.filteredMovies), by: {String($0.Actors)})
case CategoryNames.Directors:
groupedDictionary = Dictionary(grouping: (self.filteredMovies), by: {String($0.Director)})
default:
break
}
let keys = groupedDictionary.keys.sorted()
self.sections = keys.map {Section(letter: $0, movies: groupedDictionary[$0]!)}
print(self.sections)
DispatchQueue.main.async {
UITableViewHeaderFooterView.appearance().tintColor = .lightGray
self.tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return isDashboardList ? sections.count : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return isDashboardList ? sections[section].movies.count : filteredMovies.count
}
override func tableView(_ tableView:UITableView, titleForHeaderInSection section: Int) -> String?
{
return isDashboardList ? sections[section].letter : nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell") as? CategoryOptionTableViewCell
if cell == nil
{
let topLevelObjects = Bundle.main.loadNibNamed("CategoryOptionTableViewCell", owner: self, options: nil)
cell = topLevelObjects?[0] as? CategoryOptionTableViewCell
}
let cellData = isDashboardList ? sections[indexPath.section].movies[indexPath.row] : filteredMovies[indexPath.row]
cell?.titleLbl.text = cellData.Title
cell?.yearLbl.text = "Year "+cellData.Year
cell?.durationLbl.text = cellData.Runtime
cell?.genreLbl.text = cellData.Genre
cell?.posterImgView.load(url: URL(string:cellData.Poster)!)
return cell!
}
//MARK: Tableview Delegates
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 125
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isDashboardList
{
let nextVc = MoviewDetailViewController()
nextVc.movieDetails = sections[indexPath.section].movies[indexPath.row]
self.navigationController?.pushViewController(nextVc, animated: true)
}
else
{
guard let suggestedSearchDelegate = suggestedSearchDelegate else { return }
let selectedMovie = filteredMovies[indexPath.row]
suggestedSearchDelegate.didSelectMovie(selectedMovie)
}
}
}
| 32.957447 | 122 | 0.64192 |
2328294fbfb68368032fada74443e1501622a0ea | 267 | //
// ColorPalette.swift
// CV-MVVM-SwiftUI
//
// Created by parrilla nelson on 02/03/2020.
// Copyright © 2020 parrilla nelson. All rights reserved.
//
import UIKit
struct ColorPalette {
static let gray = UIColor(named: "Gray")! //#EC616C
}
| 15.705882 | 58 | 0.640449 |
d5c186896d12b072beaf3fda03e34da47b058356 | 14,018 | //
// Persistence.swift
// Mixpanel
//
// Created by Yarden Eitan on 6/2/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
struct ArchivedProperties {
let superProperties: InternalProperties
let timedEvents: InternalProperties
let distinctId: String
let alias: String?
let peopleDistinctId: String?
let peopleUnidentifiedQueue: Queue
#if DECIDE
let shownNotifications: Set<Int>
let automaticEventsEnabled: Bool?
#endif // DECIDE
}
class Persistence {
enum ArchiveType: String {
case events
case people
case properties
case codelessBindings
case variants
}
class func filePathWithType(_ type: ArchiveType, token: String) -> String? {
return filePathFor(type.rawValue, token: token)
}
class private func filePathFor(_ archiveType: String, token: String) -> String? {
let filename = "mixpanel-\(token)-\(archiveType)"
let manager = FileManager.default
#if os(iOS)
let url = manager.urls(for: .libraryDirectory, in: .userDomainMask).last
#else
let url = manager.urls(for: .cachesDirectory, in: .userDomainMask).last
#endif // os(iOS)
guard let urlUnwrapped = url?.appendingPathComponent(filename).path else {
return nil
}
return urlUnwrapped
}
#if DECIDE
class func archive(eventsQueue: Queue,
peopleQueue: Queue,
properties: ArchivedProperties,
codelessBindings: Set<CodelessBinding>,
variants: Set<Variant>,
token: String) {
archiveEvents(eventsQueue, token: token)
archivePeople(peopleQueue, token: token)
archiveProperties(properties, token: token)
archiveVariants(variants, token: token)
archiveCodelessBindings(codelessBindings, token: token)
}
#else
class func archive(eventsQueue: Queue,
peopleQueue: Queue,
properties: ArchivedProperties,
token: String) {
archiveEvents(eventsQueue, token: token)
archivePeople(peopleQueue, token: token)
archiveProperties(properties, token: token)
}
#endif // DECIDE
class func archiveEvents(_ eventsQueue: Queue, token: String) {
objc_sync_enter(self)
archiveToFile(.events, object: eventsQueue, token: token)
objc_sync_exit(self)
}
class func archivePeople(_ peopleQueue: Queue, token: String) {
objc_sync_enter(self)
archiveToFile(.people, object: peopleQueue, token: token)
objc_sync_exit(self)
}
class func archiveProperties(_ properties: ArchivedProperties, token: String) {
objc_sync_enter(self)
var p = InternalProperties()
p["distinctId"] = properties.distinctId
p["alias"] = properties.alias
p["superProperties"] = properties.superProperties
p["peopleDistinctId"] = properties.peopleDistinctId
p["peopleUnidentifiedQueue"] = properties.peopleUnidentifiedQueue
p["timedEvents"] = properties.timedEvents
#if DECIDE
p["shownNotifications"] = properties.shownNotifications
p["automaticEvents"] = properties.automaticEventsEnabled
#endif // DECIDE
archiveToFile(.properties, object: p, token: token)
objc_sync_exit(self)
}
#if DECIDE
class func archiveVariants(_ variants: Set<Variant>, token: String) {
objc_sync_enter(self)
archiveToFile(.variants, object: variants, token: token)
objc_sync_exit(self)
}
class func archiveCodelessBindings(_ codelessBindings: Set<CodelessBinding>, token: String) {
objc_sync_enter(self)
archiveToFile(.codelessBindings, object: codelessBindings, token: token)
objc_sync_exit(self)
}
#endif // DECIDE
class private func archiveToFile(_ type: ArchiveType, object: Any, token: String) {
let filePath = filePathWithType(type, token: token)
guard let path = filePath else {
Logger.error(message: "bad file path, cant fetch file")
return
}
if !NSKeyedArchiver.archiveRootObject(object, toFile: path) {
Logger.error(message: "failed to archive \(type.rawValue)")
return
}
addSkipBackupAttributeToItem(at: path)
}
class private func addSkipBackupAttributeToItem(at path: String) {
var url = URL.init(fileURLWithPath: path)
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
do {
try url.setResourceValues(resourceValues)
} catch {
Logger.info(message: "Error excluding \(path) from backup.")
}
}
#if DECIDE
class func unarchive(token: String) -> (eventsQueue: Queue,
peopleQueue: Queue,
superProperties: InternalProperties,
timedEvents: InternalProperties,
distinctId: String,
alias: String?,
peopleDistinctId: String?,
peopleUnidentifiedQueue: Queue,
shownNotifications: Set<Int>,
codelessBindings: Set<CodelessBinding>,
variants: Set<Variant>,
automaticEventsEnabled: Bool?) {
let eventsQueue = unarchiveEvents(token: token)
let peopleQueue = unarchivePeople(token: token)
let codelessBindings = unarchiveCodelessBindings(token: token)
let variants = unarchiveVariants(token: token)
let (superProperties,
timedEvents,
distinctId,
alias,
peopleDistinctId,
peopleUnidentifiedQueue,
shownNotifications,
automaticEventsEnabled) = unarchiveProperties(token: token)
return (eventsQueue,
peopleQueue,
superProperties,
timedEvents,
distinctId,
alias,
peopleDistinctId,
peopleUnidentifiedQueue,
shownNotifications,
codelessBindings,
variants,
automaticEventsEnabled)
}
#else
class func unarchive(token: String) -> (eventsQueue: Queue,
peopleQueue: Queue,
superProperties: InternalProperties,
timedEvents: InternalProperties,
distinctId: String,
alias: String?,
peopleDistinctId: String?,
peopleUnidentifiedQueue: Queue) {
let eventsQueue = unarchiveEvents(token: token)
let peopleQueue = unarchivePeople(token: token)
let (superProperties,
timedEvents,
distinctId,
alias,
peopleDistinctId,
peopleUnidentifiedQueue,
_) = unarchiveProperties(token: token)
return (eventsQueue,
peopleQueue,
superProperties,
timedEvents,
distinctId,
alias,
peopleDistinctId,
peopleUnidentifiedQueue)
}
#endif // DECIDE
class private func unarchiveWithFilePath(_ filePath: String) -> Any? {
let unarchivedData: Any? = NSKeyedUnarchiver.unarchiveObject(withFile: filePath)
if unarchivedData == nil {
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
Logger.info(message: "Unable to remove file at path: \(filePath)")
}
}
return unarchivedData
}
class private func unarchiveEvents(token: String) -> Queue {
let data = unarchiveWithType(.events, token: token)
return data as? Queue ?? []
}
class private func unarchivePeople(token: String) -> Queue {
let data = unarchiveWithType(.people, token: token)
return data as? Queue ?? []
}
#if DECIDE
class private func unarchiveProperties(token: String) -> (InternalProperties,
InternalProperties,
String,
String?,
String?,
Queue,
Set<Int>,
Bool?) {
let properties = unarchiveWithType(.properties, token: token) as? InternalProperties
let (superProperties,
timedEvents,
distinctId,
alias,
peopleDistinctId,
peopleUnidentifiedQueue,
automaticEventsEnabled) = unarchivePropertiesHelper(token: token)
let shownNotifications =
properties?["shownNotifications"] as? Set<Int> ?? Set<Int>()
return (superProperties,
timedEvents,
distinctId,
alias,
peopleDistinctId,
peopleUnidentifiedQueue,
shownNotifications,
automaticEventsEnabled)
}
#else
class private func unarchiveProperties(token: String) -> (InternalProperties,
InternalProperties,
String,
String?,
String?,
Queue,
Bool?) {
return unarchivePropertiesHelper(token: token)
}
#endif // DECIDE
class private func unarchivePropertiesHelper(token: String) -> (InternalProperties,
InternalProperties,
String,
String?,
String?,
Queue,
Bool?) {
let properties = unarchiveWithType(.properties, token: token) as? InternalProperties
let superProperties =
properties?["superProperties"] as? InternalProperties ?? InternalProperties()
let timedEvents =
properties?["timedEvents"] as? InternalProperties ?? InternalProperties()
var distinctId =
properties?["distinctId"] as? String ?? ""
var alias =
properties?["alias"] as? String ?? nil
var peopleDistinctId =
properties?["peopleDistinctId"] as? String ?? nil
let peopleUnidentifiedQueue =
properties?["peopleUnidentifiedQueue"] as? Queue ?? Queue()
let automaticEventsEnabled =
properties?["automaticEvents"] as? Bool ?? nil
if properties == nil {
(distinctId, peopleDistinctId, alias) = restoreIdentity(token: token)
}
return (superProperties,
timedEvents,
distinctId,
alias,
peopleDistinctId,
peopleUnidentifiedQueue,
automaticEventsEnabled)
}
#if DECIDE
class private func unarchiveCodelessBindings(token: String) -> Set<CodelessBinding> {
let data = unarchiveWithType(.codelessBindings, token: token)
return data as? Set<CodelessBinding> ?? Set()
}
class private func unarchiveVariants(token: String) -> Set<Variant> {
let data = unarchiveWithType(.variants, token: token) as? Set<Variant>
return data ?? Set()
}
#endif // DECIDE
class private func unarchiveWithType(_ type: ArchiveType, token: String) -> Any? {
let filePath = filePathWithType(type, token: token)
guard let path = filePath else {
Logger.info(message: "bad file path, cant fetch file")
return nil
}
guard let unarchivedData = unarchiveWithFilePath(path) else {
Logger.info(message: "can't unarchive file")
return nil
}
return unarchivedData
}
class func storeIdentity(token: String, distinctID: String, peopleDistinctID: String?, alias: String?) {
guard let defaults = UserDefaults(suiteName: "Mixpanel") else {
return
}
let prefix = "mixpanel-\(token)-"
defaults.set(distinctID, forKey: prefix + "MPDistinctID")
defaults.set(peopleDistinctID, forKey: prefix + "MPPeopleDistinctID")
defaults.set(alias, forKey: prefix + "MPAlias")
defaults.synchronize()
}
class func restoreIdentity(token: String) -> (String, String?, String?) {
guard let defaults = UserDefaults(suiteName: "Mixpanel") else {
return ("", nil, nil)
}
let prefix = "mixpanel-\(token)-"
return (defaults.string(forKey: prefix + "MPDistinctID") ?? "",
defaults.string(forKey: prefix + "MPPeopleDistinctID"),
defaults.string(forKey: prefix + "MPAlias"))
}
class func deleteMPUserDefaultsData(token: String) {
guard let defaults = UserDefaults(suiteName: "Mixpanel") else {
return
}
let prefix = "mixpanel-\(token)-"
defaults.removeObject(forKey: prefix + "MPDistinctID")
defaults.removeObject(forKey: prefix + "MPPeopleDistinctID")
defaults.removeObject(forKey: prefix + "MPAlias")
defaults.synchronize()
}
}
| 37.183024 | 108 | 0.556071 |
08de9359d680d528bda69d0a72542a7f4ebbcd2a | 3,191 | //
// Copyright © 2020 Jakub Kiermasz. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#else
import AppKit
#endif
extension ViewLayout {
final class ViewDimensionLayout: DimensionLayout {
// MARK: - Properties
private let anchor: LayoutAnchor.Dimension
private let view: View
private let invoker: Layout
private let container: ConstraintsContainer
// MARK: - Initialization
init(for view: View, anchor: LayoutAnchor.Dimension, invoker: Layout, container: ConstraintsContainer) {
self.view = view
self.anchor = anchor
self.invoker = invoker
self.container = container
}
// MARK: - AxisLayout
func equalTo(constant: CGFloat) -> ConstraintMultiplier {
let constraint = LayoutConstraint(item: view, itemAttribute: self.anchor.attribute, relation: .equal, constant: constant)
return makePrioritizer(for: endorse(constraint))
}
func lessThanOrEqualTo(constant: CGFloat) -> ConstraintMultiplier {
let constraint = LayoutConstraint(item: view, itemAttribute: self.anchor.attribute, relation: .lessThanOrEqual, constant: constant)
return makePrioritizer(for: endorse(constraint))
}
func greaterThanOrEqualTo(constant: CGFloat) -> ConstraintMultiplier {
let constraint = LayoutConstraint(item: view, itemAttribute: self.anchor.attribute, relation: .greaterThanOrEqual, constant: constant)
return makePrioritizer(for: endorse(constraint))
}
func equalTo(_ sibling: View, _ anchor: LayoutAnchor.Dimension) -> ConstraintMultiplier {
let constraint = LayoutConstraint(item: view, itemAttribute: self.anchor.attribute, relation: .equal, target: sibling, targetAttribute: anchor.attribute)
return makePrioritizer(for: endorse(constraint))
}
func lessThanOrEqualTo(_ sibling: View, _ anchor: LayoutAnchor.Dimension) -> ConstraintMultiplier {
let constraint = LayoutConstraint(item: view, itemAttribute: self.anchor.attribute, relation: .lessThanOrEqual, target: sibling, targetAttribute: anchor.attribute)
return makePrioritizer(for: endorse(constraint))
}
func greaterThanOrEqualTo(_ sibling: View, _ anchor: LayoutAnchor.Dimension) -> ConstraintMultiplier {
let constraint = LayoutConstraint(item: view, itemAttribute: self.anchor.attribute, relation: .greaterThanOrEqual, target: sibling, targetAttribute: anchor.attribute)
return makePrioritizer(for: endorse(constraint))
}
// MARK: - Private
private func endorse(_ constraint: LayoutConstraint) -> LayoutConstraint {
container.add(constraint)
return constraint
}
private func makePrioritizer(for constraint: LayoutConstraint) -> ConstraintMultiplier {
DefaultLayoutResult(constraint: constraint, invoker: invoker, container: container)
}
}
}
| 40.910256 | 178 | 0.652773 |
56f7f6d8fa9c3f8b2942ce825ebfa4b7b54495ea | 3,059 | //
// CDSTypography.swift
//
//
// Created by SHIN YOON AH on 2021/10/31.
//
#if !os(macOS)
import UIKit
extension String {
public enum CDSTypography {
case header0
case header1
case header2
case header3
case subtitle0
case body0
case body1
case body2
case body3
case body4
case body5
case body6
case body7
case caption0
case caption1
case caption2
case button0
case button1
case catchu0
case catchu1
case catchu2
case catchu3
public var font: UIFont {
switch self {
case .header0:
return CDSFont.header0
case .header1:
return CDSFont.header1
case .header2:
return CDSFont.header2
case .header3:
return CDSFont.header3
case .subtitle0:
return CDSFont.subtitle0
case .body0:
return CDSFont.body0
case .body1:
return CDSFont.body1
case .body2:
return CDSFont.body2
case .body3:
return CDSFont.body3
case .body4:
return CDSFont.body4
case .body5:
return CDSFont.body5
case .body6:
return CDSFont.body6
case .body7:
return CDSFont.body7
case .caption0:
return CDSFont.caption0
case .caption1:
return CDSFont.caption1
case .caption2:
return CDSFont.caption2
case .button0:
return CDSFont.button0
case .button1:
return CDSFont.button1
case .catchu0:
return CDSFont.catchu0
case .catchu1:
return CDSFont.catchu1
case .catchu2:
return CDSFont.catchu2
case .catchu3:
return CDSFont.catchu3
}
}
public var lineHeight: CGFloat {
switch self {
default:
return -0.6
}
}
internal func style(color: UIColor? = nil) -> [NSAttributedString.Key: Any] {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = self.font.pointSize * self.lineHeight - self.font.lineHeight
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: color ?? UIColor.black,
.font: self.font,
.paragraphStyle: paragraphStyle
]
return attributes
}
}
internal func attributedString(byPreset preset: CDSTypography, color: UIColor? = nil) -> NSAttributedString {
return NSAttributedString.init(string : self, attributes: preset.style(color: color))
}
}
#endif
| 27.070796 | 113 | 0.501144 |
38e6a5b963e52d07075692f8cd861625605cb5cd | 17,253 | //
// OmniBar.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Core
import os.log
extension OmniBar: NibLoading {}
// swiftlint:disable file_length
// swiftlint:disable type_body_length
class OmniBar: UIView {
public static let didLayoutNotification = Notification.Name("com.duckduckgo.app.OmniBarDidLayout")
@IBOutlet weak var searchLoupe: UIView!
@IBOutlet weak var searchContainer: UIView!
@IBOutlet weak var searchStackContainer: UIStackView!
@IBOutlet weak var searchFieldContainer: SearchFieldContainerView!
@IBOutlet weak var siteRatingContainer: SiteRatingContainerView!
@IBOutlet weak var textField: TextFieldWithInsets!
@IBOutlet weak var editingBackground: RoundedRectangleView!
@IBOutlet weak var clearButton: UIButton!
@IBOutlet weak var menuButton: UIButton!
@IBOutlet weak var settingsButton: UIButton!
@IBOutlet weak var separatorView: UIView!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var refreshButton: UIButton!
@IBOutlet weak var bookmarksButton: UIButton!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var forwardButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
private(set) var menuButtonContent = MenuButton()
// Don't use weak because adding/removing them causes them to go away
@IBOutlet var separatorHeightConstraint: NSLayoutConstraint!
@IBOutlet var leftButtonsSpacingConstraint: NSLayoutConstraint!
@IBOutlet var rightButtonsSpacingConstraint: NSLayoutConstraint!
@IBOutlet var searchContainerCenterConstraint: NSLayoutConstraint!
@IBOutlet var searchContainerMaxWidthConstraint: NSLayoutConstraint!
@IBOutlet var omniBarLeadingConstraint: NSLayoutConstraint!
@IBOutlet var omniBarTrailingConstraint: NSLayoutConstraint!
weak var omniDelegate: OmniBarDelegate?
fileprivate var state: OmniBarState = SmallOmniBarState.HomeNonEditingState()
private lazy var appUrls: AppUrls = AppUrls()
private var safeAreaInsetsObservation: NSKeyValueObservation?
private(set) var trackersAnimator = TrackersAnimator()
static func loadFromXib() -> OmniBar {
return OmniBar.load(nibName: "OmniBar")
}
var siteRatingView: SiteRatingView {
return siteRatingContainer.siteRatingView
}
override func awakeFromNib() {
super.awakeFromNib()
configureMenuButton()
configureTextField()
configureSeparator()
configureEditingMenu()
refreshState(state)
enableInteractionsWithPointer()
observeSafeAreaInsets()
}
private func observeSafeAreaInsets() {
safeAreaInsetsObservation = self.observe(\.safeAreaInsets, options: .new) { [weak self] (_, _) in
self?.updateOmniBarPadding()
}
}
private func enableInteractionsWithPointer() {
guard #available(iOS 13.4, *) else { return }
backButton.isPointerInteractionEnabled = true
forwardButton.isPointerInteractionEnabled = true
settingsButton.isPointerInteractionEnabled = true
cancelButton.isPointerInteractionEnabled = true
bookmarksButton.isPointerInteractionEnabled = true
shareButton.isPointerInteractionEnabled = true
menuButton.isPointerInteractionEnabled = true
refreshButton.isPointerInteractionEnabled = true
refreshButton.pointerStyleProvider = { button, effect, _ -> UIPointerStyle? in
return .init(effect: .lift(.init(view: button)))
}
}
private func configureMenuButton() {
menuButton.addSubview(menuButtonContent)
menuButton.isAccessibilityElement = true
menuButton.accessibilityTraits = .button
}
private func configureTextField() {
let theme = ThemeManager.shared.currentTheme
textField.attributedPlaceholder = NSAttributedString(string: UserText.searchDuckDuckGo,
attributes: [.foregroundColor: theme.searchBarTextPlaceholderColor])
textField.delegate = self
NotificationCenter.default.addObserver(self,
selector: #selector(textDidChange),
name: UITextField.textDidChangeNotification,
object: textField)
textField.textDragInteraction?.isEnabled = false
textField.onCopyAction = { field in
guard let range = field.selectedTextRange else { return }
UIPasteboard.general.string = field.text(in: range)
}
}
private func configureSeparator() {
separatorHeightConstraint.constant = 1.0 / UIScreen.main.scale
}
private func configureEditingMenu() {
let title = UserText.actionPasteAndGo
UIMenuController.shared.menuItems = [UIMenuItem(title: title, action: #selector(pasteAndGo))]
}
var textFieldBottomSpacing: CGFloat {
return (bounds.size.height - (searchContainer.frame.origin.y + searchContainer.frame.size.height)) / 2.0
}
@objc func textDidChange() {
let newQuery = textField.text ?? ""
omniDelegate?.onOmniQueryUpdated(newQuery)
if newQuery.isEmpty {
refreshState(state.onTextClearedState)
} else {
refreshState(state.onTextEnteredState)
}
}
@objc func pasteAndGo(sender: UIMenuItem) {
guard let pastedText = UIPasteboard.general.string else { return }
textField.text = pastedText
onQuerySubmitted()
}
func showSeparator() {
separatorView.isHidden = false
}
func hideSeparator() {
separatorView.isHidden = true
}
func startBrowsing() {
refreshState(state.onBrowsingStartedState)
}
func stopBrowsing() {
refreshState(state.onBrowsingStoppedState)
}
@IBAction func textFieldTapped() {
textField.becomeFirstResponder()
}
public func startLoadingAnimation(for url: URL?) {
trackersAnimator.startLoadingAnimation(in: self, for: url)
}
public func startTrackersAnimation(_ trackers: [DetectedTracker], collapsing: Bool) {
guard trackersAnimator.configure(self, toDisplay: trackers, shouldCollapse: collapsing), state.allowsTrackersAnimation else {
trackersAnimator.cancelAnimations(in: self)
return
}
trackersAnimator.startAnimating(in: self)
}
public func cancelAllAnimations() {
trackersAnimator.cancelAnimations(in: self)
}
public func completeAnimations() {
trackersAnimator.completeAnimations(in: self)
}
fileprivate func refreshState(_ newState: OmniBarState) {
if state.name != newState.name {
os_log("OmniBar entering %s from %s", log: generalLog, type: .debug, newState.name, state.name)
if newState.clearTextOnStart {
clear()
}
state = newState
trackersAnimator.cancelAnimations(in: self)
}
if state.showSiteRating {
searchFieldContainer.revealSiteRatingView()
} else {
searchFieldContainer.hideSiteRatingView()
}
setVisibility(searchLoupe, hidden: !state.showSearchLoupe)
setVisibility(clearButton, hidden: !state.showClear)
setVisibility(menuButton, hidden: !state.showMenu)
setVisibility(settingsButton, hidden: !state.showSettings)
setVisibility(cancelButton, hidden: !state.showCancel)
setVisibility(refreshButton, hidden: !state.showRefresh)
setVisibility(backButton, hidden: !state.showBackButton)
setVisibility(forwardButton, hidden: !state.showForwardButton)
setVisibility(bookmarksButton, hidden: !state.showBookmarksButton)
setVisibility(shareButton, hidden: !state.showShareButton)
searchContainerCenterConstraint.isActive = state.hasLargeWidth
searchContainerMaxWidthConstraint.isActive = state.hasLargeWidth
leftButtonsSpacingConstraint.constant = state.hasLargeWidth ? 24 : 0
rightButtonsSpacingConstraint.constant = state.hasLargeWidth ? 24 : 14
updateOmniBarPadding()
updateSearchBarBorder()
}
private func updateOmniBarPadding() {
omniBarLeadingConstraint.constant = (state.hasLargeWidth ? 24 : 8) + safeAreaInsets.left
omniBarTrailingConstraint.constant = (state.hasLargeWidth ? 24 : 14) + safeAreaInsets.right
}
private func updateSearchBarBorder() {
let theme = ThemeManager.shared.currentTheme
if state.showBackground {
editingBackground?.backgroundColor = theme.searchBarBackgroundColor
editingBackground?.borderColor = theme.searchBarBackgroundColor
} else {
editingBackground.borderWidth = 1.5
editingBackground.borderColor = theme.searchBarBorderColor
editingBackground.backgroundColor = UIColor.clear
}
}
/*
Superfluous check to overcome apple bug in stack view where setting value more than
once causes issues, related to http://www.openradar.me/22819594
Kill this method when radar is fixed - burn it with fire ;-)
*/
private func setVisibility(_ view: UIView, hidden: Bool) {
if view.isHidden != hidden {
view.isHidden = hidden
}
}
@discardableResult override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
@discardableResult override func resignFirstResponder() -> Bool {
return textField.resignFirstResponder()
}
func updateSiteRating(_ siteRating: SiteRating?, with storageCache: StorageCache?) {
siteRatingView.update(siteRating: siteRating, with: storageCache)
}
private func clear() {
textField.text = nil
omniDelegate?.onOmniQueryUpdated("")
}
func refreshText(forUrl url: URL?) {
if textField.isEditing {
return
}
guard let url = url else {
textField.text = nil
return
}
if let query = appUrls.searchQuery(fromUrl: url) {
textField.text = query
} else {
textField.attributedText = OmniBar.demphasisePath(forUrl: url)
}
}
public class func demphasisePath(forUrl url: URL) -> NSAttributedString? {
let s = url.absoluteString
let attributedString = NSMutableAttributedString(string: s)
guard let c = URLComponents(url: url, resolvingAgainstBaseURL: true) else {
return attributedString
}
let theme = ThemeManager.shared.currentTheme
if let pathStart = c.rangeOfPath?.lowerBound {
let urlEnd = s.endIndex
let pathRange = NSRange(pathStart ..< urlEnd, in: s)
attributedString.addAttribute(.foregroundColor, value: theme.searchBarTextDeemphasisColor, range: pathRange)
let domainRange = NSRange(s.startIndex ..< pathStart, in: s)
attributedString.addAttribute(.foregroundColor, value: theme.searchBarTextColor, range: domainRange)
} else {
let range = NSRange(s.startIndex ..< s.endIndex, in: s)
attributedString.addAttribute(.foregroundColor, value: theme.searchBarTextColor, range: range)
}
return attributedString
}
@IBAction func onTextEntered(_ sender: Any) {
onQuerySubmitted()
}
func onQuerySubmitted() {
if let suggestion = omniDelegate?.selectedSuggestion() {
omniDelegate?.onOmniSuggestionSelected(suggestion)
} else {
guard let query = textField.text?.trimWhitespace(), !query.isEmpty else {
return
}
resignFirstResponder()
if let url = query.punycodedUrl {
omniDelegate?.onOmniQuerySubmitted(url.absoluteString)
} else {
omniDelegate?.onOmniQuerySubmitted(query)
}
}
}
@IBAction func onClearButtonPressed(_ sender: Any) {
refreshState(state.onTextClearedState)
}
@IBAction func onSiteRatingPressed(_ sender: Any) {
omniDelegate?.onSiteRatingPressed()
}
@IBAction func onMenuButtonPressed(_ sender: UIButton) {
omniDelegate?.onMenuPressed()
}
@IBAction func onTrackersViewPressed(_ sender: Any) {
trackersAnimator.cancelAnimations(in: self)
textField.becomeFirstResponder()
}
@IBAction func onSettingsButtonPressed(_ sender: Any) {
omniDelegate?.onSettingsPressed()
}
@IBAction func onCancelPressed(_ sender: Any) {
omniDelegate?.onCancelPressed()
}
@IBAction func onRefreshPressed(_ sender: Any) {
Pixel.fire(pixel: .refreshPressed)
trackersAnimator.cancelAnimations(in: self)
omniDelegate?.onRefreshPressed()
}
@IBAction func onBackPressed(_ sender: Any) {
omniDelegate?.onBackPressed()
}
@IBAction func onForwardPressed(_ sender: Any) {
omniDelegate?.onForwardPressed()
}
@IBAction func onBookmarksPressed(_ sender: Any) {
Pixel.fire(pixel: .bookmarksButtonPressed,
withAdditionalParameters: [PixelParameters.originatedFromMenu: "0"])
omniDelegate?.onBookmarksPressed()
}
@IBAction func onSharePressed(_ sender: Any) {
omniDelegate?.onSharePressed()
}
func enterPhoneState() {
refreshState(state.onEnterPhoneState)
}
func enterPadState() {
refreshState(state.onEnterPadState)
}
override func layoutSubviews() {
super.layoutSubviews()
NotificationCenter.default.post(name: OmniBar.didLayoutNotification, object: self)
}
}
// swiftlint:enable type_body_length
extension OmniBar: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
omniDelegate?.onTextFieldWillBeginEditing(self)
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
DispatchQueue.main.async {
let highlightText = self.omniDelegate?.onTextFieldDidBeginEditing(self) ?? true
self.refreshState(self.state.onEditingStartedState)
if highlightText {
// Allow the cursor to move to the end before selecting all the text
// to avoid text not being selected properly
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
self.textField.selectAll(nil)
}
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
omniDelegate?.onEnterPressed()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
omniDelegate?.onDismissed()
refreshState(state.onEditingStoppedState)
}
}
extension OmniBar: Themable {
public func decorate(with theme: Theme) {
backgroundColor = theme.barBackgroundColor
tintColor = theme.barTintColor
configureTextField()
editingBackground?.backgroundColor = theme.searchBarBackgroundColor
editingBackground?.borderColor = theme.searchBarBackgroundColor
siteRatingView.circleIndicator.tintColor = theme.barTintColor
siteRatingContainer.tintColor = theme.barTintColor
siteRatingContainer.crossOutBackgroundColor = theme.searchBarBackgroundColor
searchStackContainer?.tintColor = theme.barTintColor
if let url = textField.text?.punycodedUrl {
textField.attributedText = OmniBar.demphasisePath(forUrl: url)
}
textField.textColor = theme.searchBarTextColor
textField.tintColor = theme.searchBarTextColor
textField.keyboardAppearance = theme.keyboardAppearance
clearButton.tintColor = theme.searchBarClearTextIconColor
searchLoupe.tintColor = theme.barTintColor
cancelButton.setTitleColor(theme.barTintColor, for: .normal)
updateSearchBarBorder()
}
}
extension OmniBar: UIGestureRecognizerDelegate {
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return !textField.isFirstResponder
}
}
// swiftlint:enable file_length
| 35.138493 | 133 | 0.665507 |
871af543aa36a3879760ee1dd954ff035e009510 | 410 | //
// report_my_wreckApp.swift
// report_my_wreck
//
// Created by ROBERT BRONSON on 10/21/21.
//
import SwiftUI
@main
struct report_my_wreckApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
| 19.52381 | 97 | 0.665854 |
160dd653d57f8c4a832c0358da3666984b45dcd7 | 1,568 | //
// WLStatusIndicatorView.swift
// p2p_wallet
//
// Created by Chung Tran on 18/11/2021.
//
import Foundation
import UIKit
class WLStatusIndicatorView: BEView {
enum State {
case loading, error, success
}
private let autoHide: Bool = true
private let label = UILabel(text: "loading...", textSize: 12, weight: .semibold, textColor: .white, numberOfLines: 0, textAlignment: .center)
override func commonInit() {
super.commonInit()
addSubview(label)
label.autoPinEdgesToSuperviewEdges(with: .init(x: 18, y: 8))
}
func setUp(state: State, text: String?) {
switch state {
case .loading:
backgroundColor = .ff9500
if autoHide { UIView.animate(withDuration: 0.3) { self.isHidden = false } }
case .error:
backgroundColor = .alert
UIView.animate(withDuration: 0.3) { self.isHidden = false }
if autoHide {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
UIView.animate(withDuration: 0.3) { self.isHidden = true }
}
}
case .success:
backgroundColor = .attentionGreen
if autoHide {
UIView.animate(withDuration: 0.3) { self.isHidden = false }
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
UIView.animate(withDuration: 0.3) { self.isHidden = true }
}
}
}
label.text = text
}
}
| 30.745098 | 145 | 0.559311 |
69a74cc33892f5c2571886ac5aa2919d76e6d3bc | 1,150 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSFileHandle : XCTestCase {
static var allTests : [(String, (TestNSFileHandle) -> () throws -> ())] {
return [
("test_pipe", test_pipe),
]
}
func test_pipe() {
let pipe = Pipe()
let inputs = ["Hello", "world", "🐶"]
for input in inputs {
let inputData = input.data(using: .utf8)!
// write onto pipe
pipe.fileHandleForWriting.write(inputData)
let outputData = pipe.fileHandleForReading.availableData
let output = String(data: outputData, encoding: .utf8)
XCTAssertEqual(output, input)
}
}
}
| 27.380952 | 78 | 0.628696 |
8919aa28200083fe0b21f9fbc245e5bc481020ab | 1,150 | //
// ProfileViewController.swift
// Instagram Parse
//
// Created by KaKin Chiu on 3/4/16.
// Copyright © 2016 KaKinChiu. All rights reserved.
//
import UIKit
import Parse
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "blueBackground-2.png")!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogout(sender: AnyObject) {
PFUser.logOut()
self.performSegueWithIdentifier("logoutSegue", sender: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 26.744186 | 106 | 0.676522 |
50262d6ed78452c9a2e2c5b101626bd6aba92120 | 20,097 | //
// ViewController.swift
// TGUIKit
//
// Created by keepcoder on 06/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Foundation
import SwiftSignalKitMac
class ControllerToasterView : View {
private weak var toaster:ControllerToaster?
private let textView:TextView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(textView)
textView.isSelectable = false
self.autoresizingMask = [.width]
self.border = [.Bottom]
updateLocalizationAndTheme()
}
override func updateLocalizationAndTheme() {
super.updateLocalizationAndTheme()
self.backgroundColor = presentation.colors.background
self.textView.backgroundColor = presentation.colors.background
}
func update(with toaster:ControllerToaster) {
self.toaster = toaster
}
override func layout() {
super.layout()
if let toaster = toaster {
toaster.text.measure(width: frame.width - 40)
textView.update(toaster.text)
textView.center()
}
self.setNeedsDisplayLayer()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public class ControllerToaster {
let text:TextViewLayout
var view:ControllerToasterView?
let disposable:MetaDisposable = MetaDisposable()
private let height:CGFloat
public init(text:NSAttributedString, height:CGFloat = 30.0) {
self.text = TextViewLayout(text, maximumNumberOfLines: 1, truncationType: .middle)
self.height = height
}
public init(text:String, height:CGFloat = 30.0) {
self.text = TextViewLayout(NSAttributedString.initialize(string: text, color: presentation.colors.text, font: .medium(.text)), maximumNumberOfLines: 1, truncationType: .middle)
self.height = height
}
func show(for controller:ViewController, timeout:Double, animated:Bool) {
assert(view == nil)
view = ControllerToasterView(frame: NSMakeRect(0, 0, controller.frame.width, height))
view?.update(with: self)
controller.addSubview(view!)
if animated {
view?.layer?.animatePosition(from: NSMakePoint(0, -height), to: NSZeroPoint, duration: 0.2)
}
let signal:Signal<Void,Void> = .single(Void()) |> delay(timeout, queue: Queue.mainQueue())
disposable.set(signal.start(next:{ [weak self] in
self?.hide(true)
}))
}
func hide(_ animated:Bool) {
if animated {
view?.layer?.animatePosition(from: NSZeroPoint, to: NSMakePoint(0, -height), duration: 0.2, removeOnCompletion:false, completion:{ [weak self] (completed) in
self?.view?.removeFromSuperview()
self?.view = nil
})
} else {
view?.removeFromSuperview()
view = nil
disposable.dispose()
}
}
deinit {
let view = self.view
view?.layer?.animatePosition(from: NSZeroPoint, to: NSMakePoint(0, -height), duration: 0.2, removeOnCompletion:false, completion:{ (completed) in
view?.removeFromSuperview()
})
disposable.dispose()
}
}
open class ViewController : NSObject {
fileprivate var _view:NSView?;
public var _frameRect:NSRect
private var toaster:ControllerToaster?
public var atomicSize:Atomic<NSSize> = Atomic(value:NSZeroSize)
weak open var navigationController:NavigationViewController? {
didSet {
if navigationController != oldValue {
updateNavigation(navigationController)
}
}
}
public var noticeResizeWhenLoaded: Bool = true
public var animationStyle:AnimationStyle = AnimationStyle(duration:0.4, function:kCAMediaTimingFunctionSpring)
public var bar:NavigationBarStyle = NavigationBarStyle(height:50)
public var leftBarView:BarView!
public var centerBarView:TitledBarView!
public var rightBarView:BarView!
public var popover:Popover?
open var modal:Modal?
private let _ready = Promise<Bool>()
open var ready: Promise<Bool> {
return self._ready
}
public var didSetReady:Bool = false
public let isKeyWindow:Promise<Bool> = Promise(false)
public var view:NSView {
get {
if(_view == nil) {
loadView();
}
return _view!;
}
}
public var backgroundColor: NSColor {
set {
self.view.background = newValue
}
get {
return self.view.background
}
}
open var enableBack:Bool {
return false
}
open func executeReturn() -> Void {
self.navigationController?.back()
}
open func updateNavigation(_ navigation:NavigationViewController?) {
}
open func navigationWillChangeController() {
}
open var sidebar:ViewController? {
return nil
}
open var sidebarWidth:CGFloat {
return 350
}
public private(set) var internalId:Int = 0;
public override init() {
_frameRect = NSZeroRect
self.internalId = Int(arc4random());
super.init()
}
public init(frame frameRect:NSRect) {
_frameRect = frameRect;
self.internalId = Int(arc4random());
}
open func readyOnce() -> Void {
if !didSetReady {
didSetReady = true
ready.set(.single(true))
}
}
open func updateLocalizationAndTheme() {
(view as? AppearanceViewProtocol)?.updateLocalizationAndTheme()
self.navigationController?.updateLocalizationAndTheme()
}
open func loadView() -> Void {
if(_view == nil) {
leftBarView = getLeftBarViewOnce()
centerBarView = getCenterBarViewOnce()
rightBarView = getRightBarViewOnce()
let vz = viewClass() as! NSView.Type
_view = vz.init(frame: _frameRect);
_view?.autoresizingMask = [.width,.height]
NotificationCenter.default.addObserver(self, selector: #selector(viewFrameChanged(_:)), name: NSView.frameDidChangeNotification, object: _view!)
_ = atomicSize.swap(_view!.frame.size)
}
}
open func navigationHeaderDidNoticeAnimation(_ current: CGFloat, _ previous: CGFloat, _ animated: Bool) -> ()->Void {
return {}
}
@available(OSX 10.12.2, *)
open func makeTouchBar() -> NSTouchBar? {
return window?.firstResponder?.makeTouchBar()
}
open func requestUpdateBackBar() {
if isLoaded(), let leftBarView = leftBarView as? BackNavigationBar {
leftBarView.requestUpdate()
}
self.leftBarView.style = navigationButtonStyle
}
open func requestUpdateCenterBar() {
setCenterTitle(defaultBarTitle)
}
open func dismiss() {
if navigationController?.controller == self {
navigationController?.back()
}
}
open func requestUpdateRightBar() {
(self.rightBarView as? TextButtonBarView)?.style = navigationButtonStyle
self.rightBarView.style = navigationButtonStyle
}
@objc func viewFrameChanged(_ notification:Notification) {
viewDidResized(frame.size)
}
open func viewDidResized(_ size:NSSize) {
_ = atomicSize.swap(size)
}
open func invokeNavigationBack() -> Bool {
return true
}
open func getLeftBarViewOnce() -> BarView {
return enableBack ? BackNavigationBar(self) : BarView(controller: self)
}
open var defaultBarTitle:String {
return localizedString(self.className)
}
open func getCenterBarViewOnce() -> TitledBarView {
return TitledBarView(controller: self, .initialize(string: defaultBarTitle, color: presentation.colors.text, font: .medium(.title)))
}
public func setCenterTitle(_ text:String) {
self.centerBarView.text = .initialize(string: text, color: presentation.colors.text, font: .medium(.title))
}
open func getRightBarViewOnce() -> BarView {
return BarView(controller: self)
}
open func viewClass() ->AnyClass {
return View.self
}
open func draggingItems(for pasteboard:NSPasteboard) -> [DragItem] {
return []
}
public func loadViewIfNeeded(_ frame:NSRect = NSZeroRect) -> Void {
guard _view != nil else {
if !NSIsEmptyRect(frame) {
_frameRect = frame
}
self.loadView()
return
}
}
open func viewDidLoad() -> Void {
if noticeResizeWhenLoaded {
viewDidResized(view.frame.size)
}
}
open func viewWillAppear(_ animated:Bool) -> Void {
}
deinit {
self.window?.removeObserver(for: self)
window?.removeAllHandlers(for: self)
NotificationCenter.default.removeObserver(self)
assertOnMainThread()
}
open func viewWillDisappear(_ animated:Bool) -> Void {
//assert(self.window != nil)
if canBecomeResponder {
self.window?.removeObserver(for: self)
}
if haveNextResponder {
self.window?.remove(object: self, for: .Tab)
}
NotificationCenter.default.removeObserver(self, name: NSWindow.didBecomeKeyNotification, object: window)
NotificationCenter.default.removeObserver(self, name: NSWindow.didResignKeyNotification, object: window)
isKeyWindow.set(.single(false))
}
public func isLoaded() -> Bool {
return _view != nil
}
open func viewDidAppear(_ animated:Bool) -> Void {
//assert(self.window != nil)
if haveNextResponder {
self.window?.set(handler: { [weak self] () -> KeyHandlerResult in
guard let `self` = self else {return .rejected}
self.window?.makeFirstResponder(self.nextResponder())
return .invoked
}, with: self, for: .Tab, priority: responderPriority)
}
if canBecomeResponder {
self.window?.set(responder: {[weak self] () -> NSResponder? in
return self?.firstResponder()
}, with: self, priority: responderPriority)
if let become = becomeFirstResponder(), become == true {
self.window?.applyResponderIfNeeded()
} else {
self.window?.makeFirstResponder(self.window?.firstResponder)
}
}
NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeKey), name: NSWindow.didBecomeKeyNotification, object: window)
NotificationCenter.default.addObserver(self, selector: #selector(windowDidResignKey), name: NSWindow.didResignKeyNotification, object: window)
if let window = window {
isKeyWindow.set(.single(window.isKeyWindow))
}
}
@objc open func windowDidBecomeKey() {
isKeyWindow.set(.single(true))
}
@objc open func windowDidResignKey() {
isKeyWindow.set(.single(false))
}
open var canBecomeResponder: Bool {
return true
}
open var removeAfterDisapper:Bool {
return false
}
open func escapeKeyAction() -> KeyHandlerResult {
return .rejected
}
open func backKeyAction() -> KeyHandlerResult {
if let event = NSApp.currentEvent, event.modifierFlags.contains(.shift), let textView = window?.firstResponder as? TextView, let layout = textView.layout, layout.selectedRange.range.max != 0 {
_ = layout.selectPrevChar()
textView.needsDisplay = true
return .invoked
}
return .rejected
}
open func nextKeyAction() -> KeyHandlerResult {
if let event = NSApp.currentEvent, event.modifierFlags.contains(.shift), let textView = window?.firstResponder as? TextView, let layout = textView.layout, layout.selectedRange.range.max != 0 {
_ = layout.selectNextChar()
textView.needsDisplay = true
return .invoked
}
return .invokeNext
}
open func returnKeyAction() -> KeyHandlerResult {
return .rejected
}
open func didRemovedFromStack() -> Void {
}
open func viewDidDisappear(_ animated:Bool) -> Void {
}
open func scrollup() {
}
open func becomeFirstResponder() -> Bool? {
return false
}
open var window:Window? {
return _view?.window as? Window
}
open func firstResponder() -> NSResponder? {
return nil
}
open func nextResponder() -> NSResponder? {
return nil
}
open var haveNextResponder: Bool {
return false
}
open var responderPriority:HandlerPriority {
return .low
}
public var frame:NSRect {
get {
return isLoaded() ? self.view.frame : _frameRect
}
set {
self.view.frame = newValue
}
}
public var bounds:NSRect {
return isLoaded() ? self.view.bounds : NSMakeRect(0, 0, _frameRect.width, _frameRect.height - bar.height)
}
public func addSubview(_ subview:NSView) -> Void {
self.view.addSubview(subview)
}
public func removeFromSuperview() ->Void {
self.view.removeFromSuperview()
}
open func backSettings() -> (String,CGImage?) {
return (localizedString("Navigation.back"),#imageLiteral(resourceName: "Icon_NavigationBack").precomposed(presentation.colors.blueIcon))
}
open var popoverClass:AnyClass {
return Popover.self
}
open func show(for control:Control, edge:NSRectEdge? = nil, inset:NSPoint = NSZeroPoint) -> Void {
if popover == nil {
self.popover = (self.popoverClass as! Popover.Type).init(controller: self)
}
if let popover = popover {
popover.show(for: control, edge: edge, inset: inset)
}
}
open func closePopover() -> Void {
self.popover?.hide()
}
open func invokeNavigation(action:NavigationModalAction) {
_ = (self.ready.get() |> take(1) |> deliverOnMainQueue).start(next: { (ready) in
action.close()
})
}
public func show(toaster:ControllerToaster, for delay:Double = 3.0, animated:Bool = true) {
assert(isLoaded())
if let toaster = self.toaster {
toaster.hide(true)
}
self.toaster = toaster
toaster.show(for: self, timeout: delay, animated: animated)
}
}
open class GenericViewController<T> : ViewController where T:NSView {
public var genericView:T {
return super.view as! T
}
open override func updateLocalizationAndTheme() {
super.updateLocalizationAndTheme()
genericView.background = presentation.colors.background
}
override open func loadView() -> Void {
if(_view == nil) {
leftBarView = getLeftBarViewOnce()
centerBarView = getCenterBarViewOnce()
rightBarView = getRightBarViewOnce()
_view = initializer()
_view?.autoresizingMask = [.width,.height]
NotificationCenter.default.addObserver(self, selector: #selector(viewFrameChanged(_:)), name: NSView.frameDidChangeNotification, object: _view!)
_ = atomicSize.swap(_view!.frame.size)
}
viewDidLoad()
}
open func initializer() -> T {
let vz = T.self as NSView.Type
//controller.bar.height
return vz.init(frame: NSMakeRect(_frameRect.minX, _frameRect.minY, _frameRect.width, _frameRect.height - bar.height)) as! T;
}
}
open class ModalViewController : ViewController {
open var closable:Bool {
return true
}
open var background:NSColor {
return NSColor(0x000000, 0.27)
}
open var isFullScreen:Bool {
return false
}
open var containerBackground: NSColor {
return presentation.colors.background
}
open var dynamicSize:Bool {
return false
}
open func measure(size:NSSize) {
}
open var modalInteractions:ModalInteractions? {
return nil
}
open override var responderPriority: HandlerPriority {
return .modal
}
open override func firstResponder() -> NSResponder? {
return self.view
}
open func close() {
modal?.close()
}
open var handleEvents:Bool {
return true
}
open var handleAllEvents: Bool {
return true
}
override open func loadView() -> Void {
if(_view == nil) {
_view = initializer()
_view?.autoresizingMask = [.width,.height]
NotificationCenter.default.addObserver(self, selector: #selector(viewFrameChanged(_:)), name: NSView.frameDidChangeNotification, object: _view!)
_ = atomicSize.swap(_view!.frame.size)
}
viewDidLoad()
}
open func initializer() -> NSView {
let vz = viewClass() as! NSView.Type
return vz.init(frame: NSMakeRect(_frameRect.minX, _frameRect.minY, _frameRect.width, _frameRect.height - bar.height));
}
}
public class ModalController : ModalViewController {
private let controller: NavigationViewController
init(_ controller: NavigationViewController) {
self.controller = controller
super.init(frame: controller._frameRect)
}
public override var handleEvents: Bool {
return true
}
public override func firstResponder() -> NSResponder? {
return controller.controller.firstResponder()
}
public override func returnKeyAction() -> KeyHandlerResult {
return controller.controller.returnKeyAction()
}
public override var haveNextResponder: Bool {
return true
}
public override func nextResponder() -> NSResponder? {
return controller.controller.nextResponder()
}
public override func viewDidLoad() {
super.viewDidLoad()
ready.set(controller.controller.ready.get())
}
public override func loadView() {
self._view = controller.view
NotificationCenter.default.addObserver(self, selector: #selector(viewFrameChanged(_:)), name: NSView.frameDidChangeNotification, object: _view!)
_ = atomicSize.swap(_view!.frame.size)
viewDidLoad()
}
}
open class TableModalViewController : ModalViewController {
override open var dynamicSize: Bool {
return true
}
override open func measure(size: NSSize) {
self.modal?.resize(with:NSMakeSize(genericView.frame.width, min(size.height - 70, genericView.listHeight)), animated: false)
}
override open func viewClass() -> AnyClass {
return TableView.self
}
public var genericView:TableView {
return self.view as! TableView
}
public func updateSize(_ animated: Bool) {
if let contentSize = self.modal?.window.contentView?.frame.size {
self.modal?.resize(with:NSMakeSize(genericView.frame.width, min(contentSize.height - 70, genericView.listHeight)), animated: animated)
}
}
}
| 28.587482 | 200 | 0.600985 |
edc4314070033232686b7ddeddd8eb35da8d1d93 | 286 | //
// CachedRecords+CoreDataClass.swift
// Navigate
//
// Created by Răzvan-Gabriel Geangu on 26/03/2018.
// Copyright © 2018 Răzvan-Gabriel Geangu. All rights reserved.
//
//
import Foundation
import CoreData
@objc(CachedRecords)
public class CachedRecords: NSManagedObject {
}
| 16.823529 | 64 | 0.741259 |
0183906add0ad6b5fc6e11c2629587f5b3b0e021 | 1,504 | //
// Grid.swift
//
// Created by CS193p Instructor on 4/8/20.
// Copyright © 2020 Stanford University. All rights reserved.
//
import SwiftUI
extension Grid where Item: Identifiable, ID == Item.ID {
init(_ items: [Item], viewForItem: @escaping (Item) -> ItemView) {
self.init(items, id: \Item.id, viewForItem: viewForItem)
}
}
struct Grid<Item, ID, ItemView>: View where ID: Hashable, ItemView: View {
private var items: [Item]
private var id: KeyPath<Item,ID>
private var viewForItem: (Item) -> ItemView
init(_ items: [Item], id: KeyPath<Item,ID>, viewForItem: @escaping (Item) -> ItemView) {
self.items = items
self.id = id
self.viewForItem = viewForItem
}
var body: some View {
GeometryReader { geometry in
body(for: GridLayout(itemCount: items.count, in: geometry.size))
}
}
private func body(for layout: GridLayout) -> some View {
return ForEach(items, id: id) { item in
body(for: item, in: layout)
}
}
private func body(for item: Item, in layout: GridLayout) -> some View {
let index = items.firstIndex(where: { item[keyPath: id] == $0[keyPath: id] } )
return Group {
if index != nil {
viewForItem(item)
.frame(width: layout.itemSize.width, height: layout.itemSize.height)
.position(layout.location(ofItemAt: index!))
}
}
}
}
| 29.490196 | 92 | 0.583777 |
e85b24900db6638ad52cba3f6ff4398ae1d6ba4e | 875 | //
// UserModel.swift
// Twitter_test
//
// Created by Marin Todorov on 6/18/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import Foundation
struct UserModel {
let idUser: Int64
let name: String
let username: String
let imageUrl: NSURL
static func createFromUserObject(obj: NSDictionary) -> UserModel {
let idUser = Int64((obj["id"] as! NSNumber).integerValue)
let username = obj["screen_name"] as! String
let name = obj["name"] as! String
let photoUrlString = (obj["profile_image_url"] as! String).stringByReplacingOccurrencesOfString("_normal.",
withString: "_bigger.", options: nil, range: nil)
let imageUrl = NSURL(string: photoUrlString)!
return UserModel(idUser: idUser, name: name, username: username, imageUrl: imageUrl)
}
} | 28.225806 | 115 | 0.644571 |
e68752b00bb5cf0e8e2c04e4b16aa17db9ac6bba | 8,203 | //
// SudokuView.swift
// SudokuSwift
//
// Created by Wayne Cochran on 2/13/16.
// Updated 2/22/18 by Paul Bonamy, for compatibility with Swift 4/iOS 11
// Copyright © 2018 Wayne Cochran & Paul Bonamy. All Rights Reserved
import UIKit
//
// Compute font size for target box.
// http://goo.gl/jPL9Yu
//
func fontSizeFor(_ string : NSString, fontName : String, targetSize : CGSize) -> CGFloat {
let testFontSize : CGFloat = 32
let font = UIFont(name: fontName, size: testFontSize)
let attr = [NSAttributedStringKey.font : font!]
let strSize = string.size(withAttributes: attr)
return testFontSize*min(targetSize.width/strSize.width, targetSize.height/strSize.height)
}
class SudokuView: UIView {
var selected = (row : -1, column : -1) // current selected cell in 9x9 puzzle (-1 => none)
//
// Allow user to "select" a non-fixed cell in the puzzle's 9x9 grid.
//
@IBAction func handleTap(_ sender : UIGestureRecognizer) {
let tapPoint = sender.location(in: self)
let gridSize = (self.bounds.width < self.bounds.height) ? self.bounds.width : self.bounds.height
let gridOrigin = CGPoint(x: (self.bounds.width - gridSize)/2, y: (self.bounds.height - gridSize)/2)
let d = gridSize/9
let col = Int((tapPoint.x - gridOrigin.x)/d)
let row = Int((tapPoint.y - gridOrigin.y)/d)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let puzzle = appDelegate.sudoku
if 0 <= col && col < 9 && 0 <= row && row < 9 { // if inside puzzle bounds
if (!puzzle.numberIsFixedAt(row: row, column: col)) { // and not a "fixed number"
if (row != selected.row || col != selected.column) { // and not already selected
selected.row = row // then select cell
selected.column = col
setNeedsDisplay() // request redraw ***** PuzzleView
}
}
}
}
//
// Draw sudoku board. The current puzzle state is stored in the "sudoku" property
// stored in the app delegate.
//
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
//
// Find largest square w/in bounds of view and use this to establish
// grid parameters.
//
let gridSize = (self.bounds.width < self.bounds.height) ? self.bounds.width : self.bounds.height
let gridOrigin = CGPoint(x: (self.bounds.width - gridSize)/2, y: (self.bounds.height - gridSize)/2)
let delta = gridSize/3
let d = delta/3
//
// Fill selected cell (is one is selected).
//
if selected.row >= 0 && selected.column >= 0 {
UIColor.lightGray.setFill()
let x = gridOrigin.x + CGFloat(selected.column)*d
let y = gridOrigin.y + CGFloat(selected.row)*d
context?.fill(CGRect(x: x, y: y, width: d, height: d))
}
//
// Stroke outer puzzle rectangle
//
context?.setLineWidth(6)
UIColor.black.setStroke()
context?.stroke(CGRect(x: gridOrigin.x, y: gridOrigin.y, width: gridSize, height: gridSize))
//
// Stroke major grid lines.
//
for i in 0 ..< 3 {
let x = gridOrigin.x + CGFloat(i)*delta
context?.move(to: CGPoint(x: x, y: gridOrigin.y))
context?.addLine(to: CGPoint(x: x, y: gridOrigin.y + gridSize))
context?.strokePath()
}
for i in 0 ..< 3 {
let y = gridOrigin.y + CGFloat(i)*delta
context?.move(to: CGPoint(x: gridOrigin.x, y: y))
context?.addLine(to: CGPoint(x: gridOrigin.x + gridSize, y: y))
context?.strokePath()
}
//
// Stroke minor grid lines.
//
context?.setLineWidth(3)
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let x = gridOrigin.x + CGFloat(i)*delta + CGFloat(j)*d
context?.move(to: CGPoint(x: x, y: gridOrigin.y))
context?.addLine(to: CGPoint(x: x, y: gridOrigin.y + gridSize))
let y = gridOrigin.y + CGFloat(i)*delta + CGFloat(j)*d
context?.move(to: CGPoint(x: gridOrigin.x, y: y))
context?.addLine(to: CGPoint(x: gridOrigin.x + gridSize, y: y))
context?.strokePath()
}
}
//
// Fetch Sudoku puzzle model object from app delegate.
//
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let puzzle = appDelegate.sudoku
//
// Fetch/compute font attribute information.
//
let fontName = "Helvetica"
let boldFontName = "Helvetica-Bold"
let pencilFontName = "Helvetica-Light"
let fontSize = fontSizeFor("0", fontName: boldFontName, targetSize: CGSize(width: d, height: d))
let boldFont = UIFont(name: boldFontName, size: fontSize)
let font = UIFont(name: fontName, size: fontSize)
let pencilFont = UIFont(name: pencilFontName, size: fontSize/3)
let fixedAttributes = [NSAttributedStringKey.font : boldFont!, NSAttributedStringKey.foregroundColor : UIColor.black]
let userAttributes = [NSAttributedStringKey.font : font!, NSAttributedStringKey.foregroundColor : UIColor.blue]
let conflictAttributes = [NSAttributedStringKey.font : font!, NSAttributedStringKey.foregroundColor : UIColor.red]
let pencilAttributes = [NSAttributedStringKey.font : pencilFont!, NSAttributedStringKey.foregroundColor : UIColor.black]
//
// Fill in puzzle numbers.
//
for row in 0 ..< 9 {
for col in 0 ..< 9 {
var number : Int
if puzzle.userEntry(row: row, column: col) != 0 {
number = puzzle.userEntry(row: row, column: col)
} else {
number = puzzle.numberAt(row: row, column: col)
}
if (number > 0) {
var attributes : [NSAttributedStringKey : NSObject]? = nil
if puzzle.numberIsFixedAt(row: row, column: col) {
attributes = fixedAttributes
} else if puzzle.isConflictingEntryAt(row: row, column: col) {
attributes = conflictAttributes
} else if puzzle.userEntry(row: row, column: col) != 0 {
attributes = userAttributes
}
let text = "\(number)" as NSString
let textSize = text.size(withAttributes: attributes)
let x = gridOrigin.x + CGFloat(col)*d + 0.5*(d - textSize.width)
let y = gridOrigin.y + CGFloat(row)*d + 0.5*(d - textSize.height)
let textRect = CGRect(x: x, y: y, width: textSize.width, height: textSize.height)
text.draw(in: textRect, withAttributes: attributes)
} else if puzzle.anyPencilSetAt(row: row, column: col) {
let s = d/3
for n in 1 ... 9 {
if puzzle.isSetPencil(n: n, row: row, column: col) {
let r = (n - 1) / 3
let c = (n - 1) % 3
let text : NSString = "\(n)" as NSString
let textSize = text.size(withAttributes: pencilAttributes)
let x = gridOrigin.x + CGFloat(col)*d + CGFloat(c)*s + 0.5*(s - textSize.width)
let y = gridOrigin.y + CGFloat(row)*d + CGFloat(r)*s + 0.5*(s - textSize.height)
let textRect = CGRect(x: x, y: y, width: textSize.width, height: textSize.height)
text.draw(in: textRect, withAttributes: pencilAttributes)
}
}
}
}
}
}
}
| 43.402116 | 128 | 0.538462 |
5d441e93db8d2eb6cf9ea04a82ae8994d7d4a7b8 | 2,786 | //
// UIScrollView+velocity.swift
// UIKit
//
// Created by flowing erik on 25.09.17.
// Copyright © 2017 flowkey. All rights reserved.
//
import func Foundation.sqrt
import func Foundation.log
private extension CGPoint {
var magnitude: CGFloat {
return sqrt(x * x + y * y)
}
}
extension UIScrollView {
func startDeceleratingIfNecessary() {
// Only animate if instantaneous velocity is large enough
// Otherwise we could animate after scrolling quickly, pausing for a few seconds, then letting go
let velocityIsLargeEnoughToDecelerate = (self.panGestureRecognizer.velocity(in: self).magnitude > 10)
let dampingFactor: CGFloat = 0.5 // hand-tuned
let nonBoundsCheckedScrollAnimationDistance = self.weightedAverageVelocity * dampingFactor // hand-tuned
let targetOffset = getBoundsCheckedContentOffset(contentOffset - nonBoundsCheckedScrollAnimationDistance)
let distanceToBoundsCheckedTarget = contentOffset - targetOffset
let willDecelerate = (velocityIsLargeEnoughToDecelerate && distanceToBoundsCheckedTarget.magnitude > 0.0)
delegate?.scrollViewDidEndDragging(self, willDecelerate: willDecelerate)
guard willDecelerate else { hideScrollIndicators(); return }
// https://ariya.io/2011/10/flick-list-with-its-momentum-scrolling-and-deceleration
// TODO: This value should be calculated from `self.decelerationRate` instead
// But actually we want to redo this function to avoid `UIView.animate` entirely,
// in which case we wouldn't need an animationTime at all.
let animationTimeConstant = 0.325 * dampingFactor
// This calculation is a weird approximation but it's close enough for now...
let animationTime = log(distanceToBoundsCheckedTarget.magnitude) * animationTimeConstant
UIView.animate(
withDuration: Double(animationTime),
options: [.beginFromCurrentState, .customEaseOut, .allowUserInteraction],
animations: {
self.isDecelerating = true
self.contentOffset = targetOffset
},
completion: { _ in
self.isDecelerating = false
}
)
}
func cancelDeceleratingIfNeccessary() {
if !isDecelerating { return }
// Get the presentation value from the current animation
setContentOffset(visibleContentOffset, animated: false)
cancelDecelerationAnimations()
isDecelerating = false
}
func cancelDecelerationAnimations() {
layer.removeAnimation(forKey: "bounds")
horizontalScrollIndicator.layer.removeAnimation(forKey: "position")
verticalScrollIndicator.layer.removeAnimation(forKey: "position")
}
}
| 39.8 | 113 | 0.694544 |
79740673faf5d44ca6e59ed5eb476aeb01b19cbe | 540 | //
// CoreTextLook.swift
// Look
//
// Created by wookyoung on 11/27/15.
// Copyright © 2015 factorcat. All rights reserved.
//
import CoreText
import UIKit
extension Look {
public convenience init(CTFont ctFont: CTFont) {
self.init()
if let font: UIFont = UIFont(name: CTFontCopyFullName(ctFont) as String, size: CTFontGetSize(ctFont)) {
let attrs = [NSFontAttributeName: font]
self.preview = .AttributedString(NSAttributedString(string: font.fontName, attributes:attrs))
}
}
} | 27 | 111 | 0.666667 |
9c3e3d322a702fc8443c1b2ef03eb090c9bc9fcc | 3,346 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Register for remote notifications
if #available(iOS 8.0, *) {
// [START register_for_notifications]
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
// [END register_for_notifications]
} else {
// Fallback
let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
application.registerForRemoteNotificationTypes(types)
}
FIRApp.configure()
// Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification),
name: kFIRInstanceIDTokenRefreshNotification, object: nil)
return true
}
// [START receive_message]
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%@", userInfo)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(notification: NSNotification) {
let refreshedToken = FIRInstanceID.instanceID().token()!
print("InstanceID token: \(refreshedToken)")
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
}
// [START disconnect_from_fcm]
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
}
| 33.79798 | 125 | 0.717872 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.