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
|
---|---|---|---|---|---|
1a9064f8431264d6c8593f62aada1530bf78aec4 | 1,200 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
extension AKComputedParameter {
/// This filter reiterates the input with an echo density determined by loop
/// time. The attenuation rate is independent and is determined by the
/// reverberation time (defined as the time in seconds for a signal to decay to
/// 1/1000, or 60dB down from its original amplitude). Output will begin to
/// appear immediately.
///
/// - Parameters:
/// - reverbDuration: The duration in seconds for a signal to decay to 1/1000, or 60dB down from
/// its original amplitude. (Default: 0.5, Minimum: 0, Maximum: 10)
/// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the delay time or
/// “echo density” of the reverberation. (Default: 0.1, Minimum: 0, Maximum: 1)
///
public func reverberateWithFlatFrequencyResponse(
reverbDuration: AKParameter = 0.5,
loopDuration: Double = 0.1
) -> AKOperation {
return AKOperation(module: "allpass", inputs: toMono(), reverbDuration, loopDuration)
}
}
| 50 | 119 | 0.664167 |
039c0c371f8d1a809cf6e8d3ae3b97ed79a61616 | 5,478 | //
// NSDate+Extension.swift
// Tasty
//
// Created by Vitaliy Kuzmenko on 17/10/14.
// http://github.com/vitkuzmenko
// Copyright (c) 2014 Vitaliy Kuz'menko. All rights reserved.
//
import Foundation
func NSDateTimeAgoLocalizedStrings(_ key: String) -> String {
let resourcePath: String?
if let frameworkBundle = Bundle(identifier: "com.kevinlawler.NSDateTimeAgo") {
// Load from Framework
resourcePath = frameworkBundle.resourcePath
} else {
// Load from Main Bundle
resourcePath = Bundle.main.resourcePath
}
if resourcePath == nil {
return ""
}
let path = URL(fileURLWithPath: resourcePath!).appendingPathComponent("NSDateTimeAgo.bundle")
guard let bundle = Bundle(url: path) else {
return ""
}
return NSLocalizedString(key, tableName: "NSDateTimeAgo", bundle: bundle, comment: "")
}
extension Date {
// shows 1 or two letter abbreviation for units.
// does not include 'ago' text ... just {value}{unit-abbreviation}
// does not include interim summary options such as 'Just now'
public var timeAgoSimple: String {
let components = self.dateComponents()
if components.year! > 0 {
return stringFromFormat("%%d%@yr", withValue: components.year!)
}
if components.month! > 0 {
return stringFromFormat("%%d%@mo", withValue: components.month!)
}
// TODO: localize for other calanders
if components.day! >= 7 {
let value = components.day!/7
return stringFromFormat("%%d%@w", withValue: value)
}
if components.day! > 0 {
return stringFromFormat("%%d%@d", withValue: components.day!)
}
if components.hour! > 0 {
return stringFromFormat("%%d%@h", withValue: components.hour!)
}
if components.minute! > 0 {
return stringFromFormat("%%d%@m", withValue: components.minute!)
}
if components.second! > 0 {
return stringFromFormat("%%d%@s", withValue: components.second! )
}
return ""
}
public var timeAgo: String {
let components = self.dateComponents()
if components.year! > 0 {
if components.year! < 2 {
return NSDateTimeAgoLocalizedStrings("Last year")
} else {
return stringFromFormat("%%d %@years ago", withValue: components.year!)
}
}
if components.month! > 0 {
if components.month! < 2 {
return NSDateTimeAgoLocalizedStrings("Last month")
} else {
return stringFromFormat("%%d %@months ago", withValue: components.month!)
}
}
// TODO: localize for other calanders
if components.day! >= 7 {
let week = components.day!/7
if week < 2 {
return NSDateTimeAgoLocalizedStrings("Last week")
} else {
return stringFromFormat("%%d %@weeks ago", withValue: week)
}
}
if components.day! > 0 {
if components.day! < 2 {
return NSDateTimeAgoLocalizedStrings("Yesterday")
} else {
return stringFromFormat("%%d %@days ago", withValue: components.day!)
}
}
if components.hour! > 0 {
if components.hour! < 2 {
return NSDateTimeAgoLocalizedStrings("An hour ago")
} else {
return stringFromFormat("%%d %@hours ago", withValue: components.hour!)
}
}
if components.minute! > 0 {
if components.minute! < 2 {
return NSDateTimeAgoLocalizedStrings("A minute ago")
} else {
return stringFromFormat("%%d %@minutes ago", withValue: components.minute!)
}
}
if components.second! > 0 {
if components.second! < 5 {
return NSDateTimeAgoLocalizedStrings("Just now")
} else {
return stringFromFormat("%%d %@seconds ago", withValue: components.second!)
}
}
return ""
}
fileprivate func dateComponents() -> DateComponents {
let calander = Calendar.current
return (calander as NSCalendar).components([.second, .minute, .hour, .day, .month, .year], from: self, to: Date(), options: [])
}
fileprivate func stringFromFormat(_ format: String, withValue value: Int) -> String {
let localeFormat = String(format: format, getLocaleFormatUnderscoresWithValue(Double(value)))
return String(format: NSDateTimeAgoLocalizedStrings(localeFormat), value)
}
fileprivate func getLocaleFormatUnderscoresWithValue(_ value: Double) -> String {
guard let localeCode = Locale.preferredLanguages.first else {
return ""
}
// Russian (ru) and Ukrainian (uk)
if localeCode == "ru" || localeCode == "uk" {
let XY = Int(floor(value)) % 100
let Y = Int(floor(value)) % 10
if Y == 0 || Y > 4 || (XY > 10 && XY < 15) {
return ""
}
if Y > 1 && Y < 5 && (XY < 10 || XY > 20) {
return "_"
}
if Y == 1 && XY != 11 {
return "__"
}
}
return ""
}
}
| 30.775281 | 135 | 0.546732 |
e967884b02775373005d7adcbf3b3492fc2afbf2 | 762 | //
// ChanellBarView.swift
// SweetIRC
//
// Created by Dan Stoian on 15.02.2022.
//
import SwiftUI
struct RoomBarView: View {
@StateObject var state: ChatState
var body: some View {
List {
DisclosureGroup {
ForEach(state.rooms, id: \.self) { room in
NavigationLink(destination: MessageView(room: state.roomOf(name: room.name)), label: {Text("\(room.name)")})
}
} label: {
Label("\(state.server.friendlyName)", systemImage: "server.rack")
}
}
}
}
struct ChanellBarView_Previews: PreviewProvider {
static var previews: some View {
RoomBarView(state: ChatState(server: servers[0], user: User()))
}
}
| 23.8125 | 128 | 0.564304 |
4805779feed69a82767549fc249461d0b30875cd | 537 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "Kumo",
platforms: [
.iOS(.v13),
.tvOS(.v13),
.macOS(.v10_15),
],
products: [
.library(name: "Kumo", targets: ["Kumo"]),
.library(name: "KumoCoding", targets: ["KumoCoding"])
],
targets: [
.target(name: "Kumo", dependencies: ["KumoCoding"]),
.target(name: "KumoCoding", dependencies: []),
.testTarget(name: "KumoTests", dependencies: ["Kumo", "KumoCoding"])
]
)
| 25.571429 | 76 | 0.553073 |
286b8e6e95535e703c2997493c75cf7a2c3293f1 | 5,494 | /// Copyright (c) 2018 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 UIKit
@IBDesignable public class Knob: UIControl {
/** Contains the minimum value of the receiver. */
public var minimumValue: Float = 0
/** Contains the maximum value of the receiver. */
public var maximumValue: Float = 1
/** Contains the receiver’s current value. */
public private (set) var value: Float = 0
/** Sets the receiver’s current value, allowing you to animate the change visually. */
public func setValue(_ newValue: Float, animated: Bool = false) {
value = min(maximumValue, max(minimumValue, newValue))
let angleRange = endAngle - startAngle
let valueRange = maximumValue - minimumValue
let angleValue = CGFloat(value - minimumValue) / CGFloat(valueRange) * angleRange + startAngle
renderer.setPointerAngle(angleValue, animated: animated)
}
/** Contains a Boolean value indicating whether changes
in the sliders value generate continuous update events. */
public var isContinuous = true
private let renderer = KnobRenderer()
/** Specifies the width in points of the knob control track. Defaults to 2 */
@IBInspectable public var lineWidth: CGFloat {
get { return renderer.lineWidth }
set { renderer.lineWidth = newValue }
}
/** Specifies the angle of the start of the knob control track. Defaults to -11π/8 */
public var startAngle: CGFloat {
get { return renderer.startAngle }
set { renderer.startAngle = newValue }
}
/** Specifies the end angle of the knob control track. Defaults to 3π/8 */
public var endAngle: CGFloat {
get { return renderer.endAngle }
set { renderer.endAngle = newValue }
}
/** Specifies the length in points of the pointer on the knob. Defaults to 6 */
@IBInspectable public var pointerLength: CGFloat {
get { return renderer.pointerLength }
set { renderer.pointerLength = newValue }
}
/** Specifies the color of the knob, including the pointer. Defaults to blue */
@IBInspectable public var color: UIColor {
get { return renderer.color }
set { renderer.color = newValue }
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public override func tintColorDidChange() {
renderer.color = tintColor
}
private func commonInit() {
renderer.updateBounds(bounds)
renderer.color = tintColor
renderer.setPointerAngle(renderer.startAngle)
layer.addSublayer(renderer.trackLayer)
layer.addSublayer(renderer.pointerLayer)
let gestureRecognizer = RotationGestureRecognizer(target: self, action: #selector(Knob.handleGesture(_:)))
addGestureRecognizer(gestureRecognizer)
}
@objc private func handleGesture(_ gesture: RotationGestureRecognizer) {
// 1
let midPointAngle = (2 * CGFloat(Double.pi) + startAngle - endAngle) / 2 + endAngle
// 2
var boundedAngle = gesture.touchAngle
if boundedAngle > midPointAngle {
boundedAngle -= 2 * CGFloat(Double.pi)
} else if boundedAngle < (midPointAngle - 2 * CGFloat(Double.pi)) {
boundedAngle -= 2 * CGFloat(Double.pi)
}
// 3
boundedAngle = min(endAngle, max(startAngle, boundedAngle))
// 4
let angleRange = endAngle - startAngle
let valueRange = maximumValue - minimumValue
let angleValue = Float(boundedAngle - startAngle) / Float(angleRange) * valueRange + minimumValue
// 5
setValue(angleValue)
if isContinuous {
sendActions(for: .valueChanged)
} else {
if gesture.state == .ended || gesture.state == .cancelled {
sendActions(for: .valueChanged)
}
}
}
}
extension Knob {
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
renderer.updateBounds(bounds)
}
}
| 35.908497 | 110 | 0.714598 |
905ef53339eff508440ec020c5943921958eb32c | 897 | //
// TRSegmentTests.swift
// TRSegmentTests
//
// Created by leotao on 2020/9/20.
//
import XCTest
@testable import TRSegment
class TRSegmentTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.382353 | 111 | 0.664437 |
6a62a0ef67776daf95cab9f285394600132dee46 | 632 | //
// FileItemDirectoryType.swift
// CoreFoundationKit
//
// Created by Manish on 23/10/21.
//
import Foundation
/// Parent directory of the local file
public enum FileItemDirectoryType {
case image
case document
case audio
case video
case unknown
/// Name of the local directory
var name: String {
switch self {
case .image:
return "Image"
case .document:
return "Document"
case .audio:
return "Audio"
case .video:
return "Video"
case .unknown:
return "Unknown"
}
}
}
| 18.057143 | 38 | 0.550633 |
9b7a84a1e4dd8b6c4032299a0346c9b6ba47c4dd | 463 | import Vapor
struct TokenIntrospectionAuthMiddleware: Middleware {
let resourceServerAuthenticator: ResourceServerAuthenticator
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
guard let password = request.auth.header?.basic else {
throw Abort.unauthorized
}
try resourceServerAuthenticator.authenticate(credentials: password)
return try next.respond(to: request)
}
}
| 27.235294 | 86 | 0.721382 |
388ed43726ac37263afbc191e0989dcd633df65c | 372 | //
// BasicProgressView.swift
// TemplateProject
//
// Created by Mansoor Ali on 24/10/2018.
// Copyright © 2018 Mansoor Ali. All rights reserved.
//
import UIKit
open class ProgressView: ErrorManagementView {
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 17.714286 | 54 | 0.712366 |
4a770d95a8b9b282ea0104dd84e39b99044ef370 | 178 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
[
testCase(WeTransferLinterTests.allTests)
]
}
#endif
| 17.8 | 52 | 0.606742 |
ff436686fcdf1691911e495f32ed8c3d9f96ada9 | 7,617 |
// Copyright (c) NagisaWorks asaday
// The MIT License (MIT)
import EzHTTP
import XCTest
class EzHTTPSampleTests: XCTestCase {
var host = "https://httpbin.org" // http or https
func findJSONString(_ json: NSObject?, path: String) -> String {
guard let json = json else { return "" }
var paths = path.components(separatedBy: "/")
let last = paths.removeLast()
guard var dst: [String: Any] = json as? [String: Any] else { return "" }
for p in paths {
guard let s = dst[p] as? [String: Any] else { return "" }
dst = s
}
return dst[last] as? String ?? ""
}
override func setUp() {
super.setUp()
HTTP.shared.escapeATS = true
}
override func tearDown() {
super.tearDown()
}
// func testPerformanceExample() {
// self.measureBlock { }
// }
func testGet() {
let expectation = self.expectation(description: "")
HTTP.get(host + "/get?a=b") { res in
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "args/a"), "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testGetURL() {
let expectation = self.expectation(description: "")
let url = URL(string: host + "/get?a=b")!
HTTP.get(url) { res in
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "args/a"), "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testGetParam() {
let expectation = self.expectation(description: "")
HTTP.get(host + "/get", params: ["a": "b"], headers: ["Aaa": "bbb"]) { res in
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "args/a"), "b")
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "headers/Aaa"), "bbb")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testGetinpath() {
let expectation = self.expectation(description: "")
HTTP.get(host + "/{zzz}", params: [HTTP.ParamMode.query.rawValue: ["a": "b"], HTTP.ParamMode.path.rawValue: ["zzz": "get"]]) { res in
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "args/a"), "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testGetRedirect() {
let expectation = self.expectation(description: "")
HTTP.get(host + "/redirect/3") { res in
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "url"), self.host + "/get")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testGetPNG() {
let expectation = self.expectation(description: "")
HTTP.get(host + "/image/png") { res in
XCTAssertNil(res.error)
let img = UIImage(data: res.dataValue)
XCTAssertNotNil(img)
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testCookie() {
let expectation = self.expectation(description: "")
HTTPCookieStorage.shared.removeCookies(since: Date(timeIntervalSince1970: 0))
let cv = UUID().uuidString
HTTP.get(host + "/cookies/set?k2=v2&k1=\(cv)") { res in
print(res.stringValue)
HTTP.get(self.host + "/get") { res in
print(res.stringValue)
var r: [String: String] = [:]
if let cookies = HTTPCookieStorage.shared.cookies {
for c in cookies {
if c.domain == "httpbin.org" { r[c.name] = c.value }
}
}
XCTAssertEqual(r["k1"], cv)
XCTAssertEqual(r["k2"], "v2")
expectation.fulfill()
}
}
waitForExpectations(timeout: 5, handler: nil)
}
func testPost() {
let expectation = self.expectation(description: "")
HTTP.request(.POST, host + "/post", params: ["a": "b"]) { res in
print(res.stringValue)
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "form/a"), "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testPostJSON() {
let expectation = self.expectation(description: "")
HTTP.request(.POST, host + "/post", params: [HTTP.ParamMode.json.rawValue: ["a": "b"]]) { res in
print(res.stringValue)
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "json/a"), "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testPostJSON2() {
let expectation = self.expectation(description: "")
HTTP.request(.POST, host + "/post", json: ["a": "b"]) { res in
print(res.stringValue)
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "json/a"), "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
// need json post check
// curl -X POST -H "Content-type: application/json" -d '{"k":"v"}' https://httpbin.org/post
func testPostMQ() {
let expectation = self.expectation(description: "")
HTTP.request(.POST, host + "/post", params: HTTP.makeParams(query: ["q": "p"], form: ["a": "b"])) { res in
print(res.stringValue)
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "form/a"), "b")
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "args/q"), "p")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testPostFile() {
let expectation = self.expectation(description: "")
let file = HTTP.MultipartFile(mime: "iage/png", filename: "name", data: "aaa".data(using: String.Encoding.utf8)!)
HTTP.request(.POST, host + "/post", params: ["a": "b", "c": file]) { res in
print(res.stringValue)
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "form/a"), "b")
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "files/c"), "aaa")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testGetRedirectHTTPS() {
let expectation = self.expectation(description: "")
// first call is HTTP,and eveolute to HTTPS by server redirect
HTTP.get(host + "/redirect-to?url=https%3A%2F%2Fhttpbin.org%2Fget%3Fa=b") { res in
XCTAssertNil(res.error)
XCTAssertEqual(self.findJSONString(res.jsonObject, path: "args/a"), "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
// func testChunk() {
// let expectation = self.expectation(description: "")
//
// HTTP.request(.GET, "http://www.httpwatch.com/httpgallery/chunked/chunkedimage.aspx") { res in
// // HTTP.request(.GET, host + "/stream-bytes/4096?chunk_size=256") { (res) in
// XCTAssertNil(res.error)
// expectation.fulfill()
// }
// waitForExpectations(timeout: 15, handler: nil)
// }
func testStatusError() {
let expectation = self.expectation(description: "")
HTTP.shared.illegalStatusCodeAsError = true
HTTP.request(.GET, host + "/xxxxxxxxx") { res in
XCTAssertNotNil(res.error)
XCTAssertEqual(res.error?.code, 404)
expectation.fulfill()
}
waitForExpectations(timeout: 15, handler: nil)
}
func testGetSync() {
let res = HTTP.getSync(host + "/get?a=b")
XCTAssertEqual(findJSONString(res.jsonObject, path: "args/a"), "b")
}
func testGetAndDecode() {
struct Result: Codable {
struct Args: Codable {
var a: String
var b: String
}
var origin: String
var url: String
var args: Args
}
let expectation = self.expectation(description: "")
HTTP.requestAndDecode(.GET, host + "/get", params: ["a": "b"]) { (result: Result?, response) in
XCTAssertNil(response.error)
XCTAssertEqual(result?.args.a, "b")
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
}
| 29.409266 | 135 | 0.664435 |
7989d8456755146b10e42a9aab796fe97f8ba0f4 | 2,538 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AudioKit
import XCTest
class VariableDelayTests: XCTestCase {
func testDefault() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = VariableDelay(input)
input.start()
let audio = engine.startTest(totalDuration: 5.0)
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testFeedback() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = VariableDelay(input, feedback: 0.95)
input.start()
let audio = engine.startTest(totalDuration: 5.0)
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testMaximum() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = VariableDelay(input, time: 0.02, feedback: 0.8, maximumTime: 0.02)
input.start()
let audio = engine.startTest(totalDuration: 5.0)
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testMaximumSurpassed() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = VariableDelay(input, time: 0.03, feedback: 0.8, maximumTime: 0.02)
input.start()
let audio = engine.startTest(totalDuration: 5.0)
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testParametersSetAfterInit() {
let engine = AudioEngine()
let input = Oscillator()
let effect = VariableDelay(input)
effect.time = 0.123_4
effect.feedback = 0.95
engine.output = effect
input.start()
let audio = engine.startTest(totalDuration: 5.0)
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testParametersSetOnInit() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = VariableDelay(input, time: 0.123_4, feedback: 0.95)
input.start()
let audio = engine.startTest(totalDuration: 5.0)
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testTime() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = VariableDelay(input, time: 0.123_4)
input.start()
let audio = engine.startTest(totalDuration: 5.0)
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
}
| 30.95122 | 100 | 0.613475 |
1631c08a3ec93b720d33a8ef658b28790503cc53 | 234 | //
// EventLogType.swift
//
//
// Created by Everaldlee Johnson on 10/25/20.
//
import Foundation
public enum EventLogType:String, Codable{
case Information = "Information"
case Debug = "Debug"
case Error = "Error"
}
| 14.625 | 46 | 0.666667 |
d631e0f01e5bbb272f03799b71ea3773b2790531 | 1,856 |
// Created by meghdad on 11/27/20.
import SwiftUI
import UIKit
struct SearchBarView : View {
@Binding var searchText : String
@Binding var isFocused : Bool
var body: some View {
ZStack {
Color.white
// HStack {
//
// Button(action: {
// print("settings click")
//// presenter.processIntents(intents: QuranHomeIntent.SettingsClicked.init())
// })
// {
// Image("ic_settings")
// .resizable()
// .frame(width: 24, height: 24, alignment: .center)
// }
//
// Spacer()
// }
// .padding(.top, 40)
// .fixedSize(horizontal: false, vertical: true)
//
HStack {
TextField("Type your search",text: $searchText, onEditingChanged: { isFocused in
print(isFocused ? "focused" : "unfocused")
self.isFocused = isFocused
})
// .border(Color.blue, width: 0)
.overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.white, lineWidth: 0))
.padding(.vertical, 10.0)
.padding(.horizontal, 20.0)
.font(.custom("Vazir", size: 16))
Image.ic_search
.resizable()
.frame(width: 24, height: 24, alignment: .center)
.padding(.trailing, 20)
}
}
.cornerRadius(15.0)
.fixedSize(horizontal: false, vertical: true)
}
}
struct SearchBarView_Previews: PreviewProvider {
static var previews: some View {
SearchBarView(searchText: .constant(""), isFocused: .constant(false))
}
}
| 28.553846 | 98 | 0.472522 |
d53b68eaa2935cf281ee646db93a4ff43d0ead1b | 3,411 | //
// OBTransaction5Basic.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Provides further details on an entry in the report. */
public struct OBTransaction5Basic: Codable {
public var accountId: AccountId
public var transactionId: TransactionId?
public var transactionReference: TransactionReference?
public var statementReference: [StatementReference]?
public var creditDebitIndicator: OBCreditDebitCode1
public var status: OBEntryStatus1Code
public var bookingDateTime: BookingDateTime
public var valueDateTime: ValueDateTime?
public var addressLine: AddressLine?
public var amount: OBActiveOrHistoricCurrencyAndAmount7
public var chargeAmount: OBActiveOrHistoricCurrencyAndAmount8?
public var currencyExchange: OBCurrencyExchange5?
public var bankTransactionCode: OBBankTransactionCodeStructure1?
public var proprietaryBankTransactionCode: ProprietaryBankTransactionCodeStructure1?
public var cardInstrument: OBTransactionCardInstrument1?
public var supplementaryData: OBSupplementaryData1?
public init(accountId: AccountId, transactionId: TransactionId?, transactionReference: TransactionReference?, statementReference: [StatementReference]?, creditDebitIndicator: OBCreditDebitCode1, status: OBEntryStatus1Code, bookingDateTime: BookingDateTime, valueDateTime: ValueDateTime?, addressLine: AddressLine?, amount: OBActiveOrHistoricCurrencyAndAmount7, chargeAmount: OBActiveOrHistoricCurrencyAndAmount8?, currencyExchange: OBCurrencyExchange5?, bankTransactionCode: OBBankTransactionCodeStructure1?, proprietaryBankTransactionCode: ProprietaryBankTransactionCodeStructure1?, cardInstrument: OBTransactionCardInstrument1?, supplementaryData: OBSupplementaryData1?) {
self.accountId = accountId
self.transactionId = transactionId
self.transactionReference = transactionReference
self.statementReference = statementReference
self.creditDebitIndicator = creditDebitIndicator
self.status = status
self.bookingDateTime = bookingDateTime
self.valueDateTime = valueDateTime
self.addressLine = addressLine
self.amount = amount
self.chargeAmount = chargeAmount
self.currencyExchange = currencyExchange
self.bankTransactionCode = bankTransactionCode
self.proprietaryBankTransactionCode = proprietaryBankTransactionCode
self.cardInstrument = cardInstrument
self.supplementaryData = supplementaryData
}
public enum CodingKeys: String, CodingKey {
case accountId = "AccountId"
case transactionId = "TransactionId"
case transactionReference = "TransactionReference"
case statementReference = "StatementReference"
case creditDebitIndicator = "CreditDebitIndicator"
case status = "Status"
case bookingDateTime = "BookingDateTime"
case valueDateTime = "ValueDateTime"
case addressLine = "AddressLine"
case amount = "Amount"
case chargeAmount = "ChargeAmount"
case currencyExchange = "CurrencyExchange"
case bankTransactionCode = "BankTransactionCode"
case proprietaryBankTransactionCode = "ProprietaryBankTransactionCode"
case cardInstrument = "CardInstrument"
case supplementaryData = "SupplementaryData"
}
}
| 46.726027 | 678 | 0.769276 |
39dd15794470bead2c9c1b793da47bee76feff77 | 10,883 | //
// ShaderEditorViewController.swift
// PathTracingTests
//
// Created by Palle Klewitz on 09.08.16.
// Copyright © 2016 - 2018 Palle Klewitz.
//
// 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 Cocoa
class ShaderEditorViewController: NSViewController
{
var shader: Shader = defaultShader
{
didSet
{
self.childViewControllers.flatMap{$0 as? ColorTextureChooserViewController}.forEach
{
$0.color = shader.color
$0.texture = shader.texture
}
}
}
}
class DefaultShaderEditorViewController: ShaderEditorViewController, ColorTextureChooserDelegate
{
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidAppear()
{
self.childViewControllers.flatMap{$0 as? ColorTextureChooserViewController}.forEach
{
$0.delegate = self
$0.color = shader.color
$0.texture = shader.texture
}
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange color: Color)
{
(shader as? DefaultShader)?.color = color
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange texture: Texture?)
{
(shader as? DefaultShader)?.texture = texture
}
}
class DiffuseShaderEditorViewController: ShaderEditorViewController, ColorTextureChooserDelegate
{
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidAppear()
{
self.childViewControllers.flatMap{$0 as? ColorTextureChooserViewController}.forEach
{
$0.delegate = self
$0.color = shader.color
$0.texture = shader.texture
}
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange color: Color)
{
(shader as? DiffuseShader)?.color = color
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange texture: Texture?)
{
(shader as? DiffuseShader)?.texture = texture
}
}
class EmissionShaderEditorViewController: ShaderEditorViewController, ColorTextureChooserDelegate, NSTextFieldDelegate
{
@IBOutlet weak var txtEmissionStrength: NSTextField!
override var shader: Shader
{
didSet
{
txtEmissionStrength.floatValue = (shader as? EmissionShader)?.strength ?? 1.0
}
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad()
{
super.viewDidLoad()
txtEmissionStrength.delegate = self
}
override func viewDidAppear()
{
self.childViewControllers.flatMap{$0 as? ColorTextureChooserViewController}.forEach
{
$0.delegate = self
$0.color = shader.color
$0.texture = shader.texture
}
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange color: Color)
{
(shader as? EmissionShader)?.color = color
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange texture: Texture?)
{
(shader as? EmissionShader)?.texture = texture
}
override func controlTextDidChange(_ obj: Notification)
{
(shader as? EmissionShader)?.strength = txtEmissionStrength.floatValue
}
}
class ReflectionShaderEditorViewController: ShaderEditorViewController, ColorTextureChooserDelegate, NSTextFieldDelegate
{
@IBOutlet weak var txtRoughness: NSTextField!
override var shader: Shader
{
didSet
{
txtRoughness.floatValue = (shader as? ReflectionShader)?.roughness ?? 0.0
}
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad()
{
super.viewDidLoad()
txtRoughness.delegate = self
txtRoughness.floatValue = (shader as? RefractionShader)?.roughness ?? 0.0
}
override func viewDidAppear()
{
self.childViewControllers.flatMap{$0 as? ColorTextureChooserViewController}.forEach
{
$0.delegate = self
$0.color = shader.color
$0.texture = shader.texture
}
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange color: Color)
{
(shader as? ReflectionShader)?.color = color
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange texture: Texture?)
{
(shader as? ReflectionShader)?.texture = texture
}
override func controlTextDidChange(_ obj: Notification)
{
(shader as? ReflectionShader)?.roughness = txtRoughness.floatValue
}
}
class RefractionShaderEditorViewController: ShaderEditorViewController, ColorTextureChooserDelegate, NSTextFieldDelegate
{
@IBOutlet weak var txtIndexOfRefraction: NSTextField!
@IBOutlet weak var txtRoughness: NSTextField!
@IBOutlet weak var cwAttenuationColor: NSColorWell!
@IBOutlet weak var txtAttenuationStrength: NSTextField!
override var shader: Shader
{
didSet
{
txtIndexOfRefraction.floatValue = (shader as? RefractionShader)?.indexOfRefraction ?? 1.0
txtRoughness.floatValue = (shader as? RefractionShader)?.roughness ?? 0.0
txtAttenuationStrength.floatValue = (shader as? RefractionShader)?.absorptionStrength ?? 0.0
if let attenuationColor = (shader as? RefractionShader)?.volumeColor
{
cwAttenuationColor.color = NSColor(calibratedRed: CGFloat(attenuationColor.red),
green: CGFloat(attenuationColor.green),
blue: CGFloat(attenuationColor.blue),
alpha: CGFloat(attenuationColor.alpha))
}
}
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad()
{
super.viewDidLoad()
txtIndexOfRefraction.delegate = self
txtRoughness.delegate = self
txtAttenuationStrength.delegate = self
txtIndexOfRefraction.floatValue = (shader as? RefractionShader)?.indexOfRefraction ?? 1.0
txtRoughness.floatValue = (shader as? RefractionShader)?.roughness ?? 0.0
}
override func viewDidAppear()
{
self.childViewControllers.flatMap{$0 as? ColorTextureChooserViewController}.forEach
{
$0.delegate = self
$0.color = shader.color
$0.texture = shader.texture
}
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange color: Color)
{
(shader as? RefractionShader)?.color = color
}
func colorTextureChooser(chooser: ColorTextureChooserViewController, didChange texture: Texture?)
{
(shader as? RefractionShader)?.texture = texture
}
override func controlTextDidChange(_ obj: Notification)
{
(shader as? RefractionShader)?.indexOfRefraction = txtIndexOfRefraction.floatValue
(shader as? RefractionShader)?.roughness = txtRoughness.floatValue
(shader as? RefractionShader)?.absorptionStrength = txtAttenuationStrength.floatValue
}
@IBAction func didChangeAttenuationColor(_ sender: AnyObject)
{
let color = cwAttenuationColor.color
let r = Float(color.redComponent)
let g = Float(color.greenComponent)
let b = Float(color.blueComponent)
let a = Float(color.alphaComponent)
guard let currentAttenuationColor = (shader as? RefractionShader)?.volumeColor else { return }
guard currentAttenuationColor.red != r ||
currentAttenuationColor.green != g ||
currentAttenuationColor.blue != b ||
currentAttenuationColor.alpha != a
else
{
return
}
(shader as? RefractionShader)?.volumeColor = Color(withRed: r, green: g, blue: b, alpha: a)
}
}
class SubsurfaceScatteringShaderViewController: ShaderEditorViewController, NSTextFieldDelegate
{
}
class AddShaderEditorViewController: ShaderEditorViewController, ShaderChooserDelegate
{
override func viewDidAppear()
{
self.childViewControllers.flatMap{$0 as? ShaderChooserViewController}.enumerated().forEach
{
$0.element.delegate = self
if $0.offset == 0
{
$0.element.shader = (self.shader as? AddShader)?.shader1 ?? $0.element.shader
}
else
{
$0.element.shader = (self.shader as? AddShader)?.shader2 ?? $0.element.shader
}
}
}
func shaderChooserDidChangeShader(chooser: ShaderChooserViewController)
{
guard let index = self.childViewControllers.index(of: chooser) else { return }
guard let addShader = (shader as? AddShader) else { return }
if index == 0
{
addShader.shader1 = chooser.shader
}
else
{
addShader.shader2 = chooser.shader
}
}
}
class MixShaderEditorViewController: ShaderEditorViewController, ShaderChooserDelegate, NSTextFieldDelegate
{
@IBOutlet weak var txtBalance: NSTextField!
override func viewDidAppear()
{
txtBalance.floatValue = (shader as? MixShader)?.balance ?? 0.0
txtBalance.delegate = self
self.childViewControllers.flatMap{$0 as? ShaderChooserViewController}.enumerated().forEach
{
$0.element.delegate = self
if $0.offset == 0
{
$0.element.shader = (self.shader as? MixShader)?.shader1 ?? $0.element.shader
}
else
{
$0.element.shader = (self.shader as? MixShader)?.shader2 ?? $0.element.shader
}
}
}
func shaderChooserDidChangeShader(chooser: ShaderChooserViewController)
{
guard let index = self.childViewControllers.index(of: chooser) else { return }
guard let mixShader = (shader as? MixShader) else { return }
if index == 0
{
mixShader.shader1 = chooser.shader
}
else
{
mixShader.shader2 = chooser.shader
}
}
override func controlTextDidChange(_ obj: Notification)
{
(shader as? MixShader)?.balance = txtBalance.floatValue
}
}
| 27.413098 | 120 | 0.742534 |
29b9488cf61e06a0818bb865312c9809b7ff2c08 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
case
var {
class B {
func b {
if true {
struct B {
class
case ,
| 17.071429 | 87 | 0.728033 |
d73b2c10e825a964758274b0aab802ad5cadc973 | 8,690 | //
// SVGPath.swift
// SVGPath
//
// Created by Tim Wood on 1/21/15.
// Edited by Rudrank Riyam on 9/18/19.
// Copyright (c) 2015 Tim Wood. All rights reserved.
//
import SwiftUI
// MARK: Path
public extension Path {
init(svgPath: String) {
self.init()
applyCommands(from: SVGPath(svgPath))
}
}
@available(iOS 13.0, *)
private extension Path {
mutating func applyCommands(from svgPath: SVGPath) {
for command in svgPath.commands {
switch command.type {
case .move:
move(to: command.point)
case .line:
addLine(to: command.point)
case .quadCurve: addQuadCurve(to: command.point, control: command.control1)
case .cubeCurve: addCurve(to: command.point, control1: command.control1, control2: command.control2)
case .close: closeSubpath()
}
}
}
}
// MARK: Enums
fileprivate enum Coordinates {
case absolute
case relative
}
// MARK: Class
public class SVGPath {
public var commands: [SVGCommand] = []
private var builder: SVGCommandBuilder = move
private var coords: Coordinates = .absolute
private var increment: Int = 2
private var numbers = ""
public init(_ string: String) {
for char in string {
switch char {
case "M": use(.absolute, 2, move)
case "m": use(.relative, 2, move)
case "L": use(.absolute, 2, line)
case "l": use(.relative, 2, line)
case "V": use(.absolute, 1, lineVertical)
case "v": use(.relative, 1, lineVertical)
case "H": use(.absolute, 1, lineHorizontal)
case "h": use(.relative, 1, lineHorizontal)
case "Q": use(.absolute, 4, quadBroken)
case "q": use(.relative, 4, quadBroken)
case "T": use(.absolute, 2, quadSmooth)
case "t": use(.relative, 2, quadSmooth)
case "C": use(.absolute, 6, cubeBroken)
case "c": use(.relative, 6, cubeBroken)
case "S": use(.absolute, 4, cubeSmooth)
case "s": use(.relative, 4, cubeSmooth)
case "Z": use(.absolute, 1, close)
case "z": use(.absolute, 1, close)
default: numbers.append(char)
}
}
finishLastCommand()
}
private func use(_ coords: Coordinates, _ increment: Int, _ builder: @escaping SVGCommandBuilder) {
finishLastCommand()
self.builder = builder
self.coords = coords
self.increment = increment
}
private func finishLastCommand() {
for command in take(SVGPath.parseNumbers(numbers), increment: increment, coords: coords, last: commands.last, callback: builder) {
commands.append(coords == .relative ? command.relative(to: commands.last) : command)
}
numbers = ""
}
}
// MARK: Numbers
private let numberSet = CharacterSet(charactersIn: "-.0123456789eE")
private let locale = Locale(identifier: "en_US")
public extension SVGPath {
class func parseNumbers(_ numbers: String) -> [CGFloat] {
var all:[String] = []
var curr = ""
var last = ""
for char in numbers.unicodeScalars {
let next = String(char)
if next == "-" && last != "" && last != "E" && last != "e" {
if curr.utf16.count > 0 {
all.append(curr)
}
curr = next
} else if numberSet.contains(UnicodeScalar(char.value)!) {
curr += next
} else if curr.utf16.count > 0 {
all.append(curr)
curr = ""
}
last = next
}
all.append(curr)
return all.map { CGFloat(truncating: NSDecimalNumber(string: $0, locale: locale)) }
}
}
// MARK: Commands
public struct SVGCommand {
public var point: CGPoint
public var control1: CGPoint
public var control2: CGPoint
public var type: Kind
public enum Kind {
case move
case line
case cubeCurve
case quadCurve
case close
}
public init() {
let point = CGPoint()
self.init(point, point, point, type: .close)
}
public init(_ x: CGFloat, _ y: CGFloat, type: Kind) {
let point = CGPoint(x: x, y: y)
self.init(point, point, point, type: type)
}
public init(_ cx: CGFloat, _ cy: CGFloat, _ x: CGFloat, _ y: CGFloat) {
let control = CGPoint(x: cx, y: cy)
self.init(control, control, CGPoint(x: x, y: y), type: .quadCurve)
}
public init(_ cx1: CGFloat, _ cy1: CGFloat, _ cx2: CGFloat, _ cy2: CGFloat, _ x: CGFloat, _ y: CGFloat) {
self.init(CGPoint(x: cx1, y: cy1), CGPoint(x: cx2, y: cy2), CGPoint(x: x, y: y), type: .cubeCurve)
}
public init(_ control1: CGPoint, _ control2: CGPoint, _ point: CGPoint, type: Kind) {
self.point = point
self.control1 = control1
self.control2 = control2
self.type = type
}
fileprivate func relative(to other: SVGCommand?) -> SVGCommand {
if let otherPoint = other?.point {
return SVGCommand(control1 + otherPoint, control2 + otherPoint, point + otherPoint, type: type)
}
return self
}
}
// MARK: CGPoint helpers
private func + (a: CGPoint, b: CGPoint) -> CGPoint {
return CGPoint(x: a.x + b.x, y: a.y + b.y)
}
private func - (a: CGPoint, b: CGPoint) -> CGPoint {
return CGPoint(x: a.x - b.x, y: a.y - b.y)
}
// MARK: Command Builders
private typealias SVGCommandBuilder = ([CGFloat], SVGCommand?, Coordinates) -> SVGCommand
private func take(_ numbers: [CGFloat], increment: Int, coords: Coordinates, last: SVGCommand?, callback: SVGCommandBuilder) -> [SVGCommand] {
var out: [SVGCommand] = []
var lastCommand:SVGCommand? = last
let count = (numbers.count / increment) * increment
var nums:[CGFloat] = [0, 0, 0, 0, 0, 0];
for i in stride(from: 0, to: count, by: increment) {
for j in 0 ..< increment {
nums[j] = numbers[i + j]
}
lastCommand = callback(nums, lastCommand, coords)
out.append(lastCommand!)
}
return out
}
// MARK: Mm - Move
private func move(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], type: .move)
}
// MARK: Ll - Line
private func line(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], type: .line)
}
// MARK: Vv - Vertical Line
private func lineVertical(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(coords == .absolute ? last?.point.x ?? 0 : 0, numbers[0], type: .line)
}
// MARK: Hh - Horizontal Line
private func lineHorizontal(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], coords == .absolute ? last?.point.y ?? 0 : 0, type: .line)
}
// MARK: Qq - Quadratic Curve To
private func quadBroken(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3])
}
// MARK: Tt - Smooth Quadratic Curve To
private func quadSmooth(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
var lastControl = last?.control1 ?? CGPoint()
let lastPoint = last?.point ?? CGPoint()
if (last?.type ?? .line) != .quadCurve {
lastControl = lastPoint
}
var control = lastPoint - lastControl
if coords == .absolute {
control = control + lastPoint
}
return SVGCommand(control.x, control.y, numbers[0], numbers[1])
}
// MARK: Cc - Cubic Curve To
private func cubeBroken(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5])
}
// MARK: Ss - Smooth Cubic Curve To
private func cubeSmooth(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
var lastControl = last?.control2 ?? CGPoint()
let lastPoint = last?.point ?? CGPoint()
if (last?.type ?? .line) != .cubeCurve {
lastControl = lastPoint
}
var control = lastPoint - lastControl
if coords == .absolute {
control = control + lastPoint
}
return SVGCommand(control.x, control.y, numbers[0], numbers[1], numbers[2], numbers[3])
}
// MARK: Zz - Close Path
private func close(_ numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand()
}
| 30.491228 | 142 | 0.599655 |
0801098d21966d2b7455b6b3cbd676f5b01a0d17 | 269 | //
// MCLiveViewManager.swift
// MCSXY
//
// Created by 瞄财网 on 2017/7/12.
// Copyright © 2017年 瞄财网. All rights reserved.
//
import UIKit
class MCLiveWillViewManager: ZB_TableViewManagerModel {
override func addSubViews() {
super.addSubViews()
}
}
| 16.8125 | 55 | 0.67658 |
8a5e9e82fcb66e5994a806c7d8cceaa678ebf765 | 1,773 | //
// Post.swift
// InstagramApp
//
// Created by WUSTL STS on 3/6/16.
// Copyright © 2016 jinseokpark. All rights reserved.
//
import UIKit
import Parse
class Post: NSObject {
/**
* Other methods
*/
/**
Method to add a user post to Parse (uploading image file)
- parameter image: Image that the user wants upload to parse
- parameter caption: Caption text input by the user
- parameter completion: Block to be executed after save operation is complete
*/
class func postUserImage(image: UIImage?, withCaption caption: String?, withCompletion completion: PFBooleanResultBlock?) {
// Create Parse object PFObject
let post = PFObject(className: "Post")
// Add relevant fields to the object
post["media"] = getPFFileFromImage(image) // PFFile column type
post["author"] = PFUser.currentUser() // Pointer column type that points to PFUser
post["caption"] = caption
post["likesCount"] = 0
post["commentsCount"] = 0
// Save object (following function will save the object in Parse asynchronously)
post.saveInBackgroundWithBlock(completion)
}
/**
Method to convert UIImage to PFFile
- parameter image: Image that the user wants to upload to parse
- returns: PFFile for the the data in the image
*/
class func getPFFileFromImage(image: UIImage?) -> PFFile? {
// check if image is not nil
if let image = image {
// get image data and check if that is not nil
if let imageData = UIImagePNGRepresentation(image) {
return PFFile(name: "image.png", data: imageData)
}
}
return nil
}
}
| 31.105263 | 127 | 0.620981 |
1c3e8f6d5da333bbcc6a4e895cf31f16b0a949b5 | 1,134 | import UIKit
extension UIBezierPath {
convenience init(polygonSides sides: Int, center: CGPoint, radius: CGFloat, offset: CGFloat = 0) {
self.init()
let points = UIBezierPath.polygonPoints(sides: sides, center: center, radius: radius, offset: offset)
if points.count > 1 {
move(to: points.first!)
for i in 1 ..< points.count {
addLine(to: points[i])
}
close()
}
}
static func polygonPoints(sides: Int, center: CGPoint, radius: CGFloat, offset: CGFloat = 0)
-> [CGPoint]
{
func toRadians(_ value: CGFloat) -> CGFloat {
return value / 180 * .pi
}
let angle = toRadians(360 / CGFloat(sides))
let cx = center.x
let cy = center.y
let r = radius
let o = toRadians(offset)
return (0 ..< sides).map { i in
let xpo = cx + r * sin(angle * CGFloat(i) - o)
let ypo = cy - r * cos(angle * CGFloat(i) - o)
return CGPoint(x: xpo, y: ypo)
}
}
}
| 27.658537 | 109 | 0.500882 |
ed59ab51769b82c38fe7bb8896ebeb3ee6127723 | 13,615 | //
// ColorCustomizable.swift
// Overlay
//
// Created by Justin Jia on 8/22/16.
// Copyright © 2016 TintPoint. MIT license.
//
import UIKit
/// A protocol that describes a view that its background color can be customized.
public protocol BackgroundColorCustomizable: ColorStyleRepresentable {
/// Customizes the background color.
/// - Parameter style: A `ColorStyle` that represents the background color.
func customizeBackgroundColor(using style: ColorStyle)
}
/// A protocol that describes a view that its badge color can be customized.
public protocol BadgeColorCustomizable: ColorStyleRepresentable {
/// Customizes the badge color.
/// - Parameter style: A `ColorStyle` that represents the badge color.
func customizeBadgeColor(using style: ColorStyle)
}
/// A protocol that describes a view that its bar tint color can be customized.
public protocol BarTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the bar tint color.
/// - Parameter style: A `ColorStyle` that represents the bar tint color.
func customizeBarTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its border color can be customized.
public protocol BorderColorCustomizable: ColorStyleRepresentable {
/// Customizes the border color.
/// - Parameter style: A `ColorStyle` that represents the border color.
func customizeBorderColor(using style: ColorStyle)
}
/// A protocol that describes a view that its color can be customized.
public protocol ColorCustomizable: ColorStyleRepresentable {
/// Customizes the color.
/// - Parameter style: A `ColorStyle` that represents the color.
func customizeColor(using style: ColorStyle)
}
/// A protocol that describes a view that its maximum track tint color can be customized.
public protocol MaximumTrackTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the maximum track tint color.
/// - Parameter style: A `ColorStyle` that represents the maximum track tint color.
func customizeMaximumTrackTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its minimum track tint color can be customized.
public protocol MinimumTrackTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the minimum track tint color.
/// - Parameter style: A `ColorStyle` that represents the minimum track tint color.
func customizeMinimumTrackTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its on tint color can be customized.
public protocol OnTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the on tint color.
/// - Parameter style: A `ColorStyle` that represents the on tint color.
func customizeOnTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its placeholder text color can be customized.
public protocol PlaceholderTextColorCustomizable: ColorStyleRepresentable {
/// Customizes the placeholder text color.
/// - Parameter style: A `ColorStyle` that represents the placeholder text color.
func customizePlaceholderTextColor(using style: ColorStyle)
}
/// A protocol that describes a view that its progress tint color can be customized.
public protocol ProgressTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the progress tint color.
/// - Parameter style: A `ColorStyle` that represents the progress tint color.
func customizeProgressTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its section index background color can be customized.
public protocol SectionIndexBackgroundColorCustomizable: ColorStyleRepresentable {
/// Customizes the section index background color.
/// - Parameter style: A `ColorStyle` that represents the section index background color.
func customizeSectionIndexBackgroundColor(using style: ColorStyle)
}
/// A protocol that describes a view that its section index color can be customized.
public protocol SectionIndexColorCustomizable: ColorStyleRepresentable {
/// Customizes the section index color.
/// - Parameter style: A `ColorStyle` that represents the section index color.
func customizeSectionIndexColor(using style: ColorStyle)
}
/// A protocol that describes a view that its section index tracking background color can be customized.
public protocol SectionIndexTrackingBackgroundColorCustomizable: ColorStyleRepresentable {
/// Customizes the section index tracking background color.
/// - Parameter style: A `ColorStyle` that represents the section index tracking background color.
func customizeSectionIndexTrackingBackgroundColor(using style: ColorStyle)
}
/// A protocol that describes a view that its separator color can be customized.
public protocol SeparatorColorCustomizable: ColorStyleRepresentable {
/// Customizes the separator color.
/// - Parameter style: A `ColorStyle` that represents the separator color.
func customizeSeparatorColor(using style: ColorStyle)
}
/// A protocol that describes a view that its shadow color can be customized.
public protocol ShadowColorCustomizable: ColorStyleRepresentable {
/// Customizes the shadow color.
/// - Parameter style: A `ColorStyle` that represents the shadow color.
func customizeShadowColor(using style: ColorStyle)
}
/// A protocol that describes a view that its text color can be customized.
public protocol TextColorCustomizable: ColorStyleRepresentable {
/// Customizes the text color.
/// - Parameter style: A `ColorStyle` that represents the text color.
func customizeTextColor(using style: ColorStyle)
}
/// A protocol that describes a view that its thumb tint color can be customized.
public protocol ThumbTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the thumb tint color.
/// - Parameter style: A `ColorStyle` that represents the thumb tint color.
func customizeThumbTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its tint color can be customized.
public protocol TintColorCustomizable: ColorStyleRepresentable {
/// Customizes the tint color.
/// - Parameter style: A `ColorStyle` that represents the tint color.
func customizeTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its title color can be customized.
public protocol TitleColorCustomizable: ColorStyleRepresentable {
/// Customizes the title color.
/// - Parameter style: A `ColorStyle` that represents the title color.
func customizeTitleColor(using style: ColorStyle)
}
/// A protocol that describes a view that its title shadow color can be customized.
public protocol TitleShadowColorCustomizable: ColorStyleRepresentable {
/// Customizes the title shadow color.
/// - Parameter style: A `ColorStyle` that represents the title shadow color.
func customizeTitleShadowColor(using style: ColorStyle)
}
/// A protocol that describes a view that its track tint color can be customized.
public protocol TrackTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the track tint color.
/// - Parameter style: A `ColorStyle` that represents the track tint color.
func customizeTrackTintColor(using style: ColorStyle)
}
/// A protocol that describes a view that its unselected item tint color can be customized.
public protocol UnselectedItemTintColorCustomizable: ColorStyleRepresentable {
/// Customizes the unselected item tint color.
/// - Parameter style: A `ColorStyle` that represents the unselected item tint color.
func customizeUnselectedItemTintColor(using style: ColorStyle)
}
extension UIView: TintColorCustomizable, BackgroundColorCustomizable, BorderColorCustomizable {
public func customizeTintColor(using style: ColorStyle) {
tintColor = selectedColor(from: style)
}
public func customizeBackgroundColor(using style: ColorStyle) {
backgroundColor = selectedColor(from: style)
}
public func customizeBorderColor(using style: ColorStyle) {
layer.borderColor = selectedColor(from: style).cgColor
}
}
extension UITableView: SeparatorColorCustomizable, SectionIndexColorCustomizable, SectionIndexBackgroundColorCustomizable, SectionIndexTrackingBackgroundColorCustomizable {
public func customizeSeparatorColor(using style: ColorStyle) {
separatorColor = selectedColor(from: style)
}
public func customizeSectionIndexColor(using style: ColorStyle) {
sectionIndexColor = selectedColor(from: style)
}
public func customizeSectionIndexBackgroundColor(using style: ColorStyle) {
sectionIndexBackgroundColor = selectedColor(from: style)
}
public func customizeSectionIndexTrackingBackgroundColor(using style: ColorStyle) {
sectionIndexTrackingBackgroundColor = selectedColor(from: style)
}
}
extension UIActivityIndicatorView: ColorCustomizable {
public func customizeColor(using style: ColorStyle) {
color = selectedColor(from: style)
}
}
extension UIProgressView: ProgressTintColorCustomizable, TrackTintColorCustomizable {
public func customizeProgressTintColor(using style: ColorStyle) {
progressTintColor = selectedColor(from: style)
}
public func customizeTrackTintColor(using style: ColorStyle) {
trackTintColor = selectedColor(from: style)
}
}
extension UIButton: TitleColorCustomizable, TitleShadowColorCustomizable {
public func customizeTitleColor(using style: ColorStyle) {
customizeColor(using: style, through: setTitleColor)
}
public func customizeTitleShadowColor(using style: ColorStyle) {
customizeColor(using: style, through: setTitleShadowColor)
}
}
extension UIDatePicker: TextColorCustomizable {
public func customizeTextColor(using style: ColorStyle) {
setValue(selectedColor(from: style), forKey: "textColor")
}
}
extension UISlider: MinimumTrackTintColorCustomizable, MaximumTrackTintColorCustomizable, ThumbTintColorCustomizable {
public func customizeMinimumTrackTintColor(using style: ColorStyle) {
minimumTrackTintColor = selectedColor(from: style)
}
public func customizeMaximumTrackTintColor(using style: ColorStyle) {
maximumTrackTintColor = selectedColor(from: style)
}
public func customizeThumbTintColor(using style: ColorStyle) {
thumbTintColor = selectedColor(from: style)
}
}
extension UISwitch: OnTintColorCustomizable, ThumbTintColorCustomizable {
public func customizeOnTintColor(using style: ColorStyle) {
onTintColor = selectedColor(from: style)
}
public func customizeThumbTintColor(using style: ColorStyle) {
thumbTintColor = selectedColor(from: style)
}
}
extension UILabel: TextColorCustomizable, ShadowColorCustomizable {
public func customizeTextColor(using style: ColorStyle) {
textColor = selectedColor(from: style)
if let styleGroup = style as? ColorStyleGroup {
highlightedTextColor = styleGroup.highlighted()
}
}
public func customizeShadowColor(using style: ColorStyle) {
shadowColor = selectedColor(from: style)
}
}
extension UITextField: TextColorCustomizable, PlaceholderTextColorCustomizable {
public func customizeTextColor(using style: ColorStyle) {
textColor = selectedColor(from: style)
}
public func customizePlaceholderTextColor(using style: ColorStyle) {
if let placeholder = placeholder {
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [.foregroundColor: selectedColor(from: style)])
} else {
attributedPlaceholder = nil
}
}
}
extension UITextView: TextColorCustomizable {
public func customizeTextColor(using style: ColorStyle) {
textColor = selectedColor(from: style)
}
}
extension UIBarButtonItem: TintColorCustomizable {
public func customizeTintColor(using style: ColorStyle) {
tintColor = selectedColor(from: style)
}
}
extension UINavigationBar: BarTintColorCustomizable, TitleColorCustomizable {
public func customizeBarTintColor(using style: ColorStyle) {
barTintColor = selectedColor(from: style)
}
public func customizeTitleColor(using style: ColorStyle) {
titleTextAttributes = titleTextAttributes ?? [:]
titleTextAttributes?[.foregroundColor] = selectedColor(from: style)
}
}
extension UISearchBar: BarTintColorCustomizable, TextColorCustomizable {
public func customizeBarTintColor(using style: ColorStyle) {
barTintColor = selectedColor(from: style)
}
public func customizeTextColor(using style: ColorStyle) {
setValue(selectedColor(from: style), forKeyPath: "searchField.textColor")
}
}
extension UIToolbar: BarTintColorCustomizable {
public func customizeBarTintColor(using style: ColorStyle) {
barTintColor = selectedColor(from: style)
}
}
extension UITabBar: BarTintColorCustomizable, UnselectedItemTintColorCustomizable {
public func customizeBarTintColor(using style: ColorStyle) {
barTintColor = selectedColor(from: style)
}
public func customizeUnselectedItemTintColor(using style: ColorStyle) {
if #available(iOS 10.0, *) {
unselectedItemTintColor = selectedColor(from: style)
}
}
}
extension UITabBarItem: BadgeColorCustomizable {
public func customizeBadgeColor(using style: ColorStyle) {
if #available(iOS 10.0, *) {
badgeColor = selectedColor(from: style)
}
}
}
| 40.281065 | 172 | 0.75549 |
18511cb32b976559a4fd8d37696e62c0a69d2bf6 | 944 | //
// ShadowView.swift
// Pros and Cons
//
// Created by Danial Zahid on 9/11/15.
// Copyright © 2015 Danial Zahid. All rights reserved.
//
import UIKit
class ShadowButton: UIButton {
//MARK: - IBInspectables
@IBInspectable var shadowColor : UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
@IBInspectable var shadowOffset : CGSize = CGSizeMake(3, 3)
@IBInspectable var shadowRadius : CGFloat = CGFloat(3.0)
@IBInspectable var shadowOpacity : Float = 1
//MARK: - View lifecycle
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
layer.shadowColor = shadowColor.CGColor
layer.shadowOffset = shadowOffset
layer.shadowRadius = shadowRadius
layer.shadowOpacity = shadowOpacity
}
}
| 26.222222 | 93 | 0.662076 |
230b310147dfd0c4848ecde2b55740d2c878bb72 | 237 | //
// AuthenticationToken.swift
// MVVMTemplate
//
// Created by Sergei Kultenko on 17/07/2018.
// Copyright © 2018 Sergei Kultenko. All rights reserved.
//
import Foundation
struct AuthenticationToken {
var token: String = ""
}
| 16.928571 | 58 | 0.708861 |
5bf99c3f2c67e6dcc0564fa10ca6433ad658d6b6 | 3,003 | //
// NestedDeserialization.swift
// jabTests
//
// Created by Dino on 21/03/2019.
//
@testable import jab
import XCTest
fileprivate struct Programmer: Codable, Equatable, JSONAPIIdentifiable {
static var jsonTypeIdentifier: String {
return "programmers"
}
var identifier: String
let name: String
let favouriteIDE: IDE
let isDarkModeUser: Int
}
fileprivate struct IDE: Codable, Equatable, JSONAPIIdentifiable {
static var jsonTypeIdentifier: String {
return "ides"
}
var identifier: String
let name: String
let language: Language
}
fileprivate struct Language: Codable, Equatable, JSONAPIIdentifiable {
static var jsonTypeIdentifier: String {
return "languages"
}
var identifier: String
let name: String
let compileTarget: CompileTarget
let isForGoodProgrammersOnly: Int
}
fileprivate struct CompileTarget: Codable, Equatable, JSONAPIIdentifiable {
static var jsonTypeIdentifier: String {
return "targets"
}
var identifier: String
let name: String
}
class NestedDeserialization: XCTestCase {
lazy var bundle = Bundle(for: type(of: self))
let jsonDecoder = { () -> JSONDecoder in
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
lazy var jsonApiDeserializer: JSONAPIDeserializer = JSONAPIDeserializer(decoder: jsonDecoder)
func testNestedResourceSucessfulyDecodes() {
guard let data = loadJsonData(forResource: "programmer_ide") else {
fatalError("Could not load JSON data")
}
XCTAssertNoThrow(try jsonApiDeserializer.deserialize(data: data) as Programmer)
}
func testNestedResourceSucessfulyLoadsProps() {
guard let data = loadJsonData(forResource: "programmer_ide") else {
fatalError("Could not load JSON data")
}
guard let programmer = try? jsonApiDeserializer.deserialize(data: data) as Programmer else {
XCTAssertTrue(false, "could not decode Programmer")
return
}
let expectedCompileTarget = CompileTarget(identifier: "1", name: "x86_64")
let expectedLanguage = Language(identifier: "1", name: "Swift", compileTarget: expectedCompileTarget, isForGoodProgrammersOnly: 1)
let expectedIDE = IDE(identifier: "1", name: "Xcode", language: expectedLanguage)
let expectedProgrammer = Programmer(identifier: "1", name: "Dino", favouriteIDE: expectedIDE, isDarkModeUser: 1)
XCTAssertEqual(programmer, expectedProgrammer)
}
private func loadJsonData(forResource resource: String) -> Data? {
guard let rootJsonURL = bundle.url(forResource: resource, withExtension: "json"),
let rootJson = try? String(contentsOf: rootJsonURL),
let data = rootJson.data(using: .utf8)
else { return nil }
return data
}
}
| 31.28125 | 138 | 0.671995 |
1c0408ae700bf4c80f544ddff91d037fa97d25d8 | 2,774 | //
// AKBitCrusherAudioUnit.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
import AVFoundation
public class AKBitCrusherAudioUnit: AKAudioUnitBase {
func setParameter(_ address: AKBitCrusherParameter, value: Double) {
setParameterWithAddress(AUParameterAddress(address.rawValue), value: Float(value))
}
func setParameterImmediately(_ address: AKBitCrusherParameter, value: Double) {
setParameterImmediatelyWithAddress(AUParameterAddress(address.rawValue), value: Float(value))
}
var bitDepth: Double = AKBitCrusher.defaultBitDepth {
didSet { setParameter(.bitDepth, value: bitDepth) }
}
var sampleRate: Double = AKBitCrusher.defaultSampleRate {
didSet { setParameter(.sampleRate, value: sampleRate) }
}
var rampDuration: Double = 0.0 {
didSet { setParameter(.rampDuration, value: rampDuration) }
}
public override func initDSP(withSampleRate sampleRate: Double,
channelCount count: AVAudioChannelCount) -> UnsafeMutableRawPointer! {
return createBitCrusherDSP(Int32(count), sampleRate)
}
public override init(componentDescription: AudioComponentDescription,
options: AudioComponentInstantiationOptions = []) throws {
try super.init(componentDescription: componentDescription, options: options)
let flags: AudioUnitParameterOptions = [.flag_IsReadable, .flag_IsWritable, .flag_CanRamp]
let bitDepth = AUParameterTree.createParameter(
withIdentifier: "bitDepth",
name: "Bit Depth",
address: AUParameterAddress(0),
min: Float(AKBitCrusher.bitDepthRange.lowerBound),
max: Float(AKBitCrusher.bitDepthRange.upperBound),
unit: .generic,
unitName: nil,
flags: flags,
valueStrings: nil,
dependentParameters: nil
)
let sampleRate = AUParameterTree.createParameter(
withIdentifier: "sampleRate",
name: "Sample Rate (Hz)",
address: AUParameterAddress(1),
min: Float(AKBitCrusher.sampleRateRange.lowerBound),
max: Float(AKBitCrusher.sampleRateRange.upperBound),
unit: .hertz,
unitName: nil,
flags: flags,
valueStrings: nil,
dependentParameters: nil
)
setParameterTree(AUParameterTree.createTree(withChildren: [bitDepth, sampleRate]))
bitDepth.value = Float(AKBitCrusher.defaultBitDepth)
sampleRate.value = Float(AKBitCrusher.defaultSampleRate)
}
public override var canProcessInPlace: Bool { return true }
}
| 36.025974 | 103 | 0.667267 |
8ad94a01ce8364a5fa09c080b40b8ad9bc73ea39 | 2,125 | //
// BookDetail.swift
// MyBooks
//
// Created by Stewart Lynch on 2020-08-28.
//
import SwiftUI
struct BookDetail: View {
@Binding var book:Book
var saveUpdates: (Bool) -> Void
@State var dirty = false
let ctHelp = CTHelpBuilder.getHelpItems(page: .bookDetail)
@State private var showCTHelp = false
var body: some View {
ZStack {
Form {
Section(header: Text("Title and Author")) {
TextField("Title", text: $book.title)
TextField("Author", text: $book.author)
}
Section(header: Text("Notes")) {
TextEditor(text: $book.notes)
.frame(height: 350)
}
}
.padding()
.onChange(of: book.notes) { _ in
self.dirty = true
}
.onChange(of: book.title) { _ in
dirty = true
}
.onChange(of: book.author) { _ in
dirty = true
}
.navigationTitle(book.title)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
withAnimation {
showCTHelp = true
}
}) {
Image(systemName: "questionmark.circle.fill")
.font(.title)
}
}
}
.onDisappear {
// Only save updates if there was an editing change
saveUpdates(dirty)
}
if showCTHelp {
ctHelp.showCTHelpScreens(isPresented: $showCTHelp, ctHelp: ctHelp)
}
}
}
}
struct BookDetail_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
BookDetail(book: .constant(Book(title: "My Great Book", author: "Stewart Lynch", notes: "Very Good Book")), saveUpdates: {_ in })
}
}
}
| 30.357143 | 141 | 0.468235 |
e9bc952a12d414a20faef157d300a59cf5db75df | 1,766 | // swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
import Foundation
// swiftlint:disable superfluous_disable_command file_length implicit_return
// MARK: - Strings
// swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:disable nesting type_body_length type_name vertical_whitespace_opening_braces
internal enum L10n {
/// Cancel
internal static let cancel = L10n.tr("Localizable", "Cancel")
/// Preferences
internal static let general = L10n.tr("Localizable", "General")
/// Remove
internal static let remove = L10n.tr("Localizable", "Remove")
/// Are you sure you want to remove the iCloud Account? All documents in the iCloud Account will be removed from this computer.
internal static let removeCloudKitMessage = L10n.tr("Localizable", "Remove_CloudKit_Message")
/// Remove iCloud Account
internal static let removeCloudKitTitle = L10n.tr("Localizable", "Remove_CloudKit_Title")
}
// swiftlint:enable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:enable nesting type_body_length type_name vertical_whitespace_opening_braces
// MARK: - Implementation Details
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
let format = BundleToken.bundle.localizedString(forKey: key, value: nil, table: table)
return String(format: format, locale: Locale.current, arguments: args)
}
}
// swiftlint:disable convenience_type
private final class BundleToken {
static let bundle: Bundle = {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: BundleToken.self)
#endif
}()
}
// swiftlint:enable convenience_type
| 37.574468 | 129 | 0.771234 |
e25c9153e85d8191de020e60f48cb9b74363c5bc | 770 | import ComposableArchitecture
public struct RemoteNotificationsClient {
public var isRegistered: () -> Bool
public var register: () -> Effect<Never, Never>
public var unregister: () -> Effect<Never, Never>
}
extension RemoteNotificationsClient {
public static let noop = Self(
isRegistered: { true },
register: { .none },
unregister: { .none }
)
}
#if DEBUG
import XCTestDynamicOverlay
extension RemoteNotificationsClient {
public static let failing = Self(
isRegistered: {
XCTFail("\(Self.self).isRegistered is unimplemented")
return false
},
register: { .failing("\(Self.self).register is unimplemented") },
unregister: { .failing("\(Self.self).unregister is unimplemented") }
)
}
#endif
| 24.83871 | 74 | 0.67013 |
143d2917a0b581b95b8178d6884b0aa37648e24c | 1,245 | //
// highlightedText.swift
// Code App
//
// @Alladinian
// https://stackoverflow.com/questions/59426359/swiftui-is-there-exist-modifier-to-highlight-substring-of-text-view
import SwiftUI
struct HighlightedText: View {
let text: String
let matching: String
let accentColor: Color
init(_ text: String, matching: String, accentColor: Color) {
self.text = text
self.matching = matching
self.accentColor = accentColor
}
var body: some View {
var subString = self.matching
if let range = text.range(of: self.matching, options: .caseInsensitive){
subString = String(text[range.lowerBound..<range.upperBound])
}
let tagged = text.replacingOccurrences(of: self.matching, with: "<SPLIT>>\(subString)<SPLIT>", options: .caseInsensitive)
let split = tagged.components(separatedBy: "<SPLIT>")
return split.reduce(Text("").foregroundColor(Color.init("T1"))) { (a, b) -> Text in
guard !b.hasPrefix(">") else {
return a.foregroundColor(Color.init("T1")) + Text(b.dropFirst()).foregroundColor(self.accentColor)
}
return a.foregroundColor(Color.init("T1")) + Text(b)
}
}
}
| 34.583333 | 129 | 0.631325 |
e89d8ac6707d75b6c12c8837b4fb34934ee4e428 | 3,446 | //
// APIClient.swift
// MarsRoverPhotoViewer
//
// Created by Kevin Galarza on 8/15/21.
//
import Foundation
final class APIClient {
// REQUEST AND REPLACE PLACEHOLDER API KEY WITH ISSUED KEY FROM "https://api.nasa.gov".
let apiKey = "DEMO_KEY"
static let shared = APIClient()
let baseURL = URL(string: "https://api.nasa.gov/mars-photos/api/v1/")!
let decoder = JSONDecoder()
enum APIError: Error {
case noResponse
case jsonDecodingError(error: Error)
case networkError(error: Error)
}
enum Endpoint {
case curiosityPhotos, opportunityPhotos, spiritPhotos
case curiosityManifest, opportunityManifest, spiritManifest
func path() -> String {
switch self {
case .curiosityManifest:
return "manifests/curiosity"
case .opportunityManifest:
return "manifests/opportunity"
case .spiritManifest:
return "manifests/spirit"
case .curiosityPhotos:
return "rovers/curiosity/photos"
case .opportunityPhotos:
return "rovers/opportunity/photos"
case .spiritPhotos:
return "rovers/spirit/photos"
}
}
}
func GET<T: Decodable>(endpoint: Endpoint,
params: [String: String]?,
completionHandler: @escaping (Result<T, APIError>) -> Void) {
let url = makeURL(endpoint: endpoint, params: params)
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {
DispatchQueue.main.async {
completionHandler(.failure(.noResponse))
}
return
}
guard error == nil else {
DispatchQueue.main.async {
completionHandler(.failure(.networkError(error: error!)))
}
return
}
do {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
self.decoder.dateDecodingStrategy = .formatted(dateFormatter)
let object = try self.decoder.decode(T.self, from: data)
DispatchQueue.main.async {
completionHandler(.success(object))
}
} catch let error {
DispatchQueue.main.async {
completionHandler(.failure(.jsonDecodingError(error: error)))
}
}
}
task.resume()
}
private func makeURL(endpoint: Endpoint, params: [String: String]?) -> URL {
let queryURL = baseURL.appendingPathComponent(endpoint.path())
var components = URLComponents(url: queryURL, resolvingAgainstBaseURL: true)!
components.queryItems = [
URLQueryItem(name: "api_key", value: apiKey)
]
if let params = params {
for (_, value) in params.enumerated() {
components.queryItems?.append(URLQueryItem(name: value.key, value: value.value))
}
}
return components.url!
}
}
| 32.509434 | 96 | 0.534823 |
18e0f4b3c226942d94692292b60595efec63a05e | 3,850 | //
// NCacheManager.swift
// Nests
//
// Created by liang on 2018/11/16.
// Copyright © 2018 TaiHao. All rights reserved.
//
import Foundation
import RealmSwift
open class NCacheManager {
let realm: Realm = {
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
path = path! + "/Cache"
if !FileManager.default.fileExists(atPath: path!) {
try! FileManager.default.createDirectory(at: URL(fileURLWithPath: path!), withIntermediateDirectories: true, attributes: nil)
}
path = path! + "/caches.realm"
print("path = \(path ?? "数据库路径错误") \n\n\n")
var config = Realm.Configuration(fileURL: URL(fileURLWithPath: path!))
return try! Realm(configuration: config)
}()
public static let manager = NCacheManager()
/// 新添加或者更新单条数据
///
/// - Parameter object: 写入的数据
public class func write(object: Object) {
let manager = NCacheManager.manager;
do {
try manager.realm.write {
manager.realm.add(object, update: true)
}
} catch let error {
print("写入数据库出错 \(error)")
}
}
/// 新添加或者更新一组数据
///
/// - Parameter objects: 待插入的一组数据
public class func write(objects: [Object]) {
let manager = NCacheManager.manager;
do {
try manager.realm.write {
manager.realm.add(objects, update: true)
}
} catch let error {
print("写入数据库出错 \(error)")
}
}
/// 删除单条数据
///
/// - Parameter object: 待删除数据
public class func delete(object: Object) {
NCacheManager.manager.realm.delete(object)
}
/// 删除一组数据
///
/// - Parameter objects: 一组数据
public class func delete(objects: [Object]) {
NCacheManager.manager.realm.delete(objects)
}
/// 删除一个类型所有数据
///
/// - Parameter ofType: 数据类型
public class func delete(ofType: Object.Type) {
let manager = NCacheManager.manager
manager.realm.delete(manager.realm.objects(ofType))
}
/// 根据主键读取一条数据
///
/// - Parameters:
/// - ofType: 数据类型 Object 及其子类
/// - key: 主键
/// - Returns: 返回的类型实例
public class func readObject<T: Object>(ofType: T.Type, key: String) -> T? {
return NCacheManager.manager.realm.object(ofType: ofType, forPrimaryKey: key)
}
/// 根据一个类型的所有数据
///
/// - Parameter ofType: 数据类型 Object 及其子类
/// - Returns: ofType 对应的类型的数组
public class func readObjects<T>(ofType: T.Type, sort: SortType = .DESC) -> [T]? where T: Object {
let results = NCacheManager.manager.realm.objects(ofType)
if sort == .ASC {
return results.map { (element) -> T in
return element
}
}
return results.map { (element) -> T in
return element
}.reversed()
}
/// 根据一个类型的最新指定数量的数据
///
/// - Parameters:
/// - ofType: 数据类型 Object 及其子类
/// - latestCount: 最新的数量
/// - Returns: 对应的类型的数组
public enum SortType {
case DESC
case ASC
}
public class func readObjects<T>(ofType: T.Type, latestCount: UInt, sort: SortType = .DESC) -> [T]? where T: Object {
let results = NCacheManager.manager.realm.objects(ofType)
var count = Int(latestCount)
if count > results.count {
count = results.count
}
let subResults = results[(results.count - count)..<results.count]
if sort == .ASC {
return subResults.map { (element) -> T in
return element
}
}
return subResults.map { (element) -> T in
return element
}.reversed()
}
}
| 28.10219 | 136 | 0.556364 |
bbf0f9b70a58cd2246df6a161aa7b1e67c17d227 | 29,286 | //
// Created by Tapash Majumder on 5/30/18.
// Copyright © 2018 Iterable. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
final class IterableAPIInternal: NSObject, PushTrackerProtocol, AuthProvider {
var apiKey: String
var email: String? {
get {
_email
} set {
setEmail(newValue)
}
}
var userId: String? {
get {
_userId
} set {
setUserId(newValue)
}
}
var deviceId: String {
if let value = localStorage.deviceId {
return value
} else {
let value = IterableUtil.generateUUID()
localStorage.deviceId = value
return value
}
}
var deviceMetadata: DeviceMetadata {
DeviceMetadata(deviceId: deviceId,
platform: JsonValue.iOS.jsonStringValue,
appPackageName: Bundle.main.appPackageName ?? "")
}
var lastPushPayload: [AnyHashable: Any]? {
localStorage.getPayload(currentDate: dateProvider.currentDate)
}
var attributionInfo: IterableAttributionInfo? {
get {
localStorage.getAttributionInfo(currentDate: dateProvider.currentDate)
} set {
let expiration = Calendar.current.date(byAdding: .hour,
value: Const.UserDefaults.attributionInfoExpiration,
to: dateProvider.currentDate)
localStorage.save(attributionInfo: newValue, withExpiration: expiration)
}
}
var auth: Auth {
Auth(userId: userId, email: email, authToken: authManager.getAuthToken())
}
lazy var inAppManager: IterableInternalInAppManagerProtocol = {
self.dependencyContainer.createInAppManager(config: self.config,
apiClient: self.apiClient,
deviceMetadata: deviceMetadata)
}()
lazy var authManager: IterableInternalAuthManagerProtocol = {
self.dependencyContainer.createAuthManager(config: self.config)
}()
// MARK: - SDK Functions
@discardableResult func handleUniversalLink(_ url: URL) -> Bool {
let (result, future) = deepLinkManager.handleUniversalLink(url, urlDelegate: config.urlDelegate, urlOpener: AppUrlOpener())
future.onSuccess { attributionInfo in
if let attributionInfo = attributionInfo {
self.attributionInfo = attributionInfo
}
}
return result
}
func setDeviceAttribute(name: String, value: String) {
deviceAttributes[name] = value
}
func removeDeviceAttribute(name: String) {
deviceAttributes.removeValue(forKey: name)
}
func setEmail(_ email: String?) {
ITBInfo()
if email == nil {
logoutPreviousUser()
return
}
if _email == email {
requestNewAuthToken()
return
}
logoutPreviousUser()
_email = email
_userId = nil
storeIdentifierData()
requestNewAuthToken()
loginNewUser()
}
func setUserId(_ userId: String?) {
ITBInfo()
if userId == nil {
logoutPreviousUser()
return
}
if _userId == userId {
requestNewAuthToken()
return
}
logoutPreviousUser()
_email = nil
_userId = userId
storeIdentifierData()
requestNewAuthToken()
loginNewUser()
}
func logoutUser() {
logoutPreviousUser()
}
// MARK: - API Request Calls
@discardableResult
func register(token: Data,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
guard let appName = pushIntegrationName else {
let errorMessage = "Not registering device token - appName must not be nil"
ITBError(errorMessage)
onFailure?(errorMessage, nil)
return SendRequestError.createErroredFuture(reason: errorMessage)
}
hexToken = token.hexString()
let registerTokenInfo = RegisterTokenInfo(hexToken: token.hexString(),
appName: appName,
pushServicePlatform: config.pushPlatform,
apnsType: dependencyContainer.apnsTypeChecker.apnsType,
deviceId: deviceId,
deviceAttributes: deviceAttributes,
sdkVersion: localStorage.sdkVersion)
return requestHandler.register(registerTokenInfo: registerTokenInfo,
notificationStateProvider: notificationStateProvider,
onSuccess: onSuccess,
onFailure: onFailure)
}
@discardableResult
func disableDeviceForCurrentUser(withOnSuccess onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
guard let hexToken = hexToken else {
let errorMessage = "no token present"
onFailure?(errorMessage, nil)
return SendRequestError.createErroredFuture(reason: errorMessage)
}
guard userId != nil || email != nil else {
let errorMessage = "either userId or email must be present"
onFailure?(errorMessage, nil)
return SendRequestError.createErroredFuture(reason: errorMessage)
}
return requestHandler.disableDeviceForCurrentUser(hexToken: hexToken, withOnSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func disableDeviceForAllUsers(withOnSuccess onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
guard let hexToken = hexToken else {
let errorMessage = "no token present"
onFailure?(errorMessage, nil)
return SendRequestError.createErroredFuture(reason: errorMessage)
}
return requestHandler.disableDeviceForAllUsers(hexToken: hexToken, withOnSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func updateUser(_ dataFields: [AnyHashable: Any],
mergeNestedObjects: Bool,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.updateUser(dataFields, mergeNestedObjects: mergeNestedObjects, onSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func updateEmail(_ newEmail: String,
withToken token: String? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.updateEmail(newEmail, onSuccess: nil, onFailure: nil).onSuccess { json in
if self.email != nil {
self.setEmail(newEmail)
}
onSuccess?(json)
}.onError { error in
onFailure?(error.reason, error.data)
}
}
@discardableResult
func trackPurchase(_ total: NSNumber,
items: [CommerceItem],
dataFields: [AnyHashable: Any]? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.trackPurchase(total, items: items, dataFields: dataFields, onSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func trackPushOpen(_ userInfo: [AnyHashable: Any],
dataFields: [AnyHashable: Any]? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
save(pushPayload: userInfo)
if let metadata = IterablePushNotificationMetadata.metadata(fromLaunchOptions: userInfo), metadata.isRealCampaignNotification() {
return trackPushOpen(metadata.campaignId,
templateId: metadata.templateId,
messageId: metadata.messageId,
appAlreadyRunning: false,
dataFields: dataFields,
onSuccess: onSuccess,
onFailure: onFailure)
} else {
return SendRequestError.createErroredFuture(reason: "Not tracking push open - payload is not an Iterable notification, or is a test/proof/ghost push")
}
}
@discardableResult
func trackPushOpen(_ campaignId: NSNumber,
templateId: NSNumber?,
messageId: String,
appAlreadyRunning: Bool,
dataFields: [AnyHashable: Any]? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.trackPushOpen(campaignId,
templateId: templateId,
messageId: messageId,
appAlreadyRunning: appAlreadyRunning,
dataFields: dataFields,
onSuccess: onSuccess,
onFailure: onFailure)
}
@discardableResult
func track(_ eventName: String,
dataFields: [AnyHashable: Any]? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.track(event: eventName, dataFields: dataFields, onSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func updateSubscriptions(_ emailListIds: [NSNumber]?,
unsubscribedChannelIds: [NSNumber]?,
unsubscribedMessageTypeIds: [NSNumber]?,
subscribedMessageTypeIds: [NSNumber]?,
campaignId: NSNumber?,
templateId: NSNumber?,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
let updateSubscriptionsInfo = UpdateSubscriptionsInfo(emailListIds: emailListIds,
unsubscribedChannelIds: unsubscribedChannelIds,
unsubscribedMessageTypeIds: unsubscribedMessageTypeIds,
subscribedMessageTypeIds: subscribedMessageTypeIds,
campaignId: campaignId,
templateId: templateId)
return requestHandler.updateSubscriptions(info: updateSubscriptionsInfo, onSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func trackInAppOpen(_ message: IterableInAppMessage,
location: InAppLocation,
inboxSessionId: String? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.trackInAppOpen(message,
location: location,
inboxSessionId: inboxSessionId,
onSuccess: onSuccess,
onFailure: onFailure)
}
@discardableResult
func trackInAppClick(_ message: IterableInAppMessage,
location: InAppLocation = .inApp,
inboxSessionId: String? = nil,
clickedUrl: String,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.trackInAppClick(message, location: location,
inboxSessionId: inboxSessionId,
clickedUrl: clickedUrl,
onSuccess: onSuccess,
onFailure: onFailure)
}
@discardableResult
func trackInAppClose(_ message: IterableInAppMessage,
location: InAppLocation = .inApp,
inboxSessionId: String? = nil,
source: InAppCloseSource? = nil,
clickedUrl: String? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.trackInAppClose(message,
location: location,
inboxSessionId: inboxSessionId,
source: source,
clickedUrl: clickedUrl,
onSuccess: onSuccess,
onFailure: onFailure)
}
@discardableResult
func track(inboxSession: IterableInboxSession,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.track(inboxSession: inboxSession, onSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func track(inAppDelivery message: IterableInAppMessage,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.track(inAppDelivery: message, onSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func inAppConsume(_ messageId: String,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.inAppConsume(messageId, onSuccess: onSuccess, onFailure: onFailure)
}
@discardableResult
func inAppConsume(message: IterableInAppMessage,
location: InAppLocation = .inApp,
source: InAppDeleteSource? = nil,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.inAppConsume(message: message,
location: location,
source: source,
onSuccess: onSuccess,
onFailure: onFailure)
}
// MARK: - Private/Internal
private var config: IterableConfig
private var apiEndPoint: String
private var linksEndPoint: String
// Following are needed for handling pending notification and deep link.
static var pendingNotificationResponse: NotificationResponseProtocol?
static var pendingUniversalLink: URL?
private let dateProvider: DateProviderProtocol
private let inAppDisplayer: InAppDisplayerProtocol
private var notificationStateProvider: NotificationStateProviderProtocol
private var localStorage: LocalStorageProtocol
var networkSession: NetworkSessionProtocol
private var urlOpener: UrlOpenerProtocol
private var dependencyContainer: DependencyContainerProtocol
private var deepLinkManager: IterableDeepLinkManager
private var _email: String?
private var _userId: String?
// the hex representation of this device token
private var hexToken: String?
private var launchOptions: [UIApplication.LaunchOptionsKey: Any]?
lazy var apiClient: ApiClientProtocol = {
ApiClient(apiKey: apiKey,
authProvider: self,
endPoint: apiEndPoint,
networkSession: networkSession,
deviceMetadata: deviceMetadata)
}()
private lazy var requestHandler: RequestHandlerProtocol = {
dependencyContainer.createRequestHandler(apiKey: apiKey,
config: config,
endPoint: apiEndPoint,
authProvider: self,
authManager: authManager,
deviceMetadata: deviceMetadata)
}()
private var deviceAttributes = [String: String]()
private var pushIntegrationName: String? {
if let pushIntegrationName = config.pushIntegrationName, let sandboxPushIntegrationName = config.sandboxPushIntegrationName {
switch config.pushPlatform {
case .production:
return pushIntegrationName
case .sandbox:
return sandboxPushIntegrationName
case .auto:
return dependencyContainer.apnsTypeChecker.apnsType == .sandbox ? sandboxPushIntegrationName : pushIntegrationName
}
} else if let pushIntegrationName = config.pushIntegrationName {
return pushIntegrationName
} else {
return Bundle.main.appPackageName
}
}
private func isEitherUserIdOrEmailSet() -> Bool {
IterableUtil.isNotNullOrEmpty(string: _email) || IterableUtil.isNotNullOrEmpty(string: _userId)
}
private func requestNewAuthToken() {
authManager.requestNewAuthToken(hasFailedPriorAuth: false, onSuccess: { [weak self] authToken in
_ = self?.inAppManager.scheduleSync()
})
}
private func logoutPreviousUser() {
ITBInfo()
guard isEitherUserIdOrEmailSet() else {
return
}
if config.autoPushRegistration {
disableDeviceForCurrentUser()
}
_email = nil
_userId = nil
storeIdentifierData()
authManager.logoutUser()
_ = inAppManager.reset()
try? requestHandler.handleLogout()
}
private func loginNewUser() {
ITBInfo()
guard isEitherUserIdOrEmailSet() else {
return
}
if config.autoPushRegistration {
notificationStateProvider.registerForRemoteNotifications()
}
_ = inAppManager.scheduleSync()
}
private func storeIdentifierData() {
localStorage.email = _email
localStorage.userId = _userId
}
private func retrieveIdentifierData() {
_email = localStorage.email
_userId = localStorage.userId
}
private func save(pushPayload payload: [AnyHashable: Any]) {
let expiration = Calendar.current.date(byAdding: .hour,
value: Const.UserDefaults.payloadExpiration,
to: dateProvider.currentDate)
localStorage.save(payload: payload, withExpiration: expiration)
if let metadata = IterablePushNotificationMetadata.metadata(fromLaunchOptions: payload) {
if let templateId = metadata.templateId {
attributionInfo = IterableAttributionInfo(campaignId: metadata.campaignId, templateId: templateId, messageId: metadata.messageId)
}
}
}
// package private method. Do not call this directly.
init(apiKey: String,
launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil,
config: IterableConfig = IterableConfig(),
apiEndPointOverride: String? = nil,
linksEndPointOverride: String? = nil,
dependencyContainer: DependencyContainerProtocol = DependencyContainer()) {
IterableLogUtil.sharedInstance = IterableLogUtil(dateProvider: dependencyContainer.dateProvider, logDelegate: config.logDelegate)
ITBInfo()
self.apiKey = apiKey
self.launchOptions = launchOptions
self.config = config
apiEndPoint = apiEndPointOverride ?? Endpoint.api
linksEndPoint = linksEndPointOverride ?? Endpoint.links
self.dependencyContainer = dependencyContainer
dateProvider = dependencyContainer.dateProvider
networkSession = dependencyContainer.networkSession
notificationStateProvider = dependencyContainer.notificationStateProvider
localStorage = dependencyContainer.localStorage
inAppDisplayer = dependencyContainer.inAppDisplayer
urlOpener = dependencyContainer.urlOpener
deepLinkManager = IterableDeepLinkManager()
}
func start() -> Future<Bool, Error> {
ITBInfo()
updateSDKVersion()
checkForDeferredDeepLink()
// get email and userId from UserDefaults if present
retrieveIdentifierData()
if config.autoPushRegistration, isEitherUserIdOrEmailSet() {
notificationStateProvider.registerForRemoteNotifications()
}
IterableAppIntegration.implementation = IterableAppIntegrationInternal(tracker: self,
urlDelegate: config.urlDelegate,
customActionDelegate: config.customActionDelegate,
urlOpener: urlOpener,
inAppNotifiable: inAppManager)
handle(launchOptions: launchOptions)
handlePendingNotification()
handlePendingUniversalLink()
requestHandler.start()
return inAppManager.start()
}
private func handle(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
guard let launchOptions = launchOptions else {
return
}
if let remoteNotificationPayload = launchOptions[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
if let _ = IterableUtil.rootViewController {
// we are ready
IterableAppIntegration.implementation?.performDefaultNotificationAction(remoteNotificationPayload)
} else {
// keywindow not set yet
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
IterableAppIntegration.implementation?.performDefaultNotificationAction(remoteNotificationPayload)
}
}
}
}
private func handlePendingNotification() {
if let pendingNotificationResponse = Self.pendingNotificationResponse {
if #available(iOS 10.0, *) {
IterableAppIntegration.implementation?.userNotificationCenter(nil, didReceive: pendingNotificationResponse, withCompletionHandler: nil)
}
Self.pendingNotificationResponse = nil
}
}
private func handlePendingUniversalLink() {
if let pendingUniversalLink = Self.pendingUniversalLink {
handleUniversalLink(pendingUniversalLink)
Self.pendingUniversalLink = nil
}
}
private func checkForDeferredDeepLink() {
guard config.checkForDeferredDeeplink else {
return
}
guard localStorage.ddlChecked == false else {
return
}
guard let request = IterableRequestUtil.createPostRequest(forApiEndPoint: linksEndPoint,
path: Const.Path.ddlMatch,
headers: [JsonKey.Header.apiKey: apiKey],
args: nil,
body: DeviceInfo.createDeviceInfo()) else {
ITBError("Could not create request")
return
}
NetworkHelper.sendRequest(request, usingSession: networkSession).onSuccess { json in
self.handleDDL(json: json)
}.onError { sendError in
ITBError(sendError.reason)
}
}
private func handleDDL(json: [AnyHashable: Any]) {
if let serverResponse = try? JSONDecoder().decode(ServerResponse.self, from: JSONSerialization.data(withJSONObject: json, options: [])),
serverResponse.isMatch,
let destinationUrlString = serverResponse.destinationUrl {
handleUrl(urlString: destinationUrlString, fromSource: .universalLink)
}
localStorage.ddlChecked = true
}
private func handleUrl(urlString: String, fromSource source: IterableActionSource) {
guard let action = IterableAction.actionOpenUrl(fromUrlString: urlString) else {
ITBError("Could not create action from: \(urlString)")
return
}
let context = IterableActionContext(action: action, source: source)
DispatchQueue.main.async {
IterableActionRunner.execute(action: action,
context: context,
urlHandler: IterableUtil.urlHandler(fromUrlDelegate: self.config.urlDelegate, inContext: context),
urlOpener: self.urlOpener)
}
}
private func updateSDKVersion() {
if let lastVersion = localStorage.sdkVersion, lastVersion != IterableAPI.sdkVersion {
performUpgrade(lastVersion: lastVersion, newVersion: IterableAPI.sdkVersion)
} else {
localStorage.sdkVersion = IterableAPI.sdkVersion
}
}
private func performUpgrade(lastVersion _: String, newVersion: String) {
// do upgrade things here
// ....
// then set new version
localStorage.sdkVersion = newVersion
}
deinit {
ITBInfo()
requestHandler.stop()
}
}
// MARK: - DEPRECATED
extension IterableAPIInternal {
// deprecated - will be removed in version 6.3.x or above
@discardableResult
func trackInAppOpen(_ messageId: String,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.trackInAppOpen(messageId, onSuccess: onSuccess, onFailure: onFailure)
}
// deprecated - will be removed in version 6.3.x or above
@discardableResult
func trackInAppClick(_ messageId: String,
clickedUrl: String,
onSuccess: OnSuccessHandler? = nil,
onFailure: OnFailureHandler? = nil) -> Future<SendRequestValue, SendRequestError> {
requestHandler.trackInAppClick(messageId, clickedUrl: clickedUrl, onSuccess: onSuccess, onFailure: onFailure)
}
// deprecated - will be removed in version 6.3.x or above
func showSystemNotification(withTitle title: String, body: String, buttonLeft: String? = nil, buttonRight: String? = nil, callbackBlock: ITEActionBlock?) {
InAppDisplayer.showSystemNotification(withTitle: title, body: body, buttonLeft: buttonLeft, buttonRight: buttonRight, callbackBlock: callbackBlock)
}
// deprecated - will be removed in version 6.3.x or above
@discardableResult func getAndTrack(deepLink: URL, callbackBlock: @escaping ITEActionBlock) -> Future<IterableAttributionInfo?, Error>? {
deepLinkManager.getAndTrack(deepLink: deepLink, callbackBlock: callbackBlock).onSuccess { attributionInfo in
if let attributionInfo = attributionInfo {
self.attributionInfo = attributionInfo
}
}
}
}
| 41.777461 | 162 | 0.571672 |
756e72549e4ca397bd2c892a46384a0ddbd19e0d | 10,106 | //
// OPDS2Parser.swift
// readium-opds
//
// Created by Nikita Aizikovskyi on Jan-30-2018.
//
// Copyright 2018 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
import R2Shared
public enum OPDS2ParserError: Error {
case invalidJSON
case metadataNotFound
case invalidLink
case missingTitle
case invalidFacet
case invalidGroup
case invalidPublication
case invalidNavigation
}
public class OPDS2Parser: Loggable {
static var feedURL: URL?
/// Parse an OPDS feed or publication.
/// Feed can only be v2 (JSON).
/// - parameter url: The feed URL
public static func parseURL(url: URL, completion: @escaping (ParseData?, Error?) -> Void) {
feedURL = url
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let response = response else {
completion(nil, error ?? OPDSParserError.documentNotFound)
return
}
do {
let parseData = try self.parse(jsonData: data, url: url, response: response)
completion(parseData, nil)
} catch {
completion(nil, error)
}
}.resume()
}
/// Parse an OPDS feed or publication.
/// Feed can only be v2 (JSON).
/// - parameter jsonData: The json raw data
/// - parameter url: The feed URL
/// - parameter response: The response payload
/// - Returns: The intermediate structure of type ParseData
public static func parse(jsonData: Data, url: URL, response: URLResponse) throws -> ParseData {
feedURL = url
var parseData = ParseData(url: url, response: response, version: .OPDS2)
guard let jsonRoot = try? JSONSerialization.jsonObject(with: jsonData, options: []) else {
throw OPDS2ParserError.invalidJSON
}
guard let topLevelDict = jsonRoot as? [String: Any] else {
throw OPDS2ParserError.invalidJSON
}
do {
if topLevelDict["navigation"] == nil
&& topLevelDict["groups"] == nil
&& topLevelDict["publications"] == nil
&& topLevelDict["facets"] == nil {
// Publication only
parseData.publication = try Publication(json: topLevelDict)
} else {
// Feed
parseData.feed = try parse(jsonDict: topLevelDict)
}
} catch {
log(.warning, error)
}
return parseData
}
/// Parse an OPDS feed.
/// Feed can only be v2 (JSON).
/// - parameter jsonDict: The json top level dictionary
/// - Returns: The resulting Feed
public static func parse(jsonDict: [String: Any]) throws -> Feed {
guard let metadataDict = jsonDict["metadata"] as? [String: Any] else {
throw OPDS2ParserError.metadataNotFound
}
guard let title = metadataDict["title"] as? String else {
throw OPDS2ParserError.missingTitle
}
let feed = Feed(title: title)
parseMetadata(opdsMetadata: feed.metadata, metadataDict: metadataDict)
for (k, v) in jsonDict {
switch k {
case "@context":
switch v {
case let s as String:
feed.context.append(s)
case let sArr as [String]:
feed.context.append(contentsOf: sArr)
default:
continue
}
case "metadata": // Already handled above
continue
case "links":
guard let links = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidLink
}
try parseLinks(feed: feed, links: links)
case "facets":
guard let facets = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidFacet
}
try parseFacets(feed: feed, facets: facets)
case "publications":
guard let publications = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidPublication
}
try parsePublications(feed: feed, publications: publications)
case "navigation":
guard let navLinks = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidNavigation
}
try parseNavigation(feed: feed, navLinks: navLinks)
case "groups":
guard let groups = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidGroup
}
try parseGroups(feed: feed, groups: groups)
default:
continue
}
}
return feed
}
static func parseMetadata(opdsMetadata: OpdsMetadata, metadataDict: [String: Any]) {
for (k, v) in metadataDict {
switch k {
case "title":
if let title = v as? String {
opdsMetadata.title = title
}
case "numberOfItems":
opdsMetadata.numberOfItem = v as? Int
case "itemsPerPage":
opdsMetadata.itemsPerPage = v as? Int
case "modified":
if let dateStr = v as? String {
opdsMetadata.modified = dateStr.dateFromISO8601
}
case "@type":
opdsMetadata.rdfType = v as? String
case "currentPage":
opdsMetadata.currentPage = v as? Int
default:
continue
}
}
}
static func parseFacets(feed: Feed, facets: [[String: Any]]) throws {
for facetDict in facets {
guard let metadata = facetDict["metadata"] as? [String: Any] else {
throw OPDS2ParserError.invalidFacet
}
guard let title = metadata["title"] as? String else {
throw OPDS2ParserError.invalidFacet
}
let facet = Facet(title: title)
parseMetadata(opdsMetadata: facet.metadata, metadataDict: metadata)
for (k, v) in facetDict {
if (k == "links") {
guard let links = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidFacet
}
for linkDict in links {
let link = try Link(json: linkDict, normalizeHREF: {
URLHelper.getAbsolute(href: $0, base: feedURL) ?? $0
})
facet.links.append(link)
}
}
}
feed.facets.append(facet)
}
}
static func parseLinks(feed: Feed, links: [[String: Any]]) throws {
for linkDict in links {
let link = try Link(json: linkDict, normalizeHREF: hrefNormalizer(feedURL))
feed.links.append(link)
}
}
static func parsePublications(feed: Feed, publications: [[String: Any]]) throws {
for pubDict in publications {
let pub = try Publication(json: pubDict)
feed.publications.append(pub)
}
}
static func parseNavigation(feed: Feed, navLinks: [[String: Any]]) throws {
for navDict in navLinks {
let link = try Link(json: navDict, normalizeHREF: hrefNormalizer(feedURL))
feed.navigation.append(link)
}
}
static func parseGroups(feed: Feed, groups: [[String: Any]]) throws {
for groupDict in groups {
guard let metadata = groupDict["metadata"] as? [String: Any] else {
throw OPDS2ParserError.invalidGroup
}
guard let title = metadata["title"] as? String else {
throw OPDS2ParserError.invalidGroup
}
let group = Group(title: title)
parseMetadata(opdsMetadata: group.metadata, metadataDict: metadata)
for (k, v) in groupDict {
switch k {
case "metadata":
// Already handled above
continue
case "links":
guard let links = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidGroup
}
for linkDict in links {
let link = try Link(json: linkDict, normalizeHREF: hrefNormalizer(feedURL))
group.links.append(link)
}
case "navigation":
guard let links = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidGroup
}
for linkDict in links {
let link = try Link(json: linkDict, normalizeHREF: hrefNormalizer(feedURL))
group.navigation.append(link)
}
case "publications":
guard let publications = v as? [[String: Any]] else {
throw OPDS2ParserError.invalidGroup
}
for pubDict in publications {
let publication = try Publication(json: pubDict)
group.publications.append(publication)
}
default:
continue
}
}
feed.groups.append(group)
}
}
}
private func hrefNormalizer(_ baseURL: URL?) -> (String) -> (String) {
return { href in URLHelper.getAbsolute(href: href, base: baseURL) ?? href }
}
| 35.836879 | 99 | 0.517712 |
3a565bc0e973c9172e5bb123d76fbe3ebdca0513 | 9,370 | //
// SocketPacket.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
struct SocketPacket {
private let placeholders: Int
private var currentPlace = 0
private static let logType = "SocketPacket"
let nsp: String
let id: Int
let type: PacketType
enum PacketType: Int {
case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
}
var args: [AnyObject]? {
var arr = data
if data.count == 0 {
return nil
} else {
if type == .Event || type == .BinaryEvent {
arr.removeAtIndex(0)
return arr
} else {
return arr
}
}
}
var binary: [NSData]
var data: [AnyObject]
var description: String {
return "SocketPacket {type: \(String(type.rawValue)); data: " +
"\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
}
var event: String {
return data[0] as? String ?? String(data[0])
}
var packetString: String {
return createPacketString()
}
init(type: SocketPacket.PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) {
self.data = data
self.id = id
self.nsp = nsp
self.type = type
self.placeholders = placeholders
self.binary = binary
}
mutating func addData(data: NSData) -> Bool {
if placeholders == currentPlace {
return true
}
binary.append(data)
currentPlace++
if placeholders == currentPlace {
currentPlace = 0
return true
} else {
return false
}
}
private func completeMessage(var message: String, ack: Bool) -> String {
if data.count == 0 {
return message + "]"
}
for arg in data {
if arg is NSDictionary || arg is [AnyObject] {
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(rawValue: 0))
let jsonString = NSString(data: jsonSend, encoding: NSUTF8StringEncoding)
message += jsonString! as String + ","
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
}
} else if var str = arg as? String {
str = str["\n"] ~= "\\\\n"
str = str["\r"] ~= "\\\\r"
message += "\"\(str)\","
} else if arg is NSNull {
message += "null,"
} else {
message += "\(arg),"
}
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
private func createAck() -> String {
let msg: String
if type == PacketType.Ack {
if nsp == "/" {
msg = "3\(id)["
} else {
msg = "3\(nsp),\(id)["
}
} else {
if nsp == "/" {
msg = "6\(binary.count)-\(id)["
} else {
msg = "6\(binary.count)-\(nsp),\(id)["
}
}
return completeMessage(msg, ack: true)
}
private func createMessageForEvent() -> String {
let message: String
if type == PacketType.Event {
if nsp == "/" {
if id == -1 {
message = "2["
} else {
message = "2\(id)["
}
} else {
if id == -1 {
message = "2\(nsp),["
} else {
message = "2\(nsp),\(id)["
}
}
} else {
if nsp == "/" {
if id == -1 {
message = "5\(binary.count)-["
} else {
message = "5\(binary.count)-\(id)["
}
} else {
if id == -1 {
message = "5\(binary.count)-\(nsp),["
} else {
message = "5\(binary.count)-\(nsp),\(id)["
}
}
}
return completeMessage(message, ack: false)
}
private func createPacketString() -> String {
let str: String
if type == PacketType.Event || type == PacketType.BinaryEvent {
str = createMessageForEvent()
} else {
str = createAck()
}
return str
}
mutating func fillInPlaceholders() {
for i in 0..<data.count {
if let str = data[i] as? String, num = str["~~(\\d)"].groups() {
// Fill in binary placeholder with data
data[i] = binary[Int(num[1])!]
} else if data[i] is NSDictionary || data[i] is NSArray {
data[i] = _fillInPlaceholders(data[i])
}
}
}
private mutating func _fillInPlaceholders(data: AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return binary[Int(num[1])!]
} else {
return str
}
} else if let dict = data as? NSDictionary {
let newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
let newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
}
}
}
extension SocketPacket {
private static func findType(binCount: Int, ack: Bool) -> PacketType {
switch binCount {
case 0 where !ack:
return PacketType.Event
case 0 where ack:
return PacketType.Ack
case _ where !ack:
return PacketType.BinaryEvent
case _ where ack:
return PacketType.BinaryAck
default:
return PacketType.Error
}
}
static func packetFromEmit(items: [AnyObject], id: Int, nsp: String, ack: Bool) -> SocketPacket {
let (parsedData, binary) = deconstructData(items)
let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData,
id: id, nsp: nsp, placeholders: -1, binary: binary)
return packet
}
}
private extension SocketPacket {
static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
if let bin = data as? NSData {
let placeholder = ["_placeholder" :true, "num": binary.count]
binary.append(bin)
return placeholder
} else if var arr = data as? [AnyObject] {
for i in 0..<arr.count {
arr[i] = shred(arr[i], binary: &binary)
}
return arr
} else if let dict = data as? NSDictionary {
let mutDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
mutDict[key as! NSCopying] = shred(value, binary: &binary)
}
return mutDict
} else {
return data
}
}
static func deconstructData(var data: [AnyObject]) -> ([AnyObject], [NSData]) {
var binary = [NSData]()
for i in 0..<data.count {
data[i] = shred(data[i], binary: &binary)
}
return (data, binary)
}
}
| 30.721311 | 114 | 0.491676 |
64cdfc22dd82f7ddb9e3ed1c9f8c5871c40782bb | 639 | //
// Utils.swift
// AimyboxCore
//
// Created by Vladyslav Popovych on 30.11.2019.
// Copyright © 2019 Just Ai. All rights reserved.
//
import Foundation
public
protocol AimyboxDelegate: SpeechToTextDelegate, TextToSpeechDelegate, DialogAPIDelegate {
/**
Called before new state is set. Optional.
*/
func aimybox(_ aimybox: Aimybox, willMoveFrom oldState: AimyboxState, to newState: AimyboxState)
}
/**
All methods listed here are optional for delegates to implement.
*/
public
extension AimyboxDelegate {
func aimybox(_ aimybox: Aimybox, willMoveFrom oldState: AimyboxState, to newState: AimyboxState) {}
}
| 22.034483 | 103 | 0.738654 |
fc90a440cd4da501426838e09c7b728ea3799d9f | 1,791 | //
// ProfileNugget.swift
// swaap
//
// Created by Michael Redig on 12/4/19.
// Copyright © 2019 swaap. All rights reserved.
//
import Foundation
/// Represents a single contact method for a user
struct ProfileContactMethod: Codable, Hashable {
let id: String?
let value: String
let type: ProfileFieldType
var privacy: ProfileFieldPrivacy
var preferredContact: Bool
var infoNugget: ProfileInfoNugget {
ProfileInfoNugget(type: type, value: value)
}
init(id: String? = nil, value: String, type: ProfileFieldType, privacy: ProfileFieldPrivacy = .connected, preferredContact: Bool = false) {
self.id = id
self.value = value
self.type = type
self.privacy = privacy
self.preferredContact = preferredContact
}
}
/// Can represent either contact information or static user information like their name, industry, bio, etc.
struct ProfileInfoNugget {
var type: ProfileFieldType?
var value: String
var contactMethod: ProfileContactMethod? {
guard let type = type else { return nil }
return ProfileContactMethod(value: value, type: type)
}
var displayValue: String {
switch type {
case .twitter, .instagram:
return "@\(value)"
default:
return value
}
}
}
extension Array where Element == ProfileContactMethod {
var preferredContact: ProfileContactMethod? {
first(where: { $0.preferredContact })
}
}
struct MutateProfileContactMethod: Codable, Hashable {
let id: String?
let value: String
let type: ProfileFieldType
let privacy: ProfileFieldPrivacy
let preferredContact: Bool
}
extension MutateProfileContactMethod {
init(contactMethod: ProfileContactMethod) {
id = contactMethod.id
value = contactMethod.value
type = contactMethod.type
privacy = contactMethod.privacy
preferredContact = contactMethod.preferredContact
}
}
| 23.88 | 140 | 0.747627 |
3984a236551d9c7ae44a9d7901d8cee443c006ad | 4,123 | //
// ArticlesTableVC.swift
// SwiftGG
//
// Created by 徐开源 on 16/3/10.
// Copyright © 2016年 徐开源. All rights reserved.
//
import UIKit
import SafariServices
class ArticlesTableVC: UITableViewController, UIWebViewDelegate {
var titleText: String = "" // 这个页面的 title 应有的值,名称区别于 self.title
var link: String = "" // 这个页面需要访问的链接,据此来获取内容
fileprivate let webview = UIWebView()
fileprivate var tableData = [CellDataModel]()
fileprivate func getKey() -> String { return self.titleText }
// MARK: - Life Cycle
override func viewWillAppear(_ animated: Bool) {
// 加载本地数据
tableData = self.getContentFromDevice(key: self.getKey())
tableView.reloadData()
// 加载网页
requestContent()
}
override func viewDidLoad() {
super.viewDidLoad()
title = titleText
webview.delegate = self
// 导航栏加入刷新按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .refresh, target: self, action: #selector(requestContent))
// peek
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
}
@objc private func requestContent() {
guard let url = URL(string: link) else { return }
webview.loadRequest(URLRequest(url: url))
}
// MARK: - Web View
func webViewDidStartLoad(_ webView: UIWebView) {
// title 提示
title = "内容刷新中"
}
func webViewDidFinishLoad(_ webView: UIWebView) {
// title 提示
title = titleText
// 从 webview 抓取内容
let titles = webview.getArticleTitles()
let links = webview.getArticleLinks()
// 处理抓取到的内容
tableData.setByData(titles: titles, links: links)
// 根据内容刷新页面
self.reloadbyComparingData(tableview: tableView,
oldData: self.getContentFromDevice(key: self.getKey()),
newData: tableData, key: self.getKey())
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath)
cell.textLabel?.text = tableData[(indexPath as NSIndexPath).row].title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let url = URL(string: tableData[indexPath.row].link) else { return }
// if #available(iOS 9.0, *) {
let safari = SFSafariViewController(url: url)
self.present(safari, animated: true, completion: nil)
// } else {
// let safari = FakeSafariViewController(URL: url)
// guard let navi = self.navigationController else { return }
// navi.pushViewController(safari, animated: true)
// }
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - Peek
extension ArticlesTableVC: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location) else {
return nil
}
guard let url = URL(string: tableData[indexPath.row].link) else {
return nil
}
guard let cell = tableView.cellForRow(at: indexPath) else {return nil}
previewingContext.sourceRect = cell.frame
return SFSafariViewController(url: url)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
present(viewControllerToCommit, animated: true, completion: nil)
}
}
| 33.25 | 143 | 0.641281 |
fee6febe58091e7754b6507f3ad8e1a58f92d528 | 1,342 | //
// AppDelegate.swift
// practice
//
// Created by skynet on 23/12/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.27027 | 179 | 0.745156 |
331f85f14636eb2a35d8ad3cad7c56c149822d8e | 660 | //
// UIFont+Extensions.swift
// Reminder-Sample-App
//
// Created by Valerio Sebastianelli on 12/10/20.
//
import UIKit
extension UIFont {
func withTraits(traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
let descriptor = fontDescriptor.withSymbolicTraits(traits)
return UIFont(descriptor: descriptor!, size: 0) //size 0 means keep the size as it is
}
var bold: UIFont {
return withTraits(traits: .traitBold)
}
var italic: UIFont {
return withTraits(traits: .traitItalic)
}
var semibold: UIFont {
return UIFont.systemFont(ofSize: pointSize, weight: .semibold)
}
}
| 23.571429 | 93 | 0.654545 |
228345b31fc43583fdf65ade6ab473c7348ff743 | 2,578 | //
// Copyright (c) 2018 Related Code - http://relatedcode.com
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//-------------------------------------------------------------------------------------------------------------------------------------------------
class UserDefaultsX: NSObject {
//---------------------------------------------------------------------------------------------------------------------------------------------
class func setObject(value: Any, key: String) {
UserDefaults.standard.set(value, forKey: key)
UserDefaults.standard.synchronize()
}
//---------------------------------------------------------------------------------------------------------------------------------------------
class func removeObject(key: String) {
UserDefaults.standard.removeObject(forKey: key)
UserDefaults.standard.synchronize()
}
//---------------------------------------------------------------------------------------------------------------------------------------------
class func removeObject(key: String, afterDelay delay: TimeInterval) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
removeObject(key: key)
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------
class func object(key: String) -> Any? {
return UserDefaults.standard.object(forKey: key)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
class func string(key: String) -> String? {
return UserDefaults.standard.string(forKey: key)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
class func integer(key: String) -> Int {
return UserDefaults.standard.integer(forKey: key)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
class func bool(key: String) -> Bool {
return UserDefaults.standard.bool(forKey: key)
}
}
| 42.262295 | 147 | 0.402638 |
0efc0a24a8ad99b0d717fefc3bc9fcf220275bf9 | 15,755 | //
// DetailedInfoController.swift
// BMLTiOSLib
//
// Created by BMLT-Enabled
//
// https://bmlt.app/
//
// This software is licensed under the MIT License.
// Copyright (c) 2017 BMLT-Enabled
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import MapKit
import BMLTiOSLib
/* ###################################################################################################################################### */
/**
*/
class DetailedInfoController: BaseTestViewController, UITableViewDelegate, UITableViewDataSource, MKMapViewDelegate, UITextFieldDelegate {
static let sMapSizeInDegrees: CLLocationDegrees = 0.75
enum TableRows: Int {
case FormatRow = 0, LoginRow, LocationRow
}
let sButtonCollapsed: CGFloat = 30
let sButtonOpen: CGFloat = 200
let sLoginRowHeight: CGFloat = 164
let sLoginRowHeightCollapsed: CGFloat = 30
var mapMarkerAnnotation: BMLTiOSLibTesterAnnotation! = nil
@IBOutlet var _formatCellView: UIView!
@IBOutlet var _formatLabel: UILabel!
@IBOutlet var _formatTextView: UITextView!
@IBOutlet var _formatButton: UIButton!
@IBOutlet var _formatActivity: UIActivityIndicatorView!
@IBOutlet var _loginCellView: UIView!
@IBOutlet weak var loginIDLabel: UILabel!
@IBOutlet weak var loginIDTextField: UITextField!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var resultsTextView: UITextView!
var loginButtonLoggedIn: UIButton! = nil
@IBOutlet var _mapView: MKMapView!
/* ################################################################## */
/**
*/
func createDisplayText() {
if BMLTiOSLibTesterAppDelegate.libraryObject.isAdminLoggedIn {
var displayText: String = "We are logged into the Root Server as an administrator.\nWe have the indicated permissions for the following Service bodies:\n\n"
for sb in BMLTiOSLibTesterAppDelegate.libraryObject.serviceBodies where .None != sb.permissions {
displayText += " " + sb.name + " (\(sb.permissions))\n"
}
self.resultsTextView.text = displayText
}
}
/* ################################################################## */
/**
*/
func setupLoginView() {
if let tableView = self.view as? UITableView {
tableView.reloadData()
}
}
/* ################################################################## */
/**
*/
@IBAction func fetchAllUsedFormats(_ sender: UIButton) {
if nil != BMLTiOSLibTesterAppDelegate.libraryObject {
self._formatButton.isHidden = true
self._formatLabel.isHidden = true
self._formatTextView.isHidden = true
self._formatActivity.isHidden = false
BMLTiOSLibTesterAppDelegate.libraryObject.getAllUsedFormats()
}
}
/* ################################################################## */
/**
*/
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
/* ################################################################## */
/**
*/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Got this tip from here: http://natecook.com/blog/2014/10/loopy-random-enum-ideas/
var max: Int = 0
while nil != TableRows(rawValue: max) { max += 1 }
return max
}
/* ################################################################## */
/**
*/
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var ret: CGFloat = tableView.rowHeight
switch indexPath.row {
case TableRows.FormatRow.rawValue:
if nil != _formatTextView {
if self._formatTextView.isHidden {
ret = self.sButtonCollapsed
} else {
ret = self.sButtonOpen
}
}
case TableRows.LoginRow.rawValue:
ret = BMLTiOSLibTesterAppDelegate.libraryObject.isAdminAvailable ? (BMLTiOSLibTesterAppDelegate.libraryObject.isAdminLoggedIn ? self.sLoginRowHeightCollapsed : self.sLoginRowHeight) : 0
case TableRows.LocationRow.rawValue:
ret = tableView.bounds.size.width
default:
break
}
return ret
}
/* ################################################################## */
/**
*/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var reuseID: String = ""
var ret: UITableViewCell! = nil
switch indexPath.row {
case TableRows.FormatRow.rawValue:
reuseID = "DetailFormatCell"
case TableRows.LoginRow.rawValue:
reuseID = ""
case TableRows.LocationRow.rawValue:
reuseID = "DetailLocationMapCell"
default:
break
}
if nil == ret {
if !reuseID.isEmpty {
ret = tableView.dequeueReusableCell(withIdentifier: reuseID)
}
if nil == ret {
ret = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseID)
if nil != ret {
ret.backgroundColor = UIColor.clear
switch indexPath.row {
case TableRows.FormatRow.rawValue:
ret = self.handleFormatRow(tableView, indexPath: indexPath, ret: ret, reuseID: reuseID)
case TableRows.LoginRow.rawValue:
ret = self.handleLoginRow(tableView, indexPath: indexPath, ret: ret)
case TableRows.LocationRow.rawValue:
ret = self.handleLocationRow(tableView, indexPath: indexPath, ret: ret, reuseID: reuseID)
default:
break
}
}
}
}
return ret
}
/* ################################################################## */
/**
*/
func handleFormatRow(_ tableView: UITableView, indexPath: IndexPath, ret: UITableViewCell, reuseID: String) -> UITableViewCell {
if nil == self._formatCellView {
_ = UINib(nibName: reuseID, bundle: nil).instantiate(withOwner: self, options: nil)[0]
}
if nil != self._formatCellView {
var bounds: CGRect = tableView.bounds
bounds.size.height = self.tableView(tableView, heightForRowAt: indexPath)
self._formatCellView.bounds = bounds
self._formatCellView.frame = bounds
ret.frame = bounds
ret.bounds = bounds
ret.addSubview(self._formatCellView)
}
return ret
}
/* ################################################################## */
/**
*/
func handleLoginRow(_ tableView: UITableView, indexPath: IndexPath, ret: UITableViewCell) -> UITableViewCell {
var bounds: CGRect = tableView.bounds
bounds.size.height = self.tableView(tableView, heightForRowAt: indexPath)
ret.frame = bounds
ret.bounds = bounds
ret.backgroundColor = UIColor.clear
if BMLTiOSLibTesterAppDelegate.libraryObject.isAdminAvailable {
if !BMLTiOSLibTesterAppDelegate.libraryObject.isAdminLoggedIn {
if nil != self.loginButtonLoggedIn {
self.loginButtonLoggedIn.removeFromSuperview()
self.loginButtonLoggedIn = nil
}
if nil == self._loginCellView {
_ = UINib(nibName: "DetailLoginTableCellView", bundle: nil).instantiate(withOwner: self, options: nil)[0]
}
if nil != self._loginCellView {
self._loginCellView.bounds = bounds
self._loginCellView.frame = bounds
ret.addSubview(self._loginCellView)
}
} else {
if nil != self._loginCellView {
self.loginIDLabel.removeFromSuperview()
self.loginIDLabel = nil
self.loginIDTextField.removeFromSuperview()
self.loginIDTextField = nil
self.passwordLabel.removeFromSuperview()
self.passwordLabel = nil
self.passwordTextField.removeFromSuperview()
self.passwordTextField = nil
self.loginButton.removeFromSuperview()
self.loginButton = nil
self._loginCellView.removeFromSuperview()
self._loginCellView = nil
}
if nil == self.loginButtonLoggedIn {
self.loginButtonLoggedIn = UIButton(frame: bounds)
if nil != self.loginButtonLoggedIn {
self.loginButtonLoggedIn.setTitle("LOG OUT", for: UIControl.State.normal)
self.loginButtonLoggedIn.setTitleColor(self.view.tintColor, for: UIControl.State.normal)
self.loginButtonLoggedIn.addTarget(self, action: #selector(DetailedInfoController.loginButtonHit(_:)), for: UIControl.Event.touchUpInside)
ret.addSubview(self.loginButtonLoggedIn)
}
}
}
}
return ret
}
/* ################################################################## */
/**
*/
func handleLocationRow(_ tableView: UITableView, indexPath: IndexPath, ret: UITableViewCell, reuseID: String) -> UITableViewCell {
if nil == self._mapView {
_ = UINib(nibName: reuseID, bundle: nil).instantiate(withOwner: self, options: nil)[0]
}
if nil != self._mapView {
var bounds: CGRect = tableView.bounds
bounds.size.height = self.tableView(tableView, heightForRowAt: indexPath)
self._mapView.bounds = bounds
self._mapView.frame = bounds
ret.frame = bounds
ret.bounds = bounds
if nil != BMLTiOSLibTesterAppDelegate.libraryObject {
let mapLocation = BMLTiOSLibTesterAppDelegate.libraryObject.defaultLocation
let span = MKCoordinateSpan(latitudeDelta: type(of: self).sMapSizeInDegrees, longitudeDelta: 0)
let newRegion: MKCoordinateRegion = MKCoordinateRegion(center: mapLocation, span: span)
self._mapView.setRegion(newRegion, animated: false)
self.mapMarkerAnnotation = BMLTiOSLibTesterAnnotation(coordinate: mapLocation)
self._mapView.addAnnotation(self.mapMarkerAnnotation)
}
ret.addSubview(self._mapView)
}
return ret
}
/* ################################################################## */
/**
*/
func updateUsedFormats(inUsedFormats: [BMLTiOSLibFormatNode], isAllUsedFormats: Bool) {
self._formatButton.isHidden = true
self._formatLabel.isHidden = false
self._formatTextView.isHidden = false
self._formatActivity.isHidden = true
var text: String = ""
for format in inUsedFormats.sorted(by: { $0.key < $1.key }) {
text += format.key
text += " (" + String(format.id) + ") "
text += format.name + "\n"
}
self._formatTextView.text = text
(self.view as? UITableView)?.reloadData()
}
/* ################################################################## */
/**
Called when text is entered into a Text Entry.
- parameter inSender: The Text Entry Field that caused this to be called.
*/
@IBAction func textEntered(_ inSender: UITextField) {
self.loginButton.isEnabled = false
if (nil != self.loginIDTextField) && (nil != self.passwordTextField) {
if !BMLTiOSLibTesterAppDelegate.libraryObject.isAdminLoggedIn {
if let liText = self.loginIDTextField.text {
if let pwText = self.passwordTextField.text {
if !liText.isEmpty && !pwText.isEmpty {
self.loginButton.isEnabled = true
}
}
}
}
}
}
/* ################################################################## */
/**
*/
@IBAction func loginButtonHit(_ sender: AnyObject) {
if BMLTiOSLibTesterAppDelegate.libraryObject.isAdminLoggedIn {
if !BMLTiOSLibTesterAppDelegate.libraryObject.adminLogout() {
print("*** ERROR! The logout failed immediately!")
}
} else {
if let liText = self.loginIDTextField.text {
if let pwText = self.passwordTextField.text {
if !liText.isEmpty && !pwText.isEmpty {
if !BMLTiOSLibTesterAppDelegate.libraryObject.adminLogin(loginID: liText, password: pwText) {
print("*** ERROR! The login failed immediately!")
}
}
}
}
}
self.setupLoginView()
}
// MARK: - UITextFieldDelegate Handlers -
/* ################################################################## */
/**
*/
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if textField == self.passwordTextField {
self.loginButtonHit(self.loginButton)
}
return true
}
// MARK: - MKMapViewDelegate Methods -
/* ################################################################## */
/**
*/
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isKind(of: BMLTiOSLibTesterAnnotation.self) {
let reuseID = ""
let myAnnotation = annotation as? BMLTiOSLibTesterAnnotation
return BMLTiOSLibTesterMarker(annotation: myAnnotation, draggable: true, reuseID: reuseID)
}
return nil
}
}
| 39.486216 | 197 | 0.540717 |
9c623bff7d713a95f060e52a47bb2c43554b151b | 14,099 | // Copyright © 2020 Makeeyaf. All rights reserved
import SwiftUI
import MapKit
import Combine
class MCMapViewController: ObservableObject {
@Published public private(set) var mapView = MKMapView(frame: .zero)
}
struct MCMapControl: UIViewRepresentable {
@Binding var userTrackingMode: MKUserTrackingMode
@EnvironmentObject var mapViewController: MCMapViewController
func makeUIView(context: Context) -> MKMapView {
mapViewController.mapView.delegate = context.coordinator
let coordinate = CLLocationCoordinate2D(latitude: 36.378218, longitude: 127.834492)
let span = MKCoordinateSpan(latitudeDelta: 4, longitudeDelta: 4)
let region = MKCoordinateRegion(center: coordinate, span: span)
mapViewController.mapView.setRegion(region, animated: false)
mapViewController.mapView.showsScale = true
// context.coordinator.followUserIfPossible()
return mapViewController.mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
if uiView.userTrackingMode != userTrackingMode {
uiView.setUserTrackingMode(userTrackingMode, animated: true)
}
}
func makeCoordinator() -> MCMapViewCoordinator {
return MCMapViewCoordinator(self)
}
// MARK: - Coordinator
class MCMapViewCoordinator: NSObject, MKMapViewDelegate, CLLocationManagerDelegate {
var control: MCMapControl
var lastUpdatedRegion: MKCoordinateRegion = .init(center: CLLocationCoordinate2D(latitude: 36.378218, longitude: 127.834492), span: MKCoordinateSpan(latitudeDelta: 4, longitudeDelta: 4))
var lastUpdatedRadius: Double = 1000
var lastUpdateTime: Date = Date()
let locationManager: CLLocationManager = .init()
let mcheck = MCCheck()
var cancellable: Cancellable?
let updateInterval: Int = 5*60
init(_ control: MCMapControl) {
self.control = control
super.init()
setupLocationManager()
}
deinit {
self.cancellable?.cancel()
}
private func setupLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.pausesLocationUpdatesAutomatically = true
}
private func getNewRadius(_ radius: Double) -> Double {
switch radius {
case _ where radius > 2500:
return 5000
case _ where radius < 400:
return 800
default:
return radius*2
}
}
private func startTimer() {
#if DEBUG
print("\(type(of: self)).\(#function)")
#endif
cancellable?.cancel()
cancellable = Timer.publish(every: 30, on: .main, in: .common).autoconnect()
.sink { _ in
let duration = Int(DateInterval(start: self.lastUpdateTime, end: Date()).duration)
print("Time remaining: \(self.updateInterval - duration) sec")
if duration >= self.updateInterval {
let currentRadius = self.control.mapViewController.mapView.currentRadius()
self.updateMapView(mapView: self.control.mapViewController.mapView, radius: self.getNewRadius(currentRadius))
}
}
}
private func getDistance(currentRegion: MKCoordinateRegion, previousRegion: MKCoordinateRegion) -> CLLocationDistance {
let previousLocation = CLLocation(latitude: previousRegion.center.latitude, longitude: previousRegion.center.longitude)
let currentLocation = CLLocation(latitude: currentRegion.center.latitude, longitude: currentRegion.center.longitude)
return previousLocation.distance(from: currentLocation)
}
private func updateMapView(mapView: MKMapView, radius: Double) {
self.startTimer()
mapView.removeAnnotations(mapView.annotations)
mcheck.getStore(at: mapView.region.center, in: Int(radius)) { response in
for store in response.stores {
guard let status = store.remain_stat, status != MCRemainStat.none.status, status != MCRemainStat.empty.status else {
continue
}
#if DEBUG
print("Add \(store.name) \(store.remain_stat ?? "nil")")
#endif
DispatchQueue.main.async {
let pin = MCMapPin(store)
mapView.addAnnotation(pin)
}
}
}
self.lastUpdatedRegion = mapView.region
self.lastUpdatedRadius = radius
self.lastUpdateTime = Date()
}
// MARK: MKMapViewDelegate
func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) {
#if DEBUG
print("\(type(of: self)).\(#function): userTrackingMode=", terminator: "")
switch mode {
case .follow: print(".follow")
case .followWithHeading: print(".followWithHeading")
case .none: print(".none")
@unknown default: print("@unknown")
}
#endif
if CLLocationManager.locationServicesEnabled() {
switch mode {
case .follow, .followWithHeading:
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted:
// // Possibly due to active restrictions such as parental controls being in place
// let alert = UIAlertController(title: "Location Permission Restricted", message: "The app cannot access your location. This is possibly due to active restrictions such as parental controls being in place. Please disable or remove them and enable location permissions in settings.", preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "Settings", style: .default) { _ in
// // Redirect to Settings app
// UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
// })
// alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
// present(alert)
DispatchQueue.main.async {
self.control.userTrackingMode = .none
}
case .denied:
// let alert = UIAlertController(title: "Location Permission Denied", message: "Please enable location permissions in settings.", preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "Settings", style: .default) { _ in
// // Redirect to Settings app
// UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
// })
// alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
// present(alert)
DispatchQueue.main.async {
self.control.userTrackingMode = .none
}
default:
DispatchQueue.main.async {
self.control.userTrackingMode = mode
}
}
default:
DispatchQueue.main.async {
self.control.userTrackingMode = mode
}
}
} else {
// let alert = UIAlertController(title: "Location Services Disabled", message: "Please enable location services in settings.", preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "Settings", style: .default) { _ in
// // Redirect to Settings app
// UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
// })
// alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
// present(alert)
DispatchQueue.main.async {
self.control.userTrackingMode = mode
}
}
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
#if DEBUG
print("\(type(of: self)).\(#function)")
#endif
let currentRadius = mapView.currentRadius()
let distance = self.getDistance(currentRegion: mapView.region, previousRegion: self.lastUpdatedRegion)
if distance + currentRadius > self.lastUpdatedRadius {
self.updateMapView(mapView: mapView, radius: self.getNewRadius(currentRadius))
}
print("distance: \(Int(distance)), radius: \(currentRadius)")
print("Position: \(mapView.region.center.latitude), \(mapView.region.center.longitude)")
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let store = annotation as? MCMapPin else { return nil }
let identifier = "Pin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView
if annotationView == nil {
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
} else {
annotationView?.annotation = annotation
}
annotationView?.canShowCallout = true
annotationView?.markerTintColor = store.remain_stat.color
annotationView?.displayPriority = .required
let calloutViewController = UIHostingController(rootView: CalloutAccessoryView(status: store.remain_stat, stock_at: store.stock_at, created_at: store.created_at))
calloutViewController.view.backgroundColor = UIColor.clear
annotationView?.detailCalloutAccessoryView = calloutViewController.view
return annotationView
}
// MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
#if DEBUG
print("\(type(of: self)).\(#function): status=", terminator: "")
switch status {
case .notDetermined: print(".notDetermined")
case .restricted: print(".restricted")
case .denied: print(".denied")
case .authorizedAlways: print(".authorizedAlways")
case .authorizedWhenInUse: print(".authorizedWhenInUse")
@unknown default: print("@unknown")
}
#endif
switch status {
case .authorizedAlways, .authorizedWhenInUse:
locationManager.startUpdatingLocation()
control.mapViewController.mapView.setUserTrackingMode(control.userTrackingMode, animated: true)
guard let coordinate = manager.location?.coordinate else { break }
let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
let region = MKCoordinateRegion(center: coordinate, span: span)
control.mapViewController.mapView.setRegion(region, animated: true)
default:
control.mapViewController.mapView.setUserTrackingMode(.none, animated: true)
}
}
}
}
//class MCUserTrackingButtonController: ObservableObject {
// @Published var MCUserTrackingButton: MKUserTrackingButton
//
// init(mapView: MKMapView) {
// _MCUserTrackingButton = .init(initialValue: MKUserTrackingButton(mapView: mapView))
// }
//
//}
//
//struct MCUserTrackingButton: UIViewRepresentable {
// @EnvironmentObject var userTrackingButtonController: MCUserTrackingButtonController
//
// func makeUIView(context: Context) -> MKUserTrackingButton {
// userTrackingButtonController.MCUserTrackingButton.tintColor = UIColor.label
// userTrackingButtonController.MCUserTrackingButton.backgroundColor = UIColor.clear
// return userTrackingButtonController.MCUserTrackingButton
// }
//
// func updateUIView(_ uiView: MKUserTrackingButton, context: Context) {
// return
// }
//}
extension MKMapView {
func currentRadius() -> Double {
let centerLocation = CLLocation(latitude: self.centerCoordinate.latitude, longitude: self.centerCoordinate.longitude)
let topLeadingCoordinate = self.convert(CGPoint(x: 0, y: 0), toCoordinateFrom: self)
let topLeadingLocation = CLLocation(latitude: topLeadingCoordinate.latitude, longitude: topLeadingCoordinate.longitude)
return centerLocation.distance(from: topLeadingLocation)
}
}
| 45.925081 | 350 | 0.566991 |
38abd5b9e5cc79a6bcab0148c4eed9872a2d9f04 | 469 | import Foundation
@frozen
public enum OpenColorRed {
/// #FFF5F5
case red0
/// #FFE3E3
case red1
/// #FFC9C9
case red2
/// #FFA8A8
case red3
/// #FF8787
case red4
/// #FF6B6B
case red5
/// #FA5252
case red6
/// #F03E3E
case red7
/// #E03131
case red8
/// #C92A2A
case red9
}
extension OpenColor {
public static var red: OpenColorRed.Type {
OpenColorRed.self
}
}
| 11.439024 | 46 | 0.537313 |
1a9e9e24391d5c470e0c28f5fbead34883635cbd | 464 | //
// StartScreenTableViewCell.swift
// countidon
//
// Created by Karsten Gresch on 26.12.15.
// Copyright © 2015 Closure One. All rights reserved.
//
import UIKit
class StartScreenTableViewCell: UITableViewCell {
@IBOutlet weak var shapeButton: ShapeButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 19.333333 | 63 | 0.709052 |
6a7986cc2278ae7c92dc74603e775af23cb97e2c | 1,607 | //
// RoundCornersSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/25/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import BinartSwiftFeedback
final class RoundCornersSelectionTableViewCell: SelectionTableViewCell {
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "Round Corners"
descriptionValue = "The entry's corners can be rounded in one of the following manner"
insertSegments(by: ["None", "Top", "Bottom", "All"])
selectSegment()
}
private func selectSegment() {
switch attributesWrapper.attributes.roundCorners {
case .none:
segmentedControl.selectedSegmentIndex = 0
case .top(radius: _):
segmentedControl.selectedSegmentIndex = 1
case .bottom(radius: _):
segmentedControl.selectedSegmentIndex = 2
case .all(radius: _):
segmentedControl.selectedSegmentIndex = 3
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
attributesWrapper.attributes.roundCorners = .none
case 1:
attributesWrapper.attributes.roundCorners = .top(radius: 10)
case 2:
attributesWrapper.attributes.roundCorners = .bottom(radius: 10)
case 3:
attributesWrapper.attributes.roundCorners = .all(radius: 10)
default:
break
}
}
}
| 32.14 | 94 | 0.651525 |
ef8cefb984c5e284d3ed99498eb83775f1580755 | 466 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "SwiftUIRouter",
platforms: [
.macOS(.v11),
.iOS(.v14),
.tvOS(.v14),
.watchOS(.v6)
],
products: [
.library(
name: "SwiftUIRouter",
targets: ["SwiftUIRouter"]),
],
dependencies: [],
targets: [
.target(
name: "SwiftUIRouter",
dependencies: [],
path: "Sources"),
.testTarget(
name: "SwiftUIRouterTests",
dependencies: ["SwiftUIRouter"]),
]
)
| 16.068966 | 36 | 0.622318 |
8ac3843fa4c7d6e6d5cb8520beed02f72a4bbf87 | 851 | // ___FILEHEADER___
import UIKit
protocol ___FILEBASENAMEASIDENTIFIER___Protocol: AnyObject {
}
final class ___FILEBASENAMEASIDENTIFIER___: UITableViewController, ___FILEBASENAMEASIDENTIFIER___Protocol {
public var presenter: ___VARIABLE_productName___PresenterProtocol!
override public func viewDidLoad() -> () {
super.viewDidLoad()
}
// MARK: - TableView Delegate & DataSource
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
<#code#>
}
override public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
<#code#>
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
<#code#>
}
}
| 26.59375 | 116 | 0.695652 |
e4837be421f00502afb9d97ab2ae8caef6c99df7 | 979 | //
// RatingButtonsViewModel.swift
// FruitCounter
//
// Created by Ken Krzeminski on 8/14/20.
// Copyright © 2020 Ken Krzeminski. All rights reserved.
//
import Combine
import SwiftUI
final class RatingsButtonViewModel {
let font: Font = .appFont(size: 69)
var thumbsUpOpacity: Double
var thumbsDownOpacity: Double
private var currentRating: Rating
private let selectedOpacity: Double = 1
private let unselectedOpacity: Double = 0.35
init(currentRating: Rating) {
self.currentRating = currentRating
switch currentRating {
case .unrated:
thumbsUpOpacity = unselectedOpacity
thumbsDownOpacity = unselectedOpacity
case .thumbsDown:
thumbsUpOpacity = unselectedOpacity
thumbsDownOpacity = selectedOpacity
case .thumbsUp:
thumbsUpOpacity = selectedOpacity
thumbsDownOpacity = unselectedOpacity
}
}
}
| 25.102564 | 57 | 0.656793 |
fcaad21ea00c7d70388e25086501a4b00e7bd3a0 | 845 | /*
* Copyright 2021 Outfox, 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 Foundation
protocol CustomPathConvertible {
var pathDescription: String { get }
}
/**
* Standard PathParameterConvertible types
*/
extension UUID: CustomPathConvertible {
var pathDescription: String {
return uuidString
}
}
| 23.472222 | 75 | 0.734911 |
2f115a2d0e92aae4ae73ef537cce123fea28e47b | 22,256 | //
// Archive+Writing.swift
// ZIPFoundation
//
// Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
private enum ModifyOperation: Int {
case remove = -1
case add = 1
}
/// Write files, directories or symlinks to the receiver.
///
/// - Parameters:
/// - path: The path that is used to identify an `Entry` within the `Archive` file.
/// - baseURL: The base URL of the `Entry` to add.
/// The `baseURL` combined with `path` must form a fully qualified file URL.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`.
/// By default, no compression will be applied.
/// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed).
/// - progress: A progress object that can be used to track or cancel the add operation.
/// - Throws: An error if the source file cannot be read or the receiver is not writable.
public func addEntry(with path: String, relativeTo baseURL: URL, compressionMethod: CompressionMethod = .none,
bufferSize: UInt32 = defaultWriteChunkSize, progress: Progress? = nil) throws {
let fileManager = FileManager()
let entryURL = baseURL.appendingPathComponent(path)
guard fileManager.itemExists(at: entryURL) else {
throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: entryURL.path])
}
let type = try FileManager.typeForItem(at: entryURL)
// symlinks do not need to be readable
guard type == .symlink || fileManager.isReadableFile(atPath: entryURL.path) else {
throw CocoaError(.fileReadNoPermission, userInfo: [NSFilePathErrorKey: url.path])
}
let modDate = try FileManager.fileModificationDateTimeForItem(at: entryURL)
let uncompressedSize = type == .directory ? 0 : try FileManager.fileSizeForItem(at: entryURL)
let permissions = try FileManager.permissionsForItem(at: entryURL)
var provider: Provider
switch type {
case .file:
let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: entryURL.path)
guard let entryFile: UnsafeMutablePointer<FILE> = fopen(entryFileSystemRepresentation, "rb") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(entryFile) }
provider = { _, _ in return try Data.readChunk(of: Int(bufferSize), from: entryFile) }
try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize,
modificationDate: modDate, permissions: permissions,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
case .directory:
provider = { _, _ in return Data() }
try self.addEntry(with: path.hasSuffix("/") ? path : path + "/",
type: type, uncompressedSize: uncompressedSize,
modificationDate: modDate, permissions: permissions,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
case .symlink:
provider = { _, _ -> Data in
let linkDestination = try fileManager.destinationOfSymbolicLink(atPath: entryURL.path)
let linkFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: linkDestination)
let linkLength = Int(strlen(linkFileSystemRepresentation))
let linkBuffer = UnsafeBufferPointer(start: linkFileSystemRepresentation, count: linkLength)
return Data(buffer: linkBuffer)
}
try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize,
modificationDate: modDate, permissions: permissions,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
}
}
/// Write files, directories or symlinks to the receiver.
///
/// - Parameters:
/// - path: The path that is used to identify an `Entry` within the `Archive` file.
/// - type: Indicates the `Entry.EntryType` of the added content.
/// - uncompressedSize: The uncompressed size of the data that is going to be added with `provider`.
/// - modificationDate: A `Date` describing the file modification date of the `Entry`.
/// Default is the current `Date`.
/// - permissions: POSIX file permissions for the `Entry`.
/// Default is `0`o`644` for files and symlinks and `0`o`755` for directories.
/// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`.
/// By default, no compression will be applied.
/// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed).
/// - progress: A progress object that can be used to track or cancel the add operation.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - Throws: An error if the source data is invalid or the receiver is not writable.
public func addEntry(with path: String, type: Entry.EntryType, uncompressedSize: UInt32,
modificationDate: Date = Date(), permissions: UInt16? = nil,
compressionMethod: CompressionMethod = .none, bufferSize: UInt32 = defaultWriteChunkSize,
progress: Progress? = nil, provider: Provider) throws {
guard self.accessMode != .read else { throw ArchiveError.unwritableArchive }
progress?.totalUnitCount = type == .directory ? defaultDirectoryUnitCount : Int64(uncompressedSize)
var endOfCentralDirRecord = self.endOfCentralDirectoryRecord
var startOfCD = Int(endOfCentralDirRecord.offsetToStartOfCentralDirectory)
var existingCentralDirData = Data()
fseek(self.archiveFile, startOfCD, SEEK_SET)
existingCentralDirData = try Data.readChunk(of: Int(endOfCentralDirRecord.sizeOfCentralDirectory),
from: self.archiveFile)
fseek(self.archiveFile, startOfCD, SEEK_SET)
let localFileHeaderStart = ftell(self.archiveFile)
let modDateTime = modificationDate.fileModificationDateTime
defer { fflush(self.archiveFile) }
do {
var localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod,
size: (uncompressedSize, 0), checksum: 0,
modificationDateTime: modDateTime)
let (written, checksum) = try self.writeEntry(localFileHeader: localFileHeader, type: type,
compressionMethod: compressionMethod, bufferSize: bufferSize,
progress: progress, provider: provider)
startOfCD = ftell(self.archiveFile)
fseek(self.archiveFile, localFileHeaderStart, SEEK_SET)
// Write the local file header a second time. Now with compressedSize (if applicable) and a valid checksum.
localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod,
size: (uncompressedSize, written),
checksum: checksum, modificationDateTime: modDateTime)
fseek(self.archiveFile, startOfCD, SEEK_SET)
_ = try Data.write(chunk: existingCentralDirData, to: self.archiveFile)
let permissions = permissions ?? (type == .directory ? defaultDirectoryPermissions :defaultFilePermissions)
let externalAttributes = FileManager.externalFileAttributesForEntry(of: type, permissions: permissions)
let offset = UInt32(localFileHeaderStart)
let centralDir = try self.writeCentralDirectoryStructure(localFileHeader: localFileHeader,
relativeOffset: offset,
externalFileAttributes: externalAttributes)
if startOfCD > UINT32_MAX { throw ArchiveError.invalidStartOfCentralDirectoryOffset }
endOfCentralDirRecord = try self.writeEndOfCentralDirectory(centralDirectoryStructure: centralDir,
startOfCentralDirectory: UInt32(startOfCD),
operation: .add)
self.endOfCentralDirectoryRecord = endOfCentralDirRecord
} catch ArchiveError.cancelledOperation {
try rollback(localFileHeaderStart, existingCentralDirData, endOfCentralDirRecord)
throw ArchiveError.cancelledOperation
}
}
/// Remove a ZIP `Entry` from the receiver.
///
/// - Parameters:
/// - entry: The `Entry` to remove.
/// - bufferSize: The maximum size for the read and write buffers used during removal.
/// - progress: A progress object that can be used to track or cancel the remove operation.
/// - Throws: An error if the `Entry` is malformed or the receiver is not writable.
public func remove(_ entry: Entry, bufferSize: UInt32 = defaultReadChunkSize, progress: Progress? = nil) throws {
let manager = FileManager()
let tempDir = self.uniqueTemporaryDirectoryURL()
defer { try? manager.removeItem(at: tempDir) }
let uniqueString = ProcessInfo.processInfo.globallyUniqueString
let tempArchiveURL = tempDir.appendingPathComponent(uniqueString)
do { try manager.createParentDirectoryStructure(for: tempArchiveURL) } catch {
throw ArchiveError.unwritableArchive }
guard let tempArchive = Archive(url: tempArchiveURL, accessMode: .create) else {
throw ArchiveError.unwritableArchive
}
progress?.totalUnitCount = self.totalUnitCountForRemoving(entry)
var centralDirectoryData = Data()
var offset = 0
for currentEntry in self {
let centralDirectoryStructure = currentEntry.centralDirectoryStructure
if currentEntry != entry {
let entryStart = Int(currentEntry.centralDirectoryStructure.relativeOffsetOfLocalHeader)
fseek(self.archiveFile, entryStart, SEEK_SET)
let provider: Provider = { (_, chunkSize) -> Data in
return try Data.readChunk(of: Int(chunkSize), from: self.archiveFile)
}
let consumer: Consumer = {
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
_ = try Data.write(chunk: $0, to: tempArchive.archiveFile)
progress?.completedUnitCount += Int64($0.count)
}
_ = try Data.consumePart(of: Int(currentEntry.localSize), chunkSize: Int(bufferSize),
provider: provider, consumer: consumer)
let centralDir = CentralDirectoryStructure(centralDirectoryStructure: centralDirectoryStructure,
offset: UInt32(offset))
centralDirectoryData.append(centralDir.data)
} else { offset = currentEntry.localSize }
}
let startOfCentralDirectory = ftell(tempArchive.archiveFile)
_ = try Data.write(chunk: centralDirectoryData, to: tempArchive.archiveFile)
tempArchive.endOfCentralDirectoryRecord = self.endOfCentralDirectoryRecord
let endOfCentralDirectoryRecord = try
tempArchive.writeEndOfCentralDirectory(centralDirectoryStructure: entry.centralDirectoryStructure,
startOfCentralDirectory: UInt32(startOfCentralDirectory),
operation: .remove)
tempArchive.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
fflush(tempArchive.archiveFile)
try self.replaceCurrentArchiveWithArchive(at: tempArchive.url)
}
// MARK: - Helpers
func uniqueTemporaryDirectoryURL() -> URL {
#if swift(>=5.0) || os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
if let tempDir = try? FileManager().url(for: .itemReplacementDirectory, in: .userDomainMask,
appropriateFor: self.url, create: true) {
return tempDir
}
#endif
return URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(
ProcessInfo.processInfo.globallyUniqueString)
}
func replaceCurrentArchiveWithArchive(at URL: URL) throws {
fclose(self.archiveFile)
let fileManager = FileManager()
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
do {
_ = try fileManager.replaceItemAt(self.url, withItemAt: URL)
} catch {
_ = try fileManager.removeItem(at: self.url)
_ = try fileManager.moveItem(at: URL, to: self.url)
}
#else
_ = try fileManager.removeItem(at: self.url)
_ = try fileManager.moveItem(at: URL, to: self.url)
#endif
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: self.url.path)
self.archiveFile = fopen(fileSystemRepresentation, "rb+")
}
private func writeLocalFileHeader(path: String, compressionMethod: CompressionMethod,
size: (uncompressed: UInt32, compressed: UInt32),
checksum: CRC32,
modificationDateTime: (UInt16, UInt16)) throws -> LocalFileHeader {
// We always set Bit 11 in generalPurposeBitFlag, which indicates an UTF-8 encoded path.
guard let fileNameData = path.data(using: .utf8) else { throw ArchiveError.invalidEntryPath }
let localFileHeader = LocalFileHeader(versionNeededToExtract: UInt16(20), generalPurposeBitFlag: UInt16(2048),
compressionMethod: compressionMethod.rawValue,
lastModFileTime: modificationDateTime.1,
lastModFileDate: modificationDateTime.0, crc32: checksum,
compressedSize: size.compressed, uncompressedSize: size.uncompressed,
fileNameLength: UInt16(fileNameData.count), extraFieldLength: UInt16(0),
fileNameData: fileNameData, extraFieldData: Data())
_ = try Data.write(chunk: localFileHeader.data, to: self.archiveFile)
return localFileHeader
}
private func writeEntry(localFileHeader: LocalFileHeader, type: Entry.EntryType,
compressionMethod: CompressionMethod, bufferSize: UInt32, progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: UInt32, crc32: CRC32) {
var checksum = CRC32(0)
var sizeWritten = UInt32(0)
switch type {
case .file:
switch compressionMethod {
case .none:
(sizeWritten, checksum) = try self.writeUncompressed(size: localFileHeader.uncompressedSize,
bufferSize: bufferSize,
progress: progress, provider: provider)
case .deflate:
(sizeWritten, checksum) = try self.writeCompressed(size: localFileHeader.uncompressedSize,
bufferSize: bufferSize,
progress: progress, provider: provider)
}
case .directory:
_ = try provider(0, 0)
if let progress = progress { progress.completedUnitCount = progress.totalUnitCount }
case .symlink:
(sizeWritten, checksum) = try self.writeSymbolicLink(size: localFileHeader.uncompressedSize,
provider: provider)
if let progress = progress { progress.completedUnitCount = progress.totalUnitCount }
}
return (sizeWritten, checksum)
}
private func writeUncompressed(size: UInt32, bufferSize: UInt32, progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) {
var position = 0
var sizeWritten = 0
var checksum = CRC32(0)
while position < size {
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
let readSize = (Int(size) - position) >= bufferSize ? Int(bufferSize) : (Int(size) - position)
let entryChunk = try provider(Int(position), Int(readSize))
checksum = entryChunk.crc32(checksum: checksum)
sizeWritten += try Data.write(chunk: entryChunk, to: self.archiveFile)
position += Int(bufferSize)
progress?.completedUnitCount = Int64(sizeWritten)
}
return (UInt32(sizeWritten), checksum)
}
private func writeCompressed(size: UInt32, bufferSize: UInt32, progress: Progress? = nil,
provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) {
var sizeWritten = 0
let consumer: Consumer = { data in sizeWritten += try Data.write(chunk: data, to: self.archiveFile) }
let checksum = try Data.compress(size: Int(size), bufferSize: Int(bufferSize),
provider: { (position, size) -> Data in
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
let data = try provider(position, size)
progress?.completedUnitCount += Int64(data.count)
return data
}, consumer: consumer)
return(UInt32(sizeWritten), checksum)
}
private func writeSymbolicLink(size: UInt32, provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) {
let linkData = try provider(0, Int(size))
let checksum = linkData.crc32(checksum: 0)
let sizeWritten = try Data.write(chunk: linkData, to: self.archiveFile)
return (UInt32(sizeWritten), checksum)
}
private func writeCentralDirectoryStructure(localFileHeader: LocalFileHeader, relativeOffset: UInt32,
externalFileAttributes: UInt32) throws -> CentralDirectoryStructure {
let centralDirectory = CentralDirectoryStructure(localFileHeader: localFileHeader,
fileAttributes: externalFileAttributes,
relativeOffset: relativeOffset)
_ = try Data.write(chunk: centralDirectory.data, to: self.archiveFile)
return centralDirectory
}
private func writeEndOfCentralDirectory(centralDirectoryStructure: CentralDirectoryStructure,
startOfCentralDirectory: UInt32,
operation: ModifyOperation) throws -> EndOfCentralDirectoryRecord {
var record = self.endOfCentralDirectoryRecord
let countChange = operation.rawValue
var dataLength = centralDirectoryStructure.extraFieldLength
dataLength += centralDirectoryStructure.fileNameLength
dataLength += centralDirectoryStructure.fileCommentLength
let centralDirectoryDataLengthChange = operation.rawValue * (Int(dataLength) + CentralDirectoryStructure.size)
var updatedSizeOfCentralDirectory = Int(record.sizeOfCentralDirectory)
updatedSizeOfCentralDirectory += centralDirectoryDataLengthChange
let numberOfEntriesOnDisk = UInt16(Int(record.totalNumberOfEntriesOnDisk) + countChange)
let numberOfEntriesInCentralDirectory = UInt16(Int(record.totalNumberOfEntriesInCentralDirectory) + countChange)
record = EndOfCentralDirectoryRecord(record: record, numberOfEntriesOnDisk: numberOfEntriesOnDisk,
numberOfEntriesInCentralDirectory: numberOfEntriesInCentralDirectory,
updatedSizeOfCentralDirectory: UInt32(updatedSizeOfCentralDirectory),
startOfCentralDirectory: startOfCentralDirectory)
_ = try Data.write(chunk: record.data, to: self.archiveFile)
return record
}
private func rollback(_ localFileHeaderStart: Int,
_ existingCentralDirectoryData: Data,
_ endOfCentralDirRecord: EndOfCentralDirectoryRecord) throws {
fflush(self.archiveFile)
ftruncate(fileno(self.archiveFile), off_t(localFileHeaderStart))
fseek(self.archiveFile, localFileHeaderStart, SEEK_SET)
_ = try Data.write(chunk: existingCentralDirectoryData, to: self.archiveFile)
_ = try Data.write(chunk: endOfCentralDirRecord.data, to: self.archiveFile)
}
}
| 62.870056 | 120 | 0.611925 |
87ac9124282bbfbd743a38fb5d14f2ec6e263428 | 4,413 | //
// BatchRequest.swift
// LeanCloud
//
// Created by Tang Tianyong on 3/22/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
class BatchRequest {
let object: LCObject
let method: RESTClient.Method?
let operationTable: OperationTable?
init(object: LCObject, method: RESTClient.Method? = nil, operationTable: OperationTable? = nil) {
self.object = object
self.method = method
self.operationTable = operationTable
}
var isNewborn: Bool {
return !object.hasObjectId
}
var actualMethod: RESTClient.Method {
return method ?? (isNewborn ? .POST : .PUT)
}
var path: String {
var path: String
let APIVersion = RESTClient.APIVersion
switch actualMethod {
case .GET, .PUT, .DELETE:
path = RESTClient.eigenEndpoint(object)!
case .POST:
path = RESTClient.endpoint(object)
}
return "/\(APIVersion)/\(path)"
}
var body: AnyObject {
var body: [String: AnyObject] = [
"__internalId": object.objectId?.value ?? object.internalId
]
var children: [(String, LCObject)] = []
operationTable?.forEach { (key, operation) in
switch operation.name {
case .Set:
/* If object is newborn, put it in __children field. */
if let child = operation.value as? LCObject {
if !child.hasObjectId {
children.append((key, child))
break
}
}
body[key] = operation.JSONValue()
default:
body[key] = operation.JSONValue()
}
}
if children.count > 0 {
var list: [AnyObject] = []
children.forEach { (key, child) in
list.append([
"className": child.actualClassName,
"cid": child.internalId,
"key": key
])
}
body["__children"] = list
}
return body
}
func JSONValue() -> AnyObject {
let method = actualMethod
var request: [String: AnyObject] = [
"path": path,
"method": method.rawValue
]
switch method {
case .GET:
break
case .POST, .PUT:
request["body"] = body
if isNewborn {
request["new"] = true
}
case .DELETE:
break
}
return request
}
}
class BatchRequestBuilder {
/**
Get a list of requests of an object.
- parameter object: The object from which you want to get.
- returns: A list of request.
*/
static func buildRequests(object: LCObject) -> [BatchRequest] {
return operationTableList(object).map { element in
BatchRequest(object: object, operationTable: element)
}
}
/**
Get initial operation table list of an object.
- parameter object: The object from which to get.
- returns: The operation table list.
*/
private static func initialOperationTableList(object: LCObject) -> OperationTableList {
var operationTable: OperationTable = [:]
/* Collect all non-null properties. */
object.forEach { (key, value) in
switch value {
case let relation as LCRelation:
/* If the property type is relation,
We should use "AddRelation" instead of "Set" as operation type.
Otherwise, the relations will added as an array. */
operationTable[key] = Operation(name: .AddRelation, key: key, value: LCArray(relation.value))
default:
operationTable[key] = Operation(name: .Set, key: key, value: value)
}
}
return [operationTable]
}
/**
Get operation table list of object.
- parameter object: The object from which you want to get.
- returns: A list of operation tables.
*/
private static func operationTableList(object: LCObject) -> OperationTableList {
if object.hasObjectId {
return object.operationHub.operationTableList()
} else {
return initialOperationTableList(object)
}
}
} | 26.908537 | 109 | 0.542941 |
4b023f7c2bae877b8bc87146f28734d780d87577 | 2,291 | import Foundation
import azureSwiftRuntime
public protocol ApplicationGatewaysListAvailableSslOptions {
var headerParameters: [String: String] { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (ApplicationGatewayAvailableSslOptionsProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.ApplicationGateways {
// ListAvailableSslOptions lists available Ssl options for configuring Ssl policy.
internal class ListAvailableSslOptionsCommand : BaseCommand, ApplicationGatewaysListAvailableSslOptions {
public var subscriptionId : String
public var apiVersion = "2018-01-01"
public init(subscriptionId: String) {
self.subscriptionId = subscriptionId
super.init()
self.method = "Get"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(ApplicationGatewayAvailableSslOptionsData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (ApplicationGatewayAvailableSslOptionsProtocol?, Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(result: ApplicationGatewayAvailableSslOptionsData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 45.82 | 132 | 0.657791 |
4852052ec47901f5fce6c1007d64b66ca8c35257 | 6,253 | import XCTest
class SentrySpanTests: XCTestCase {
private class Fixture {
let someTransaction = "Some Transaction"
let someOperation = "Some Operation"
let someDescription = "Some Description"
let extraKey = "extra_key"
let extraValue = "extra_value"
let options: Options
init() {
options = Options()
options.dsn = TestConstants.dsnAsString(username: "username")
options.environment = "test"
}
func getSut() -> Span {
return getSut(client: TestClient(options: options)!)
}
func getSut(client: Client) -> Span {
let hub = SentryHub(client: client, andScope: nil, andCrashAdapter: TestSentryCrashWrapper())
return hub.startTransaction(name: someTransaction, operation: someOperation)
}
}
private var fixture: Fixture!
override func setUp() {
let testDataProvider = TestCurrentDateProvider()
CurrentDate.setCurrentDateProvider(testDataProvider)
testDataProvider.setDate(date: TestData.timestamp)
fixture = Fixture()
}
func testInitAndCheckForTimestamps() {
let span = fixture.getSut()
XCTAssertNotNil(span.startTimestamp)
XCTAssertNil(span.timestamp)
XCTAssertFalse(span.isFinished)
}
func testFinish() {
let client = TestClient(options: fixture.options)!
let span = fixture.getSut(client: client)
span.finish()
XCTAssertEqual(span.startTimestamp, TestData.timestamp)
XCTAssertEqual(span.timestamp, TestData.timestamp)
XCTAssertTrue(span.isFinished)
let lastEvent = client.captureEventWithScopeArguments[0].event
XCTAssertEqual(lastEvent.transaction, fixture.someTransaction)
XCTAssertEqual(lastEvent.timestamp, TestData.timestamp)
XCTAssertEqual(lastEvent.startTimestamp, TestData.timestamp)
XCTAssertEqual(lastEvent.type, SentryEnvelopeItemTypeTransaction)
}
func testFinishWithStatus() {
let span = fixture.getSut()
span.finish(status: .ok)
XCTAssertEqual(span.startTimestamp, TestData.timestamp)
XCTAssertEqual(span.timestamp, TestData.timestamp)
XCTAssertEqual(span.context.status, .ok)
XCTAssertTrue(span.isFinished)
}
func testFinishWithChild() {
let client = TestClient(options: fixture.options)!
let span = fixture.getSut(client: client)
let childSpan = span.startChild(operation: fixture.someOperation)
span.finish()
let lastEvent = client.captureEventWithScopeArguments[0].event
let serializedData = lastEvent.serialize()
let spans = serializedData["spans"] as! [Any]
let serializedChild = spans[0] as! [String: Any]
XCTAssertEqual(serializedChild["span_id"] as? String, childSpan.context.spanId.sentrySpanIdString)
XCTAssertEqual(serializedChild["parent_span_id"] as? String, span.context.spanId.sentrySpanIdString)
}
func testStartChildWithNameOperation() {
let span = fixture.getSut()
let childSpan = span.startChild(operation: fixture.someOperation)
XCTAssertEqual(childSpan.context.parentSpanId, span.context.spanId)
XCTAssertEqual(childSpan.context.operation, fixture.someOperation)
XCTAssertNil(childSpan.context.spanDescription)
}
func testStartChildWithNameOperationAndDescription() {
let span = fixture.getSut()
let childSpan = span.startChild(operation: fixture.someOperation, description: fixture.someDescription)
XCTAssertEqual(childSpan.context.parentSpanId, span.context.spanId)
XCTAssertEqual(childSpan.context.operation, fixture.someOperation)
XCTAssertEqual(childSpan.context.spanDescription, fixture.someDescription)
}
func testSetExtras() {
let span = fixture.getSut()
span.setExtra(value: fixture.extraValue, key: fixture.extraKey)
XCTAssertEqual(span.data!.count, 1)
XCTAssertEqual(span.data![fixture.extraKey] as! String, fixture.extraValue)
}
func testSerialization() {
let span = fixture.getSut()
span.setExtra(value: fixture.extraValue, key: fixture.extraKey)
span.finish()
let serialization = span.serialize()
XCTAssertEqual(serialization["span_id"] as? String, span.context.spanId.sentrySpanIdString)
XCTAssertEqual(serialization["trace_id"] as? String, span.context.traceId.sentryIdString)
XCTAssertEqual(serialization["timestamp"] as? String, TestData.timestampAs8601String)
XCTAssertEqual(serialization["start_timestamp"] as? String, TestData.timestampAs8601String)
XCTAssertEqual(serialization["type"] as? String, SpanContext.type)
XCTAssertEqual(serialization["sampled"] as? String, "false")
XCTAssertNotNil(serialization["data"])
XCTAssertEqual((serialization["data"] as! Dictionary)[fixture.extraKey], fixture.extraValue)
}
@available(tvOS 10.0, *)
@available(OSX 10.12, *)
@available(iOS 10.0, *)
func testModifyingTagsFromMultipleThreads() {
let queue = DispatchQueue(label: "SentrySpanTests", qos: .userInteractive, attributes: [.concurrent, .initiallyInactive])
let group = DispatchGroup()
let span = fixture.getSut()
// The number is kept small for the CI to not take to long.
// If you really want to test this increase to 100_000 or so.
let innerLoop = 1_000
let outerLoop = 20
let value = fixture.extraValue
for i in 0..<outerLoop {
group.enter()
queue.async {
for j in 0..<innerLoop {
span.setExtra(value: value, key: "\(i)-\(j)")
}
group.leave()
}
}
queue.activate()
group.wait()
XCTAssertEqual(span.data!.count, outerLoop * innerLoop)
}
}
| 37.89697 | 129 | 0.641292 |
2fb2b6b895a78946de52bf63210f53d019725910 | 1,066 | /*
* Copyright (c) 2019 Telekom Deutschland AG
*
* 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 MicroBlink
public class SloveniaIDBackCardResult: IDCardResult {
public var authority: String?
public var rawDateOfIssue: String?
public var dateOfIssue: Date?
init(with result: MBSloveniaIdBackRecognizerResult) {
super.init()
self.address = result.address
self.authority = result.authority
self.rawDateOfIssue = result.rawDateOfIssue
self.dateOfIssue = result.dateOfIssue
}
}
| 30.457143 | 74 | 0.719512 |
f8a58929b3bbf2699832d34a13db50fac8f95179 | 5,653 | //
// PlannerViewModel.swift
// VacationPlanner
//
// Created by John Kennedy Martins Alves on 09/02/19.
// Copyright © 2019 John Kennedy Martins Alves. All rights reserved.
//
import Foundation
protocol PlannerViewModelDelegate: class {
func handleErrorWith(msg: String)
func onDailyClimatesReceived()
func updatePlannerData()
func allInfoIs(ready: Bool)
}
class PlannerViewModel {
private let TIMEOUT_SECONDS = 10
private let ERROR_MSG = "Um Erro aconteceu ao recuperar os dados"
private var selectedWeathers: [WeatherViewModel] = [WeatherViewModel]()
private var dailyClimateList: [DailyClimate]?
private var selectedCity: CityViewModel?
private var daysOfVacation: String = ""
private var selectedYear: String = ""
private var weatherList: [Weather]?
private var cityList: [City]?
private var apiPlanner: VacationPlannerAPI
private var managerPlannerBusiness: PlannerBusinessManager
private var errorGetCities = false
private var errorGetWeathers = false
private let dispatchGroup = DispatchGroup()
// MARK: - Public Atributes
weak var delegate: PlannerViewModelDelegate?
var cityViewModelList: [CityViewModel] {
guard let list = cityList else { return [CityViewModel]() }
return list.map { CityViewModel(model: $0) }
}
var weartherViewModelList: [WeatherViewModel] {
guard let list = weatherList else { return [WeatherViewModel]() }
return list.map { WeatherViewModel(model: $0) }
}
var dailyClimateViewModelList: [DailyClimateViewModel] {
guard let list = dailyClimateList else { return [DailyClimateViewModel]() }
return list.map { DailyClimateViewModel(model: $0) }
}
//MARK: - Init
init(api: VacationPlannerAPI = VacationPlannerAPI(), manager: PlannerBusinessManager = PlannerBusinessManager()) {
apiPlanner = api
managerPlannerBusiness = manager
}
// MARK: - Public Functions
func addSelectedWeather(from index: Int) {
selectedWeathers.append(weartherViewModelList[index])
}
func changeSelectedCity(from index: Int) {
selectedCity = cityViewModelList[index]
}
func removeSelectedWeather(from index: Int) {
selectedWeathers = selectedWeathers.filter { $0.id != weartherViewModelList[index].id }
}
func getVacationDatesFormated() -> String {
guard let days = Int(daysOfVacation) else { return ""}
return managerPlannerBusiness.getDatesFormated(from: dailyClimateViewModelList, with: days, selectedWeathers: selectedWeathers)
}
func validateYear(_ year: String) -> Bool {
selectedYear = year
return managerPlannerBusiness.validate(year: year)
}
func validateDaysOfVacation(_ days: String) -> Bool {
daysOfVacation = days
return managerPlannerBusiness.validate(days: days)
}
func validateEnteredInfo() {
if let del = delegate {
del.allInfoIs(ready: validateYear(selectedYear)
&& validateDaysOfVacation(daysOfVacation)
&& selectedCity != nil && !selectedWeathers.isEmpty)
}
}
func getPlannerInfo() {
getCities()
getWeathers()
handleDispatchGroup()
}
func getDailyClimates() {
guard let cityVM = selectedCity, !selectedYear.isEmpty else { return }
apiPlanner.getDailyClimates(year: selectedYear, woeId: cityVM.woeId) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let listDailyClimate):
self.dailyClimateList = listDailyClimate
if let del = self.delegate { del.onDailyClimatesReceived() }
case .error(let errorMsg):
if let del = self.delegate { del.handleErrorWith(msg: errorMsg) }
}
}
}
// MARK: - Private Functions
private func getCities() {
dispatchGroup.enter()
apiPlanner.getCities() { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let listOfCities):
self.cityList = listOfCities
self.errorGetCities = false
case .error(_):
self.errorGetCities = true
}
self.dispatchGroup.leave()
}
}
private func getWeathers() {
dispatchGroup.enter()
apiPlanner.getWeathers() { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let listOfWeathers):
self.weatherList = listOfWeathers
self.errorGetWeathers = false
case .error(_):
self.errorGetWeathers = true
}
self.dispatchGroup.leave()
}
}
private func handleDispatchGroup() {
let timeout = DispatchTime.now() + .seconds(TIMEOUT_SECONDS)
if dispatchGroup.wait(timeout: timeout) == .timedOut {
delegate?.handleErrorWith(msg: ERROR_MSG)
}
dispatchGroup.notify(queue: DispatchQueue.main) { [weak self] in
guard let self = self else { return }
if self.errorGetCities || self.errorGetWeathers {
self.delegate?.handleErrorWith(msg: self.ERROR_MSG)
} else {
self.delegate?.updatePlannerData()
}
}
}
}
| 33.05848 | 135 | 0.615602 |
1a0b1451889bed047538dd9f4899fc781302379f | 1,783 | import Foundation
import TSCBasic
import TuistCore
import TuistGraph
import TuistGraphTesting
import TuistSupport
import XCTest
@testable import ProjectDescription
@testable import TuistLoader
@testable import TuistLoaderTesting
@testable import TuistSupportTesting
final class DependenciesModelLoaderTests: TuistUnitTestCase {
private var manifestLoader: MockManifestLoader!
private var subject: DependenciesModelLoader!
override func setUp() {
super.setUp()
manifestLoader = MockManifestLoader()
subject = DependenciesModelLoader(manifestLoader: manifestLoader)
}
override func tearDown() {
subject = nil
manifestLoader = nil
super.tearDown()
}
func test_loadDependencies() throws {
// Given
let stubbedPath = try temporaryPath()
manifestLoader.loadDependenciesStub = { _ in
Dependencies([
.carthage(origin: .github(path: "Dependency1"), requirement: .exact("1.1.1"), platforms: [.iOS]),
.carthage(origin: .git(path: "Dependency1"), requirement: .exact("2.3.4"), platforms: [.macOS, .tvOS]),
])
}
// When
let model = try subject.loadDependencies(at: stubbedPath)
// Then
let expectedCarthageModels: [TuistGraph.CarthageDependency] = [
CarthageDependency(origin: .github(path: "Dependency1"), requirement: .exact("1.1.1"), platforms: Set([.iOS])),
CarthageDependency(origin: .git(path: "Dependency1"), requirement: .exact("2.3.4"), platforms: Set([.macOS, .tvOS])),
]
let expectedDependenciesModel = TuistGraph.Dependencies(carthageDependencies: expectedCarthageModels)
XCTAssertEqual(model, expectedDependenciesModel)
}
}
| 31.839286 | 129 | 0.675827 |
20b7076a30a0400e4947adcdc4f215e8aa281f53 | 6,872 | //
// EditProfileService.swift
// Instagram
//
// Created by Владимир Юшков on 30.01.2022.
//
import Foundation
import Firebase
struct EditProfileService {
static func updateUserProfileImage(currentUser: User, editedProfile: EditProfileModel, compleation: @escaping (String?) -> ()) {
let currentUserUid = currentUser.uid
if let profileImage = editedProfile.profileImage {
ImageUploader.uploadImage(image: profileImage) { profileImageURL in
updateProfileImageInUserProfile(for: currentUserUid, with: profileImageURL)
updateProfileImageInPosts(for: currentUserUid, with: profileImageURL)
updateProfileImageInNotifications(for: currentUserUid, with: profileImageURL)
updateProfileImageInComments(for: currentUserUid, with: profileImageURL)
compleation(profileImageURL)
print("DEBUG 1 profile Photo has been updated")
}
}
if let fullname = editedProfile.fullname {
COLLECTION_USERS.document(currentUserUid).updateData(["fullname": fullname])
if editedProfile.profileImage == nil { compleation(nil) }
print("DEBUG 2 profile Fullname has been updated")
}
if let username = editedProfile.username {
updateUsernameInProfile(for: currentUserUid, with: username)
updateUsernameInPosts(for: currentUserUid, with: username)
updateUsernameInNotifications(for: currentUserUid, with: username)
updateUsernameInComments(for: currentUserUid, with: username)
if editedProfile.profileImage == nil { compleation(nil) }
print("DEBUG 3 profile Username has been updated")
}
}
private static func updateProfileImageInUserProfile(for userUid: String, with imageUrl: String) {
COLLECTION_USERS.document(userUid).updateData(["profileImageUrl": imageUrl])
}
private static func updateProfileImageInPosts(for userUid: String, with imageUrl: String) {
let postQuery = COLLECTION_POSTS.whereField("ownerUid", isEqualTo: userUid)
postQuery.getDocuments { snapshot, error in
guard let documents = snapshot?.documents else { return }
documents.forEach { COLLECTION_POSTS.document($0.documentID).updateData(["ownerImageUrl" : imageUrl]) }
}
}
private static func updateProfileImageInNotifications(for userUid: String, with imageUrl: String) {
COLLECTION_NOTIFICATIONS.getDocuments { snapshot, error in
guard let documents = snapshot?.documents else { return }
documents.forEach { document in
if document.documentID != userUid {
let notificationQuery = COLLECTION_NOTIFICATIONS.document(document.documentID).collection("user-notifications").whereField("uid", isEqualTo: userUid)
notificationQuery.getDocuments { snapshot, error in
guard let documents = snapshot?.documents else { return }
documents.forEach {
COLLECTION_NOTIFICATIONS.document(document.documentID).collection("user-notifications").document($0.documentID).updateData(["userProfileImageUrl": imageUrl])
}
}
}
}
}
}
private static func updateProfileImageInComments(for userUid: String, with imageUrl: String) {
COLLECTION_POSTS.getDocuments { snapshot, _ in
guard let documents = snapshot?.documents else { return }
documents.forEach { post in
let commentsQuery = COLLECTION_POSTS.document(post.documentID).collection("comments").whereField("uid", isEqualTo: userUid)
commentsQuery.getDocuments { snapshot, _ in
guard let documents = snapshot?.documents else { return }
documents.forEach { comment in
COLLECTION_POSTS.document(post.documentID).collection("comments").document(comment.documentID).updateData(["profileImageUrl": imageUrl])
}
}
}
}
}
private static func updateUsernameInProfile(for userUid: String, with username: String) {
COLLECTION_USERS.document(userUid).updateData(["username": username])
}
private static func updateUsernameInPosts(for userUid: String, with username: String) {
let postQuery = COLLECTION_POSTS.whereField("ownerUid", isEqualTo: userUid)
postQuery.getDocuments { snapshot, error in
guard let documents = snapshot?.documents else { return }
documents.forEach { COLLECTION_POSTS.document($0.documentID).updateData(["ownerUserName" : username]) }
}
}
private static func updateUsernameInNotifications(for userUid: String, with username: String) {
COLLECTION_NOTIFICATIONS.getDocuments { snapshot, error in
guard let documents = snapshot?.documents else { return }
documents.forEach { document in
if document.documentID != userUid {
let notificationQuery = COLLECTION_NOTIFICATIONS.document(document.documentID).collection("user-notifications").whereField("uid", isEqualTo: userUid)
notificationQuery.getDocuments { snapshot, error in
guard let documents = snapshot?.documents else { return }
documents.forEach {
COLLECTION_NOTIFICATIONS.document(document.documentID).collection("user-notifications").document($0.documentID).updateData(["username": username])
}
}
}
}
}
}
private static func updateUsernameInComments(for userUid: String, with username: String) {
COLLECTION_POSTS.getDocuments { snapshot, _ in
guard let documents = snapshot?.documents else { return }
documents.forEach { post in
let commentsQuery = COLLECTION_POSTS.document(post.documentID).collection("comments").whereField("uid", isEqualTo: userUid)
commentsQuery.getDocuments { snapshot, _ in
guard let documents = snapshot?.documents else { return }
documents.forEach { comment in
COLLECTION_POSTS.document(post.documentID).collection("comments").document(comment.documentID).updateData(["username": username])
}
}
}
}
}
}
| 46.748299 | 185 | 0.615832 |
1d48a4ec4dbefc38fbfe461140337b0863d6613e | 3,647 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
// swift-tools-version:4.0
//
// swift-tools-version:4.0
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Network)
import Foundation
import NIO
import NIOConcurrencyHelpers
import Dispatch
import Network
/// An `EventLoopGroup` containing `EventLoop`s specifically designed for use with
/// Network.framework's post-sockets networking API.
///
/// These `EventLoop`s provide highly optimised and powerful networking tools for
/// the Darwin platforms. They have a number of advantages over the regular
/// `SelectableEventLoop` that NIO uses on other platforms. In particular:
///
/// - The use of `DispatchQueue`s to schedule tasks allows the Darwin kernels to make
/// intelligent scheduling decisions, as well as to maintain QoS and ensure that
/// tasks required to handle networking in your application are given appropriate
/// priority by the system.
/// - Network.framework provides powerful tools for observing network state and managing
/// connections on devices with highly fluid networking environments, such as laptops
/// and mobile devices. These tools can be exposed to `Channel`s using this backend.
/// - Network.framework brings the networking stack into userspace, reducing the overhead
/// of most network operations by removing syscalls, and greatly increasing the safety
/// and security of the network stack.
/// - The applications networking needs are more effectively communicated to the kernel,
/// allowing mobile devices to change radio configuration and behaviour as needed to
/// take advantage of the various interfaces available on mobile devices.
///
/// In general, when building applications whose primary purpose is to be deployed on Darwin
/// platforms, the `NIOTSEventLoopGroup` should be preferred over the
/// `MultiThreadedEventLoopGroup`. In particular, on iOS, the `NIOTSEventLoopGroup` is the
/// preferred networking backend.
public final class NIOTSEventLoopGroup: EventLoopGroup {
private let index = Atomic<Int>(value: 0)
private let eventLoops: [NIOTSEventLoop]
public init(loopCount: Int = 1, defaultQoS: DispatchQoS = .default) {
precondition(loopCount > 0)
self.eventLoops = (0..<loopCount).map { _ in NIOTSEventLoop(qos: defaultQoS) }
}
public func next() -> EventLoop {
return self.eventLoops[abs(index.add(1) % self.eventLoops.count)]
}
/// Shuts down all of the event loops, rendering them unable to perform further work.
public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) {
let g = DispatchGroup()
let q = DispatchQueue(label: "nio.transportservices.shutdowngracefullyqueue", target: queue)
var error: Error? = nil
for loop in self.eventLoops {
g.enter()
loop.closeGently().recover { err in
q.sync { error = err }
}.whenComplete { (_: Result<Void, Error>) in
g.leave()
}
}
g.notify(queue: q) {
callback(error)
}
}
public func makeIterator() -> EventLoopIterator {
return EventLoopIterator(self.eventLoops)
}
}
#endif
| 41.443182 | 100 | 0.675898 |
38565d5c11cf257f7c68aee5537aa346487737f0 | 1,809 | //
// ExtensionDictionary.swift
// GGITCommon iOS
//
// Created by Kelvin Leong on 14/09/2018.
// Copyright © 2018 Grace Generation Information Technology. All Rights Reserved. All rights reserved.
//
import Foundation
extension Dictionary {
/**
Dictionary extension - convert dictionary to json
### Usage Example: ###
```swift
import GGITCommon
...
Dictionary.json
```
*/
public var json: String {
let invalidJson = "Not a valid JSON"
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson
} catch {
return invalidJson
}
}
public func getKeys() -> [String]{
var keys = [String?](repeating: nil, count:self.count)
for (key, value) in self{
keys[value as! Int] = key as? String
}
return keys as! [String]
}
mutating func merge<K, V>(dictionaries: Dictionary<K, V>...) {
for dict in dictionaries {
for (key, value) in dict {
self.updateValue(value as! Value, forKey: key as! Key)
}
}
}
}
extension NSDictionary {
// var data:Data? {
// guard let data = try? PropertyListSerialization.data(fromPropertyList: self, format: PropertyListSerialization.PropertyListFormat.binary, options: 0) else {return nil}
//
// return data
// }
public var data: Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return jsonData
} catch {
return nil
}
}
}
| 26.217391 | 181 | 0.566611 |
e99402cdd95ac0a2213013afdd8744d4f8227857 | 1,117 | //
// CLDataPickerTitleView.swift
// CLDemo
//
// Created by JmoVxia on 2020/4/7.
// Copyright © 2020 JmoVxia. All rights reserved.
//
import UIKit
class CLDataPickerTitleView: UIView {
var text: String? {
didSet {
titleLabel.text = text
}
}
var margin: CGFloat = 0.0{
didSet {
titleLabel.snp.updateConstraints { (make) in
make.left.equalTo(self.snp.centerX).offset(margin)
}
}
}
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.textAlignment = .right
titleLabel.textColor = .themeColor
titleLabel.font = UIFont.systemFont(ofSize: 14)
return titleLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.snp.centerX).offset(0)
make.top.bottom.equalToSuperview()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 25.976744 | 66 | 0.591764 |
79ed84ace9e6c6492aa53546a8c543a2f86a0452 | 336 | //
// ViewController.swift
// Mach-SwiftDemo-iOS
//
// Created by Daisuke T on 2019/04/10.
// Copyright © 2019 Mach-SwiftDemo-iOS. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Common.machTest()
}
}
| 15.272727 | 61 | 0.616071 |
76bd8ce54f141de1f4863cc7f51de771b9f1fb57 | 1,696 | //
// OtherElementsScreen.swift
// TABTestKit_ExampleUITests
//
// Created by Kane Cheshire on 11/09/2019.
// Copyright © 2019 The App Business LTD. All rights reserved.
//
import TABTestKit
let otherElementsScreen = OtherElementsScreen()
struct OtherElementsScreen: Screen {
let trait = Header(id: "Other elements")
let scrollView = ScrollView(id: "MyScrollView") // In iOS 13, XCUI matches a hidden scroll view when the keyboard is showing :(
let label = Label(id: "Example label")
let button = Button(id: "Example button")
let segmentedControl = SegmentedControl(parent: View(id: "ExampleSegmentedControl"))
let textField = TextField(id: "ExampleTextField")
let numberPadTextField = TextField(id: "NumberPadTextField")
let decimalPadTextField = TextField(id: "DecimalPadTextField")
let emailAddressTextField = TextField(id: "EmailAddressTextField")
let numbersAndPunctuationTextField = TextField(id: "NumbersAndPunctuationTextField")
let phonePadTextField = TextField(id: "PhonePadTextField")
let twitterTextField = TextField(id: "TwitterTextField")
let urlTextField = TextField(id: "URLTextField")
let webSearchTextField = TextField(id: "WebSearchTextField")
let secureTextField = SecureTextField(id: "ExampleSecureTextField")
let slider = Slider(id: "ExampleSlider")
let toggle = Switch(id: "ExampleSwitch")
let stepper = Stepper(id: "ExampleStepper")
let pageIndicator = PageIndicator(id: "ExamplePageControl")
let picker = Picker(id: "ExamplePicker")
let shareSheet = ActivitySheet()
}
extension OtherElementsScreen: Scrollable {
func scroll(_ direction: ElementAttributes.Direction) {
scrollView.scroll(direction)
}
}
| 36.869565 | 129 | 0.757075 |
713855467281ccdf2212de136d043ec9ea521dab | 3,907 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
enum TemplateASTNode {
case blockNode(Block) // {{$ name }}...{{/ name }}
case partialOverrideNode(PartialOverride) // {{< name }}...{{/ name }}
case partialNode(Partial) // {{> name }}
case sectionNode(Section) // {{# name }}...{{/ name }}, {{^ name }}...{{/ name }}
case textNode(String) // text
case variableNode(Variable) // {{ name }}, {{{ name }}}, {{& name }}
// Define structs instead of long tuples
struct Block {
// {{$ name }}innerTemplateAST{{/ name }}
let innerTemplateAST: TemplateAST
let name: String
}
struct PartialOverride {
// {{< parentPartial }}childTemplateAST{{/ parentPartial }}
let childTemplateAST: TemplateAST
let parentPartial: Partial
}
struct Partial {
let templateAST: TemplateAST
let name: String?
}
struct Section {
let tag: SectionTag
let expression: Expression
let inverted: Bool
}
struct Variable {
let tag: VariableTag
let expression: Expression
let escapesHTML: Bool
}
// Factory methods
static func block(innerTemplateAST: TemplateAST, name: String) -> TemplateASTNode {
return .blockNode(Block(innerTemplateAST: innerTemplateAST, name: name))
}
static func partialOverride(childTemplateAST: TemplateAST, parentTemplateAST: TemplateAST, parentPartialName: String? = nil) -> TemplateASTNode {
return .partialOverrideNode(PartialOverride(childTemplateAST: childTemplateAST, parentPartial: Partial(templateAST: parentTemplateAST, name: parentPartialName)))
}
static func partial(templateAST: TemplateAST, name: String?) -> TemplateASTNode {
return .partialNode(Partial(templateAST: templateAST, name: name))
}
static func section(templateAST: TemplateAST, expression: Expression, inverted: Bool, openingToken: TemplateToken, innerTemplateString: String) -> TemplateASTNode {
let tag = SectionTag(innerTemplateAST: templateAST, openingToken: openingToken, innerTemplateString: innerTemplateString)
return .sectionNode(Section(tag: tag, expression: expression, inverted: inverted))
}
static func text(text: String) -> TemplateASTNode {
return .textNode(text)
}
static func variable(expression: Expression, contentType: ContentType, escapesHTML: Bool, token: TemplateToken) -> TemplateASTNode {
let tag = VariableTag(contentType: contentType, token: token)
return .variableNode(Variable(tag: tag, expression: expression, escapesHTML: escapesHTML))
}
}
| 41.126316 | 169 | 0.671871 |
2384d24a1549145e4822f7d2cf0f6661e40301c6 | 588 | //
// Created by Alexey Korolev on 29.06.2018.
// Copyright (c) 2018 Alpha Troya. All rights reserved.
//
import Foundation
import Moya
final class MockRequest: RequestType {
var request: URLRequest?
func authenticate(user _: String, password _: String, persistence _: URLCredential.Persistence) -> MockRequest {
fatalError("authenticate(user:password:persistence:) has not been implemented")
}
func authenticate(usingCredential _: URLCredential) -> MockRequest {
fatalError("authenticate(credential:) has not been implemented")
}
init() {}
}
| 26.727273 | 116 | 0.712585 |
4a1d199d82df23bdbe2059c8c19826b156929629 | 31,495 | //
// RestaurantMonth.swift
// SpotShare
//
// Created by 김희중 on 18/11/2019.
// Copyright © 2019 김희중. All rights reserved.
//
import UIKit
import Cosmos
import Firebase
import GoogleMaps
import SDWebImage
// https://github.com/ink-spot/UPCarouselFlowLayout
// https://github.com/evgenyneu/Cosmos/blob/master/README.md
// https://github.com/SDWebImage/SDWebImage
class RestaurantMonthController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
deinit {
print("no retain cycle in RestaurantMonthController")
}
fileprivate let cellid = "cellid"
fileprivate let cellPercentWidth: CGFloat = 0.7
// https://github.com/ink-spot/UPCarouselFlowLayout
let backGroundImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "restMonth_mask")
iv.layer.masksToBounds = true
iv.contentMode = .scaleAspectFill
return iv
}()
lazy var backImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "back")
iv.contentMode = .scaleAspectFit
iv.isUserInteractionEnabled = true
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(goBack)))
return iv
}()
let TitleLabel: UILabel = {
let lb = UILabel()
// letter spacing -0.5
lb.letterSpacing(text: "Restaurant of the Month", spacing: -0.5)
lb.font = UIFont(name: "DMSans-Medium", size: 28)
lb.textColor = .darkGray
lb.textAlignment = .center
lb.numberOfLines = 0
return lb
}()
let restDate: UILabel = {
let lb = UILabel()
// letter spacing -0.1
lb.letterSpacing(text: "June 2019", spacing: -0.1)
lb.font = UIFont(name: "DMSans-Regular", size: 16)
lb.textColor = .gray
lb.textAlignment = .center
lb.numberOfLines = 0
return lb
}()
// https://github.com/ink-spot/UPCarouselFlowLayout
let flowLayout = UPCarouselFlowLayout()
lazy var innerCollectionview: UICollectionView = {
flowLayout.scrollDirection = .horizontal
flowLayout.spacingMode = UPCarouselFlowLayoutSpacingMode.fixed(spacing: 30)
flowLayout.sideItemScale = 0.9
let collectionview = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
collectionview.delegate = self
collectionview.dataSource = self
collectionview.alwaysBounceHorizontal = true
collectionview.showsHorizontalScrollIndicator = false
collectionview.backgroundColor = .clear
return collectionview
}()
let pageIndicator: UILabel = {
let lb = UILabel()
lb.font = UIFont(name: "DMSans-Regular", size: 16)
lb.textColor = .gray
lb.textAlignment = .center
lb.numberOfLines = 0
return lb
}()
fileprivate var pageSize: CGSize {
let layout = self.innerCollectionview.collectionViewLayout as! UPCarouselFlowLayout
var pageSize = layout.itemSize
if layout.scrollDirection == .horizontal {
pageSize.width += layout.minimumLineSpacing
} else {
pageSize.height += layout.minimumLineSpacing
}
return pageSize
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// swipe로 back 구현하려면 두개 다 써줘야함.
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
setupLayouts()
innerCollectionview.register(innerRestMonthCell.self, forCellWithReuseIdentifier: cellid)
getResMonth_firebase()
}
var resInfos = [ResInfoModel]()
var checkOpen = [Bool]()
fileprivate func getResMonth_firebase() {
let ref = Database.database().reference().child("추천")
ref.observe(.childAdded, with: { [weak self] (snapshot) in
let snapid = snapshot.key
let magazineReference = Database.database().reference().child("맛집").child(snapid)
magazineReference.observeSingleEvent(of: .value, with: { [weak self] (snapshot) in
if let dictionary = snapshot.value as? [String:Any] {
let resInfo = ResInfoModel()
// 주석한 부분은 그 다음 RestaurantViewController 넘어갈때 추가로 데이터 받아오기
// 그래야 각각 데이터 가져오는데 시간이 빠르고 효율적일듯.
resInfo.resName = dictionary["resName"] as? String
resInfo.starPoint = dictionary["resPoints"] as? Double
guard let lat = (dictionary["lat"] as? CLLocationDegrees) else {return}
guard let long = (dictionary["long"] as? CLLocationDegrees) else {return}
resInfo.resLocation = CLLocationCoordinate2D(latitude: lat, longitude: long)
resInfo.locationText = (dictionary["location"] as? String)
resInfo.toilet = dictionary["toilet"] as? String
// 해당 맛집에서 첫번째 이미지 따오기.
let magazineReference = Database.database().reference().child("맛집").child(snapid).child("FirstResimage")
magazineReference.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String:Any] {
resInfo.resImageUrl = dictionary["url"] as? String
}
})
// 해당 맛집에서 hashtag 따오기
let ref = Database.database().reference().child("맛집").child(snapid).child("hashTag")
ref.observeSingleEvent(of: .value) { [weak self] (snapshot) in
if let dictionary = snapshot.value as? [String:Any] {
// 만약 hashTag가 DB에 없다면 결국 최종 append가 안된다고 생각.
resInfo.hash1 = dictionary["hash1"] as? String ?? ""
resInfo.hash2 = dictionary["hash2"] as? String ?? ""
resInfo.hash3 = dictionary["hash3"] as? String ?? ""
resInfo.hash4 = dictionary["hash4"] as? String ?? ""
resInfo.hash5 = dictionary["hash5"] as? String ?? ""
self?.checkOpen.append(false)
self?.resInfos.append(resInfo)
}
DispatchQueue.main.async {
self?.innerCollectionview.reloadData()
}
}
}
}, withCancel: { (err) in
print("Failed to fetch resMonthData:", err)
})
}, withCancel: { (err) in
print("Failed to fetch all resMonthDatas:", err)
})
}
var backGroundImageViewConstraint: NSLayoutConstraint?
var backImageViewConstraint: NSLayoutConstraint?
var innerCollectionviewConstraint: NSLayoutConstraint?
var TitleLabelConstraint: NSLayoutConstraint?
var restDateConstraint: NSLayoutConstraint?
var pageIndicatorConstraint: NSLayoutConstraint?
var cosmosViewConstraint: NSLayoutConstraint?
fileprivate func setupLayouts() {
view.addSubview(backGroundImageView)
view.addSubview(backImageView)
view.addSubview(TitleLabel)
view.addSubview(restDate)
view.addSubview(innerCollectionview)
view.addSubview(pageIndicator)
if #available(iOS 11.0, *) {
// iphone se,7,8 etc
if view.frame.height < 800 {
let height: CGFloat = 430
self.flowLayout.itemSize = setCellImageWidth(height: height)
backGroundImageViewConstraint = backGroundImageView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0).first
backImageViewConstraint = backImageView.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 16, leftConstant: 24, bottomConstant: 0, rightConstant: 0, widthConstant: 24, heightConstant: 24).first
TitleLabelConstraint = TitleLabel.anchor(backImageView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 10, leftConstant: 100, bottomConstant: 0, rightConstant: 100, widthConstant: 0, heightConstant: 84).first
restDateConstraint = restDate.anchor(TitleLabel.bottomAnchor, left: TitleLabel.leftAnchor, bottom: nil, right: TitleLabel.rightAnchor, topConstant: 6, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 26).first
innerCollectionviewConstraint = innerCollectionview.anchor(restDate.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 20.5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: height).first
pageIndicatorConstraint = pageIndicator.anchor(nil, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 30, rightConstant: 0, widthConstant: 0, heightConstant: 26).first
}
else {
let height: CGFloat = 450
self.flowLayout.itemSize = setCellImageWidth(height: height)
backGroundImageViewConstraint = backGroundImageView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0).first
backImageViewConstraint = backImageView.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 16, leftConstant: 24, bottomConstant: 0, rightConstant: 0, widthConstant: 24, heightConstant: 24).first
TitleLabelConstraint = TitleLabel.anchor(backImageView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 30, leftConstant: 100, bottomConstant: 0, rightConstant: 100, widthConstant: 0, heightConstant: 84).first
restDateConstraint = restDate.anchor(TitleLabel.bottomAnchor, left: TitleLabel.leftAnchor, bottom: nil, right: TitleLabel.rightAnchor, topConstant: 6, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 26).first
innerCollectionviewConstraint = innerCollectionview.anchor(restDate.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 20.5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: height).first
pageIndicatorConstraint = pageIndicator.anchor(nil, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 34, rightConstant: 0, widthConstant: 0, heightConstant: 26).first
}
}
else {
// iphone se,7,8 etc
if view.frame.height < 800 {
let height: CGFloat = 430
self.flowLayout.itemSize = setCellImageWidth(height: height)
backGroundImageViewConstraint = backGroundImageView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0).first
backImageViewConstraint = backImageView.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 16, leftConstant: 24, bottomConstant: 0, rightConstant: 0, widthConstant: 24, heightConstant: 24).first
TitleLabelConstraint = TitleLabel.anchor(backImageView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 10, leftConstant: 100, bottomConstant: 0, rightConstant: 100, widthConstant: 0, heightConstant: 84).first
innerCollectionviewConstraint = innerCollectionview.anchor(restDate.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 20.5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: height).first
pageIndicatorConstraint = pageIndicator.anchor(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 30, rightConstant: 0, widthConstant: 0, heightConstant: 26).first
}
else {
let height: CGFloat = 450
self.flowLayout.itemSize = setCellImageWidth(height: height)
backGroundImageViewConstraint = backGroundImageView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0).first
backImageViewConstraint = backImageView.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 16, leftConstant: 24, bottomConstant: 0, rightConstant: 0, widthConstant: 24, heightConstant: 24).first
TitleLabelConstraint = TitleLabel.anchor(backImageView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 30, leftConstant: 100, bottomConstant: 0, rightConstant: 100, widthConstant: 0, heightConstant: 84).first
innerCollectionviewConstraint = innerCollectionview.anchor(restDate.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 20.5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: height).first
pageIndicatorConstraint = pageIndicator.anchor(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 34, rightConstant: 0, widthConstant: 0, heightConstant: 26).first
}
}
}
fileprivate func setCellImageWidth(height: CGFloat) -> CGSize{
// width/height
let imageRatio: CGFloat = 5/9
let width = imageRatio * height
return CGSize(width: width, height: height)
}
@objc fileprivate func goBack() {
self.navigationController?.popViewController(animated: true)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let pageCount = resInfos.count
// letter spacing -0.1
pageIndicator.letterSpacing(text: "1/\(pageCount)", spacing: -0.1)
return pageCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as! innerRestMonthCell
cell.delegate = self
cell.index = indexPath.item
let resInfo = resInfos[indexPath.item]
// letter spacing -0.4
cell.resNameLabel.letterSpacing(text: resInfo.resName ?? "", spacing: -0.4)
cell.cosmosView.rating = resInfo.starPoint ?? 3.5
let url = URL(string: resInfo.resImageUrl ?? "")
cell.resImageView.sd_setImage(with: url, completed: nil)
let toilet = resInfo.toilet ?? "공용"
cell.toilet = toilet
cell.hash1 = resInfo.hash1 ?? ""
cell.hash2 = resInfo.hash2 ?? ""
let swipeDownGesture = UISwipeGestureRecognizer(target: self, action: #selector(openCell2(sender:)))
swipeDownGesture.direction = .down
let swipeUpGesture = UISwipeGestureRecognizer(target: self, action: #selector(closeCell2(sender:)))
swipeUpGesture.direction = .up
// 이렇게 tag를 이용해서 selector의 parameter를 가져오자..
cell.tag = indexPath.item
cell.addGestureRecognizer(swipeUpGesture)
cell.addGestureRecognizer(swipeDownGesture)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let layout = self.innerCollectionview.collectionViewLayout as! UPCarouselFlowLayout
// check if the currentCenteredPage is not the page that was touched
let currentCenteredPage = layout.currentCenteredPage
if currentCenteredPage != indexPath.row {
// trigger a scrollToPage(index: animated:)
layout.scrollToPage(index: indexPath.row, animated: true)
let pageCount = resInfos.count
// letter spacing -0.1
pageIndicator.letterSpacing(text: "\(indexPath.row + 1)/\(pageCount)", spacing: -0.1)
}
let checkCurrentPage = currentCenteredPage
if checkCurrentPage == indexPath.item {
if self.checkOpen[indexPath.item] == false {
self.openCell(indexPath: indexPath)
}
else {
self.goRestaurant(indexPath: indexPath)
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let layout = self.innerCollectionview.collectionViewLayout as! UPCarouselFlowLayout
let pageSide = (layout.scrollDirection == .horizontal) ? self.pageSize.width : self.pageSize.height
let offset = (layout.scrollDirection == .horizontal) ? scrollView.contentOffset.x : scrollView.contentOffset.y
let currentPage = Int(floor((offset - pageSide / 2) / pageSide) + 1) + 1
let pageCount = resInfos.count
// letter spacing -0.1
pageIndicator.letterSpacing(text: "\(currentPage)/\(pageCount)", spacing: -0.1)
}
@objc fileprivate func openCell2(sender: UISwipeGestureRecognizer) {
// 이렇게 tag를 이용해서 selector의 parameter를 가져오자..
let indexPath = IndexPath(item: sender.view?.tag ?? 0, section: 0)
let cell = innerCollectionview.cellForItem(at: indexPath) as? innerRestMonthCell
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
cell?.whiteView.transform = CGAffineTransform(scaleX: 1.1, y: 1).translatedBy(x: 0, y: 70)
cell?.resImageView.transform = CGAffineTransform(scaleX: 1, y: 1).translatedBy(x: 0, y: -30)
cell?.containerView.layer.shadowOpacity = 0.1
self.checkOpen[indexPath.item] = true
}, completion: nil)
}
@objc fileprivate func closeCell2(sender: UISwipeGestureRecognizer) {
// 이렇게 tag를 이용해서 selector의 parameter를 가져오자..
let indexPath = IndexPath(item: sender.view?.tag ?? 0, section: 0)
let cell = innerCollectionview.cellForItem(at: indexPath) as? innerRestMonthCell
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
cell?.whiteView.transform = CGAffineTransform.identity
cell?.resImageView.transform = CGAffineTransform.identity
cell?.containerView.layer.shadowOpacity = 0.0
self.checkOpen[indexPath.item] = false
}, completion: nil)
}
fileprivate func openCell(indexPath: IndexPath) {
let cell = innerCollectionview.cellForItem(at: indexPath) as? innerRestMonthCell
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
cell?.whiteView.transform = CGAffineTransform(scaleX: 1.1, y: 1).translatedBy(x: 0, y: 70)
cell?.resImageView.transform = CGAffineTransform(scaleX: 1, y: 1).translatedBy(x: 0, y: -30)
cell?.containerView.layer.shadowOpacity = 0.1
self.checkOpen[indexPath.item] = true
}, completion: nil)
}
fileprivate func goRestaurant(indexPath: IndexPath) {
let resinfo = resInfos[indexPath.item]
let rest = RestaurantViewController()
rest.resinfo = resinfo
self.navigationController?.pushViewController(rest, animated: true)
}
}
class innerRestMonthCell: UICollectionViewCell, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
weak var delegate: RestaurantMonthController?
var index: Int?
fileprivate let cellid = "cellid"
let containerView: UIView = {
let view = UIView()
view.backgroundColor = .clear
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 2)
view.layer.shadowOpacity = 0.0
view.layer.shadowRadius = 10
view.layer.masksToBounds = false
return view
}()
let whiteView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.layer.cornerRadius = 10
view.layer.masksToBounds = true
return view
}()
let resImageView: UIImageView = {
let iv = UIImageView()
iv.backgroundColor = .clear
iv.contentMode = .scaleAspectFill
iv.layer.masksToBounds = true
iv.layer.cornerRadius = 10
return iv
}()
var open_Bool: String = "Closed"
var far_location: String = "14 min walk"
var toilet: String? {
didSet {
setupInfos()
}
}
let infoLabel: UILabel = {
let lb = UILabel()
lb.font = UIFont(name: "DMSans-Regular", size: 12)
lb.textColor = .gray
lb.textAlignment = .center
lb.numberOfLines = 0
return lb
}()
lazy var hashCollecionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 8
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.dataSource = self
cv.delegate = self
cv.showsHorizontalScrollIndicator = false
cv.backgroundColor = .white
return cv
}()
let resNameLabel: UILabel = {
let lb = UILabel()
lb.textColor = .white
lb.textAlignment = .center
lb.numberOfLines = 0
lb.font = UIFont(name: "DMSans-Regular", size: 22)
return lb
}()
lazy var cosmosView: CosmosView = {
var cv = CosmosView()
cv.settings.updateOnTouch = false
cv.settings.totalStars = 5
cv.settings.starSize = 16
cv.settings.starMargin = 1
cv.settings.fillMode = .half
cv.settings.filledImage = UIImage(named: "filledStar")
cv.settings.emptyImage = UIImage(named: "emptyStar")
return cv
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var containerViewConstraint: NSLayoutConstraint?
var whiteViewConstraint: NSLayoutConstraint?
var resImageViewConstraint: NSLayoutConstraint?
var infoLabelConstraint: NSLayoutConstraint?
var seperatorImageViewConstraint: NSLayoutConstraint?
var locationImageViewConstraint: NSLayoutConstraint?
var locationLabelConstraint: NSLayoutConstraint?
var toiletImageViewConstraint: NSLayoutConstraint?
var toiletLabelConstraint: NSLayoutConstraint?
var hashCollecionViewConstraint: NSLayoutConstraint?
var cosmosViewConstraint: NSLayoutConstraint?
var restNameLabelConstraint: NSLayoutConstraint?
var hashtagArray = [String]()
var hash1: String? {
didSet {
hashtagArray.append(hash1 ?? "")
}
}
var hash2: String? {
didSet {
hashtagArray.append(hash2 ?? "")
}
}
var gradient = CAGradientLayer()
fileprivate func setupViews() {
backgroundColor = .clear
addSubview(containerView)
containerView.addSubview(whiteView)
addSubview(resImageView)
whiteView.addSubview(infoLabel)
whiteView.addSubview(hashCollecionView)
resImageView.addSubview(cosmosView)
resImageView.addSubview(resNameLabel)
hashCollecionView.register(infoHashCell.self, forCellWithReuseIdentifier: cellid)
containerViewConstraint = containerView.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 30, leftConstant: 0, bottomConstant: 100, rightConstant: 0, widthConstant: 0, heightConstant: 0).first
whiteViewConstraint = whiteView.anchor(self.containerView.topAnchor, left: self.containerView.leftAnchor, bottom: self.containerView.bottomAnchor, right: self.containerView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0).first
resImageViewConstraint = resImageView.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 30, leftConstant: 0, bottomConstant: 100, rightConstant: 0, widthConstant: 0, heightConstant: 0).first
infoLabelConstraint = infoLabel.anchor(nil, left: whiteView.leftAnchor, bottom: whiteView.bottomAnchor, right: whiteView.rightAnchor, topConstant: 0, leftConstant: 15, bottomConstant: 60, rightConstant: 15, widthConstant: 0, heightConstant: 16).first
hashCollecionViewConstraint = hashCollecionView.anchor(infoLabel.bottomAnchor, left: self.leftAnchor, bottom: nil, right: self.rightAnchor, topConstant: 15, leftConstant: 25, bottomConstant: 0, rightConstant: 25, widthConstant: 0, heightConstant: 24).first
cosmosViewConstraint = cosmosView.anchor(nil, left: self.leftAnchor, bottom: resImageView.bottomAnchor, right: self.rightAnchor, topConstant: 0, leftConstant: 80, bottomConstant: 26, rightConstant: 80, widthConstant: 0, heightConstant: 18).first
restNameLabelConstraint = resNameLabel.anchor(nil, left: self.leftAnchor, bottom: cosmosView.topAnchor, right: self.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 10, rightConstant: 0, widthConstant: 0, heightConstant: 25).first
resImageView.setGradientBackgroundVertical(gradientLayer: gradient, colorOne:UIColor(white: 0, alpha: 0), colorTwo: UIColor(white: 0, alpha: 0.6))
}
// https://fluffy.es/solve-duplicated-cells/
// 3번째 cell부터 reuse되는걸 막음.
override func prepareForReuse() {
super.prepareForReuse()
whiteView.transform = CGAffineTransform.identity
resImageView.transform = CGAffineTransform.identity
containerView.layer.shadowOpacity = 0.0
delegate?.checkOpen[index ?? 0] = false
// 밑에 두줄은 신의 한수!
hashtagArray.removeAll()
cellWidthArr.removeAll()
hashCollecionView.reloadData()
}
fileprivate func setupInfos() {
// https://zeddios.tistory.com/406
let attributedString = NSMutableAttributedString(string: "\(open_Bool) ")
let seperator = NSTextAttachment()
seperator.image = UIImage(named: "seperator")
seperator.bounds = CGRect(x: 0, y: 0, width: 9, height: 9)
attributedString.append(NSAttributedString(attachment: seperator))
attributedString.append(NSAttributedString(string: " "))
let locationImage = NSTextAttachment()
locationImage.image = UIImage(named: "location")
locationImage.bounds = CGRect(x: 0, y: 0, width: 12, height: 12)
attributedString.append(NSAttributedString(attachment: locationImage))
attributedString.append(NSAttributedString(string: " \(far_location) "))
let toiletImage = NSTextAttachment()
if toilet == "공용" {
toiletImage.image = UIImage(named: "Unisex Toilet_gray")
}
else {
toiletImage.image = UIImage(named: "Seperate Toilet_gray")
}
toiletImage.bounds = CGRect(x: 0, y: -1, width: 14, height: 14)
attributedString.append(NSAttributedString(attachment: toiletImage))
attributedString.append(NSAttributedString(string: " \(toilet ?? "공용")"))
infoLabel.attributedText = attributedString
infoLabel.sizeToFit()
}
// autolayout 사용시에는 gradient 설정하고 밑에 viewDidLayoutSubviews를 설정해주어야함.
// collectionview 안에 있는 cell은 이걸로 설정!!
override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = resImageView.bounds
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hashtagArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as! infoHashCell
// spacing -0.1
cell.hashLabel.letterSpacing(text: "#" + hashtagArray[indexPath.item], spacing: -0.1)
cell.hashLabel.font = UIFont(name: "DMSans-Regular", size: 13)
return cell
}
var cellWidthArr = [CGFloat]()
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// 밑에 frame의 width에 따라 width가 너무 작으면 오류가 나더라.. constraint관련해서
let frame = CGRect(x: 0, y: 0, width: 1000, height: 24)
let dummyCell = infoHashCell(frame: frame)
dummyCell.hashLabel.letterSpacing(text: "#" + hashtagArray[indexPath.item], spacing: -0.1)
dummyCell.layoutIfNeeded()
let textWidth = dummyCell.hashLabel.sizeThatFits(dummyCell.hashLabel.frame.size).width + 10
cellWidthArr.append(textWidth)
return CGSize(width: textWidth, height: 24)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
// cell 크기가 유동적으로 변하기 때문에 popular 한 68크기로 잡음
// cell들이 중앙에 위치하게 하는 코드.
// https://stackoverflow.com/questions/34267662/how-to-center-horizontally-uicollectionview-cells
let totalCellWidth: CGFloat = cellWidthArr[0] + cellWidthArr[1]
let totalSpacingWidth: CGFloat = 8 * CGFloat(hashtagArray.count - 1)
let collectionViewWidth = self.frame.width - 50
let leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
let rightInset = leftInset
return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
}
}
| 48.453846 | 306 | 0.654993 |
fe4fd2cfac1b34962af74d2b208051865901cb2d | 2,184 | //
// SceneDelegate.swift
// YoSwiftKing
//
// Created by admin on 2022/2/9.
//
import UIKit
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else {
return
}
window = UIWindow(windowScene: windowScene)
window?.frame = windowScene.coordinateSpace.bounds
let tabBarCtl = YoTabBarCtl()
window?.rootViewController = tabBarCtl
window?.makeKeyAndVisible()
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 38.315789 | 140 | 0.695971 |
8f17b7b8ad5a8b44f49f37157d7c20ffa82b20f6 | 926 | //
// HttpStrategy.swift
// Pioneer
//
// Created by d-exclaimation on 4:30 PM.
//
import Foundation
extension Pioneer {
/// HTTP Operation and routing strategy for GraphQL
public enum HTTPStrategy {
/// Only allow `POST` GraphQL Request, most common choice
case onlyPost
/// Only allow `GET` GraphQL Request, not recommended for most
case onlyGet
/// Allow all operation through `POST` and allow only Queries through `GET`, recommended to utilize CORS
case queryOnlyGet
/// Allow all operation through `GET` and allow only Mutations through `POST`, utilize browser GET cache but not recommended
case mutationOnlyPost
/// Query must go through `GET` while any mutations through `POST`, follow and utilize HTTP conventions
case splitQueryAndMutation
/// Allow all operation through `GET` and `POST`.
case both
}
}
| 34.296296 | 132 | 0.672786 |
088892d879466c0712398affe15312728ae5ff7f | 2,606 | //
// MySegmentsV2PayloaDecoderTest.swift
// SplitTests
//
// Created by Javier Avrudsky on 14-Sep-2021.
// Copyright © 2021 Split. All rights reserved.
//
import Foundation
import XCTest
@testable import Split
class MySegmentsV2PayloaDecoderTest: XCTestCase {
let decoder = DefaultMySegmentsV2PayloadDecoder()
let gzip = Gzip()
let zlib = Zlib()
override func setUp() {
}
func testKeyListGzipPayload() throws {
let payload = try decoder.decodeAsString(payload: TestingData.encodedKeyListPayloadGzip(),
compressionUtil: gzip)
let keyList = try decoder.parseKeyList(jsonString: payload)
let added = keyList.added
let removed = keyList.removed
XCTAssertEqual(2, added.count)
XCTAssertEqual(2, removed.count)
XCTAssertTrue(added.contains(1573573083296714675))
XCTAssertTrue(added.contains(8482869187405483569))
XCTAssertTrue(removed.contains(8031872927333060586))
XCTAssertTrue(removed.contains(6829471020522910836))
}
func testBoundedGzipPayload() throws {
let payload = try decoder.decodeAsBytes(payload: TestingData.encodedBoundedPayloadGzip(), compressionUtil: gzip)
try boundedTest(payload: payload,decompressor: gzip)
}
func testBoundedZlibPayload() throws {
let payload = try decoder.decodeAsBytes(payload: TestingData.encodedBoundedPayloadZlib(), compressionUtil: zlib)
try boundedTest(payload: payload,decompressor: zlib)
}
func boundedTest(payload: Data, decompressor: CompressionUtil) throws {
var keys = [String]()
keys.append("603516ce-1243-400b-b919-0dce5d8aecfd")
keys.append("88f8b33b-f858-4aea-bea2-a5f066bab3ce")
keys.append("375903c8-6f62-4272-88f1-f8bcd304c7ae")
keys.append("18c936ad-0cd2-490d-8663-03eaa23a5ef1")
keys.append("bfd4a824-0cde-4f11-9700-2b4c5ad6f719")
keys.append("4588c4f6-3d18-452a-bc4a-47d7abfd23df")
keys.append("42bcfe02-d268-472f-8ed5-e6341c33b4f7")
keys.append("2a7cae0e-85a2-443e-9d7c-7157b7c5960a")
keys.append("4b0b0467-3fe1-43d1-a3d5-937c0a5473b1")
keys.append("09025e90-d396-433a-9292-acef23cf0ad1")
var results = [String: Bool]()
for key in keys {
let hashedKey = decoder.hashKey(key)
results[key] = decoder.isKeyInBitmap(keyMap: payload, hashedKey: hashedKey)
}
for key in keys {
XCTAssertTrue(results[key] ?? false)
}
}
override func tearDown() {
}
}
| 32.17284 | 120 | 0.674981 |
11f886a892d6d8db8d816251af04f134ae4c7b10 | 1,816 | //
// GenreDecode.swift
// KinoLenta
//
// Created by user on 15.12.2021.
//
import Foundation
enum GenreDecoderContainer {
static let sharedMovieManager = GenreDecoder(fileURL: MockJsonPaths.movieGenrePath.fileURL)
static let sharedTVManager = GenreDecoder(fileURL: MockJsonPaths.tvGenrePath.fileURL)
}
class GenreDecoder {
private var intIndexed: [Int: String] = [:]
private var stringIndexed: [String: Int] = [:]
private init(genres: [Int: String]) {
intIndexed = genres
for pair in intIndexed {
stringIndexed[pair.value] = pair.key
}
}
convenience init(fileURL: URL) {
guard let data = try? readJsonData(fileURL: fileURL) else {
self.init(genres: [:])
return
}
self.init(jsonData: data)
}
convenience init(jsonData: Data) {
let topDict = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]
guard let container = topDict?["genres"] as? [[String: Any]] else {
self.init(genres: [:])
return
}
self.init(genres: Dictionary(uniqueKeysWithValues: container.compactMap {
guard let genreItemID = $0["id"] as? Int,
let genreItemName = $0["name"] as? String else { return nil }
return (genreItemID, genreItemName)
}))
}
}
extension GenreDecoder {
func getByID(_ id: Int) -> String? {
guard let solution = intIndexed[id] else { return nil }
return solution
}
func getByName(_ name: String) -> Int? {
guard let solution = stringIndexed[name] else { return nil }
return solution
}
}
extension GenreDecoder {
func getGenreNames() -> [String] { Array(intIndexed.values.map { $0.firstUppercased }) }
}
| 27.515152 | 102 | 0.613987 |
f82bfc6b5b6f28d843fd911e9295b717bae3c14b | 940 | //
// ZQGameViewModel.swift
// DouYuZB
//
// Created by 张泉 on 2021/8/30.
//
import UIKit
class ZQGameViewModel {
lazy var games : [ZQGameModel] = [ZQGameModel]()
}
//http://capi.douyucdn.cn/api/v1/getColumnDetail?&shortName=game
extension ZQGameViewModel {
func loadAllGameData(finishedCallback : @escaping () -> ()) {
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getColumnDetail", parameters: ["shortName" : "game"]) { (result) in
print(result)
// 1.获取到数据
guard let resultDict = result as? [String : Any] else { return }
guard let dataArray = resultDict["data"] as? [[String : Any]] else { return }
// 2.字典转模型
for dict in dataArray {
self.games.append(ZQGameModel.deserialize(from: dict)!)
}
// 3.完成回调
finishedCallback()
}
}
}
| 29.375 | 149 | 0.57234 |
29e32caf52b3161f9e7e70b068d22c37d649ba50 | 399 | //
// NetworkLayer.swift
// Flist
//
// Created by Роман Широков on 06/11/2018.
// Copyright © 2018 Flist. All rights reserved.
//
import Foundation
protocol BaseLayerProtocol {
/**
- returns: the identificator of the active user. One of the uses is the verification of authorization; thus if returns nil, the user is not logged in.
*/
func getCurrentUID() -> String?
}
| 22.166667 | 155 | 0.676692 |
01f0736d4b96522ab362994574b3fc3fdb6b84e5 | 1,191 | import UIKit
class EditPostViewController: UIViewController {
@IBOutlet weak var bodyTextField: UITextField!
@IBOutlet weak var titleTextField: UITextField!
fileprivate let newPost: Bool
fileprivate let post: Post
fileprivate let postController = PostController()
init(post: Post?) {
self.newPost = (post == nil)
self.post = post ?? Post()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createNewPost() {
postController.uploadNew(post) { (error) in
if let error = error {
print(error)
}
}
}
func updatePost() {
postController.update(post) { (error) in
if let error = error {
print(error)
}
}
}
@IBAction func submitTapped() {
if newPost {
createNewPost()
} else {
updatePost()
}
}
override func viewDidLoad() {
super.viewDidLoad()
bodyTextField.text = post.body
titleTextField.text = post.title
}
}
| 20.894737 | 59 | 0.558354 |
183aa7f6480185dce4ed47b4d239390bb824eb5d | 1,166 | //: Playground - noun: a place where people can play
import UIKit
/*
Optional 可选类型:
强制对空值做判断
在swif 开发中,nil 也是一个特殊的类型, 因为和真是类型不匹配,所以是不能赋值的, (swift 是强类型语言)但是在开发中我们又在所难免的把对象值为nil,所以Swift 推出了可选类型
总结:
1.定义可选类型 option案例<Sring> / String?
2.给可选类型赋值 Optional(“king”) / 直接赋值 "king"
3.从可选类型中取值
4. 强制解包非常危险 name !
5.可选绑定 if let name = name {}
*/
//在类里面所有的必须都初始化
//class person{
// var name :String = nil 类型不一致,不可以初始化为nil nil也是特殊的类型
//}
/*
在开发中只有可选类型可以赋值为 nil , 其他类型都不可以
*/
//1 .定义可变类型, 泛型集合
//>1 ,定义方式 一
var name1 : Optional<String> = nil
//>2 定义方式二 : 语法糖
var name : String? = nil
//2.给可选类型进行赋值
//>1 赋值方式一
name = Optional("12")
//>2 赋值方式二 语法糖
name = "king"
//3 .取出可选类型中的值
print(name) //Optional("king") 可选类型
print(name!) // king 强制解包 输出的确定类型 不再是可选类型
//4. 注意强制解包非常危险 ,如果对象为nil ,那么强制解包,程序就会崩溃掉
//print(name1!)
// 避免强制解包
if name != nil{
print(name)
}
//5 .可选绑定 :该语法用于可选类型,使用起来更加方便 先判断那么是否有值,如果没有值,则不会执行{} 内容,如果有值,则那么系统会自动对可选类型解包,并且将解包后的结果赋值给临时tempName
if let tempName = name{
print(tempName)
}
//写法二 推荐
if let name = name{
print(name)
}
| 19.762712 | 106 | 0.624357 |
23d626ab1c5e124448d9631241ec38c9525f844d | 4,268 | import PySwift_ObjC
extension UnsafeMutableRawPointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
public func bridgeRetained<T : AnyObject>(obj : T) -> UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Unmanaged.passRetained(obj).toOpaque())
}
public func bridgeTransfer<T : AnyObject>(ptr : UnsafeRawPointer) -> T {
return Unmanaged<T>.fromOpaque(ptr).takeRetainedValue()
}
/// Compute the prefix sum of `seq`.
public func scan<
S : Sequence, U
>(_ seq: S, _ initial: U, _ combine: (U, S.Iterator.Element) -> U) -> [U] {
var result: [U] = []
result.reserveCapacity(seq.underestimatedCount)
var runningResult = initial
for element in seq {
runningResult = combine(runningResult, element)
result.append(runningResult)
}
return result
}
public func withArrayOfCStrings<R>(
_ args: [String], _ body: ([UnsafeMutablePointer<CChar>?]) -> R
) -> R {
let argsCounts = Array(args.map { $0.utf8.count + 1 })
let argsOffsets = [ 0 ] + scan(argsCounts, 0, +)
let argsBufferSize = argsOffsets.last!
var argsBuffer: [UInt8] = []
argsBuffer.reserveCapacity(argsBufferSize)
for arg in args {
argsBuffer.append(contentsOf: arg.utf8)
argsBuffer.append(0)
}
return argsBuffer.withUnsafeMutableBufferPointer {
(argsBuffer) in
let ptr = UnsafeMutableRawPointer(argsBuffer.baseAddress!).bindMemory(
to: CChar.self, capacity: argsBuffer.count)
var cStrings: [UnsafeMutablePointer<CChar>?] = argsOffsets.map { ptr + $0 }
cStrings[cStrings.count - 1] = nil
return body(cStrings)
}
}
@inline(__always) public func prepareFor<T: WrappableInPython>() -> UnsafeMutablePointer<T> {
let ptr = UnsafeMutablePointer<pyswift_PyObjWrappingSwift>.allocate(capacity: 1)
let intermediate = unsafeBitCast(ptr, to: UnsafeMutablePointer<T>.self)
return intermediate
}
@inline(__always) public func prepareFor<T>(_ pyType: T.Type) -> UnsafeMutablePointer<T> {
return UnsafeMutablePointer<T>.allocate(capacity: 1)
}
@inline(__always) public func finishFor<T: AnyObject>(_ intermediate: UnsafeMutablePointer<T>) -> T where T: WrappableInPython {
return intermediate.withMemoryRebound(to: pyswift_PyObjWrappingSwift.self, capacity: 1, { pyPtr -> T in
let swiftyInstance : T = Unmanaged<T>.fromOpaque(pyPtr.pointee.wrapped_obj).takeRetainedValue()
return swiftyInstance
})
}
public func parseSelfAndArgs<S : WrappableInPython>(
_ rawSelf : UnsafeMutablePointer<PyObject>?,
_ pyArgs: UnsafeMutablePointer<PyObject>?,
_ types: String,
_ sfArgs: UnsafeMutableRawPointer...) -> S? where S : AnyObject
{
let pySelf = UnsafeMutableRawPointer(rawSelf!).bindMemory(to: pyswift_PyObjWrappingSwift.self, capacity: 1).pointee
let swSelf : S = Unmanaged<S>.fromOpaque(pySelf.wrapped_obj).takeRetainedValue()
let retCode = withVaList(sfArgs) { p -> Int32 in
return PyArg_VaParse(pyArgs, types, p)
}
guard retCode > 0 else {
PythonSwift.setPythonException( PythonSwift.retrievePythonException()! )
return nil
}
guard type(of: swSelf) == S.self else {
PythonSwift.setPythonException( PySwiftError.UnexpectedTypeError(expected: S.self, got: type(of: swSelf)) )
return nil
}
return swSelf
}
public func parseSelfAndArgs<S : PythonObject>(
_ rawSelf : UnsafeMutablePointer<PyObject>?,
_ pyArgs: UnsafeMutablePointer<PyObject>?,
_ types: String,
_ sfArgs: UnsafeMutableRawPointer...) -> S?
{
let pySelf = UnsafeMutableRawPointer(rawSelf ?? PyNone_Get()).bindMemory(to: PyObject.self, capacity: 1)
let retCode = withVaList(sfArgs) { p -> Int32 in
return PyArg_VaParse(pyArgs, types, p)
}
guard retCode > 0 else {
PythonSwift.setPythonException( PythonSwift.retrievePythonException()! )
return nil
}
return S(ptr: pySelf)
}
public func getPointerToPythonObjectType(_ type: UnsafePointer<PyTypeObject>) -> PythonTypeObjectPointer {
return type
}
| 35.566667 | 128 | 0.692127 |
1a13f4dd20d64201224bbcf656dbc8c9bc38dea0 | 1,403 | import UIKit
import KeychainSwift
let TegKeychainDemo_keyName = "my key"
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var valueLabel: UILabel!
@IBOutlet weak var synchronizableSwitch: UISwitch!
let keychain = KeychainSwift()
override func viewDidLoad() {
super.viewDidLoad()
updateValueLabel()
}
@IBAction func onSaveTapped(_ sender: AnyObject) {
closeKeyboard()
if let text = textField.text {
keychain.synchronizable = synchronizableSwitch.isOn
keychain.set(text, forKey: TegKeychainDemo_keyName)
updateValueLabel()
}
}
@IBAction func onDeleteTapped(_ sender: AnyObject) {
closeKeyboard()
keychain.synchronizable = synchronizableSwitch.isOn
keychain.delete(TegKeychainDemo_keyName)
updateValueLabel()
}
@IBAction func onGetTapped(_ sender: AnyObject) {
closeKeyboard()
updateValueLabel()
}
private func updateValueLabel() {
keychain.synchronizable = synchronizableSwitch.isOn
if let value = keychain.get(TegKeychainDemo_keyName) {
valueLabel.text = "In Keychain: \(value)"
} else {
valueLabel.text = "no value in keychain"
}
}
private func closeKeyboard() {
textField.resignFirstResponder()
}
@IBAction func didTapView(_ sender: AnyObject) {
closeKeyboard()
}
}
| 21.921875 | 58 | 0.693514 |
87579146cd20eb6717360d06fa5dfb5823b07d8c | 1,369 | // Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: proto.fbe
// Version: 1.4.0.0
import ChronoxorFbe
// Fast Binary Encoding OrderType final model
public class FinalModelOrderType: FinalModel {
public var _buffer: Buffer
public var _offset: Int
// Final size
public let fbeSize: Int = 1
public init(buffer: Buffer = Buffer(), offset: Int = 0) {
_buffer = buffer
_offset = offset
}
// Get the allocation size
public func fbeAllocationSize(value: OrderType) -> Int { fbeSize }
public func verify() -> Int {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
return Int.max
}
return fbeSize
}
// Get the value
public func get(size: inout Size) -> OrderType {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
return OrderType()
}
size.value = fbeSize
return OrderType(value: readByte(offset: fbeOffset))
}
// Set the value
public func set(value: OrderType) throws -> Int {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
assertionFailure("Model is broken!")
return 0
}
write(offset: fbeOffset, value: value.raw)
return fbeSize
}
}
| 25.351852 | 79 | 0.620161 |
6a136588fa5d8bb54586fd14f2e84ba8473a98ac | 2,163 | //
// ViewController.swift
// TogglerDemo
//
// Created by YiSeungyoun on 2017. 8. 6..
// Copyright © 2017년 SeungyounYi. All rights reserved.
//
import UIKit
import Toggler
class ViewController: UIViewController {
var toggler: Toggler!
var toggler2: Toggler!
@IBOutlet weak var button1: Button!
@IBOutlet weak var button2: Button!
@IBOutlet weak var button3: Button!
@IBOutlet weak var button4: Button!
@IBOutlet weak var button5: Button!
@IBOutlet weak var button6: Button!
@IBOutlet weak var button7: Button!
@IBOutlet weak var button8: Button!
@IBOutlet weak var button9: UIControl!
@IBOutlet weak var button10: UIControl!
override func viewDidLoad() {
super.viewDidLoad()
toggler = Toggler(default: 0, togglers: [button1, button2, button3, button4, button5])
button1.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
button3.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
button4.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
button5.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
toggler2 = Toggler(default: 0, togglers: [button6, button7, button8, button9, button10])
button6.addTarget(self, action: #selector(buttonClicked2(_:)), for: .touchUpInside)
button7.addTarget(self, action: #selector(buttonClicked2(_:)), for: .touchUpInside)
button8.addTarget(self, action: #selector(buttonClicked2(_:)), for: .touchUpInside)
button9.addTarget(self, action: #selector(buttonClicked2(_:)), for: .touchUpInside)
button10.addTarget(self, action: #selector(buttonClicked2(_:)), for: .touchUpInside)
}
func buttonClicked(_ sender: UIButton) {
toggler.on(button: sender)
}
func buttonClicked2(_ sender: UIButton) {
toggler2.on(button: sender)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 35.459016 | 96 | 0.679149 |
76b76e8e4ffd0a3cfa4f6cc5ecee6082993e0166 | 1,006 | //
// HeaderAttributedStringLayoutBlockBuilder.swift
// Pods
//
// Created by Jim van Zummeren on 11/06/16.
//
//
import Foundation
import UIKit
class HeaderAttributedStringLayoutBlockBuilder: InlineAttributedStringLayoutBlockBuilder {
// MARK: LayoutBuilder
override func relatedMarkDownItemType() -> MarkDownItem.Type {
return HeaderMarkDownItem.self
}
override func build(_ markDownItem: MarkDownItem, asPartOfConverter converter: MarkDownConverter<NSMutableAttributedString>, styling: ItemStyling) -> NSMutableAttributedString {
let headerMarkDownItem = markDownItem as! HeaderMarkDownItem
let headerStyling = styling as? HeadingStyling
headerStyling?.configureForLevel(headerMarkDownItem.level)
let attributedString = attributedStringForMarkDownItem(markDownItem, styling: headerStyling ?? styling)
return attributedStringWithContentInset(attributedString, contentInset: headerStyling?.contentInsets ?? UIEdgeInsets())
}
}
| 33.533333 | 181 | 0.774354 |
8990b3a99272d0b13a42fcee478eb81717dc87ff | 922 | //
// ProcessInfo.swift
// Swiftline
//
// Created by Omar Abdelhafith on 26/11/2015.
// Copyright © 2015 Omar Abdelhafith. All rights reserved.
//
import Foundation
protocol ProcessInfoType {
var arguments: [String] { get }
var cacheResults: Bool { get }
}
extension Foundation.ProcessInfo: ProcessInfoType {
var cacheResults: Bool { return true }
}
class DummyProcessInfo: ProcessInfoType {
var argsToReturn: [String]
init(_ argsToReturn: String...) {
self.argsToReturn = argsToReturn
}
var arguments: [String] {
return argsToReturn
}
var cacheResults: Bool { return false }
}
enum ProcessInfo {
static var internalProcessInfo: ProcessInfoType = Foundation.ProcessInfo.processInfo
static var arguments: [String] {
return internalProcessInfo.arguments
}
static var cacheResults: Bool {
return internalProcessInfo.cacheResults
}
}
| 19.208333 | 88 | 0.698482 |
912322a98bae2e73a760fcf26e85c0ab7e192153 | 1,413 | //
// AppDelegate.swift
// tipper
//
// Created by Sadia Chowdhury on 7/31/20.
// Copyright © 2020 Codepath. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// 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.184211 | 179 | 0.747346 |
5def324eee49700a84d85638dc7bf20b63e6ea85 | 1,932 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import UIKit
extension UIColor {
convenience init(r: UInt8, g: UInt8, b: UInt8) {
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: 255)
}
// RGB (12-bit), RGB (24-bit) and RGBA (32-bit) formats are supported
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // RGBA (32-bit)
(a, r, g, b) = (int & 0xFF, int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
// RGB (24-bit) and RGBA (32-bit) formats are supported
func hexString(_ includeAlpha: Bool = true) -> String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
guard r >= 0 && r <= 1 && g >= 0 && g <= 1 && b >= 0 && b <= 1 else {
return nil
}
if (includeAlpha) {
return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))
} else {
return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
}
}
}
| 37.153846 | 114 | 0.51087 |
7260182de838578a7fb1d501850cb1ad906d9cf4 | 515 | //
// NoCancelButtonSearchController.swift
// iOS_Bootstrap_Example
//
// Created by Ahmad Mahmoud on 11/19/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
class NoCancelButtonSearchController: UISearchController {
let noCancelButtonSearchBar = NoCancelButtonSearchBar()
override var searchBar: UISearchBar { return noCancelButtonSearchBar }
}
class NoCancelButtonSearchBar: UISearchBar {
override func setShowsCancelButton(_ showsCancelButton: Bool, animated: Bool) {}
}
| 27.105263 | 84 | 0.780583 |
1aef6b475c7f70c694aeccac20e1cf8ae7f1dc66 | 1,854 | //
// HTTPHeadersTests.swift
// TwilioVerifyTests
//
// Copyright © 2020 Twilio.
//
// 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 XCTest
@testable import TwilioVerify
class HTTPHeadersTests: XCTestCase {
typealias HeaderConstants = HTTPHeader.Constant
func testGetDictionary_shouldContaintExpectedHeaders() {
let expectedHeaders = [HTTPHeader.accept("accept"), HTTPHeader.contentType("content")]
var httpHeaders = HTTPHeaders()
httpHeaders.addAll(expectedHeaders)
let headersDict = httpHeaders.dictionary
XCTAssertEqual(headersDict?.count, expectedHeaders.count,
"Headers size should be \(expectedHeaders.count) but were \(String(describing: headersDict?.count))")
XCTAssertEqual(headersDict?[HeaderConstants.acceptType], expectedHeaders.first { $0.key == HeaderConstants.acceptType }?.value,
"Header should be \(expectedHeaders.first { $0.key == HeaderConstants.acceptType }!.value) but was \(headersDict![HeaderConstants.acceptType]!)")
XCTAssertEqual(headersDict?[HeaderConstants.contentType], expectedHeaders.first { $0.key == HeaderConstants.contentType }?.value,
"Header should be \(expectedHeaders.first { $0.key == HeaderConstants.contentType }!.value) but was \(headersDict![HTTPHeader.Constant.contentType]!)")
}
}
| 46.35 | 170 | 0.73247 |
e5b9303c06d0131cc886711691b7ffa4480b569d | 546 | //: [Previous](@previous)
/*
Functions are first-class citizen types in Swift, so it is
perfectly legal to define operators for them.
*/
import Foundation
let firstRange = { (0...3).contains($0) }
let secondRange = { (5...6).contains($0) }
func ||(_ lhs: @escaping (Int) -> Bool, _ rhs: @escaping (Int) -> Bool) -> (Int) -> Bool {
return { value in
return lhs(value) || rhs(value)
}
}
(firstRange || secondRange)(2) // true
(firstRange || secondRange)(4) // false
(firstRange || secondRange)(6) // true
//: [Next](@next)
| 22.75 | 90 | 0.617216 |
76b8f6fae31522618bc949991a15e3423ce65ae3 | 8,893 | //
// PAPermissionsTableViewCell.swift
// PAPermissionsApp
//
// Created by Pasquale Ambrosini on 05/09/16.
// Copyright © 2016 Pasquale Ambrosini. All rights reserved.
//
import UIKit
class PAPermissionsTableViewCell: UITableViewCell {
var didSelectItem: ((PAPermissionsItem) -> ())?
weak var iconImageView: UIImageView!
weak var titleLabel: UILabel!
weak var detailsLabel: UILabel!
weak var permission: PAPermissionsItem!
fileprivate weak var rightDetailsContainer: UIView!
fileprivate weak var enableButton: UIButton!
fileprivate weak var checkingIndicator: UIActivityIndicatorView!
fileprivate var _permissionStatus = PAPermissionsStatus.disabled
var permissionStatus: PAPermissionsStatus {
get {
return self._permissionStatus
}
set(newStatus) {
self._permissionStatus = newStatus
self.setupEnableButton(newStatus)
}
}
override var tintColor: UIColor! {
get {
return super.tintColor
}
set(newTintColor) {
super.tintColor = newTintColor
self.updateTintColor()
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func updateTintColor() {
self.setupImageView()
self.setupTitleLabel()
self.setupDetailsLabel()
self.setupEnableButton(self.permissionStatus)
}
fileprivate func setupUI() {
self.backgroundColor = UIColor.clear
self.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
self.setupImageView()
self.setupTitleLabel()
self.setupDetailsLabel()
self.setupRightDetailsContainer()
let views = ["iconImageView": self.iconImageView,
"titleLabel": self.titleLabel,
"detailsLabel": self.detailsLabel,
"rightDetailsContainer": self.rightDetailsContainer] as [String:UIView]
let allConstraints = PAConstraintsUtils.concatenateConstraintsFromString([
"V:|-2-[iconImageView]-2-|",
"H:|-0-[iconImageView(15)]",
"V:|-2-[rightDetailsContainer]-2-|",
"H:[rightDetailsContainer(58)]-0-|",
"V:|-8-[titleLabel(18)]-2-[detailsLabel(13)]",
"H:[iconImageView]-8-[titleLabel]-4-[rightDetailsContainer]",
"H:[iconImageView]-8-[detailsLabel]-4-[rightDetailsContainer]"
], views: views)
if #available(iOS 8.0, *) {
NSLayoutConstraint.activate(allConstraints)
} else {
self.addConstraints(allConstraints)
}
self.setupEnableButton(.disabled)
}
fileprivate func setupImageView() {
if self.iconImageView == nil {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
self.addSubview(imageView)
self.iconImageView = imageView
self.iconImageView.backgroundColor = UIColor.clear
self.iconImageView.translatesAutoresizingMaskIntoConstraints = false
}
self.iconImageView.tintColor = self.tintColor
}
fileprivate func setupTitleLabel() {
if self.titleLabel == nil {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(titleLabel)
self.titleLabel = titleLabel
self.titleLabel.text = "Title"
self.titleLabel.adjustsFontSizeToFitWidth = true
}
self.titleLabel.font = UIFont(name: "HelveticaNeue-Light", size: 15)
self.titleLabel.minimumScaleFactor = 0.1
self.titleLabel.textColor = self.tintColor
}
fileprivate func setupDetailsLabel() {
if self.detailsLabel == nil {
let detailsLabel = UILabel()
detailsLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(detailsLabel)
self.detailsLabel = detailsLabel
self.detailsLabel.text = "details"
self.detailsLabel.adjustsFontSizeToFitWidth = true
}
self.detailsLabel.font = UIFont(name: "HelveticaNeue-Light", size: 11)
self.detailsLabel.minimumScaleFactor = 0.1
self.detailsLabel.textColor = self.tintColor
}
fileprivate func setupRightDetailsContainer() {
if self.rightDetailsContainer == nil {
let rightDetailsContainer = UIView()
rightDetailsContainer.backgroundColor = UIColor.clear
rightDetailsContainer.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(rightDetailsContainer)
self.rightDetailsContainer = rightDetailsContainer
self.rightDetailsContainer.backgroundColor = UIColor.clear
}
}
fileprivate func setupEnableButton(_ status: PAPermissionsStatus) {
if self.enableButton == nil {
let enableButton = UIButton(type: .system)
enableButton.translatesAutoresizingMaskIntoConstraints = false
self.rightDetailsContainer.addSubview(enableButton)
self.enableButton = enableButton
self.enableButton.backgroundColor = UIColor.red
self.enableButton.addTarget(self, action: #selector(PAPermissionsTableViewCell._didSelectItem), for: .touchUpInside)
let checkingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
checkingIndicator.translatesAutoresizingMaskIntoConstraints = false
self.rightDetailsContainer.addSubview(checkingIndicator)
self.checkingIndicator = checkingIndicator
let views = ["enableButton": self.enableButton,
"checkingIndicator": self.checkingIndicator] as [String : UIView]
var allConstraints = PAConstraintsUtils.concatenateConstraintsFromString([
"V:[enableButton(30)]",
"H:|-2-[enableButton]-2-|",
"V:|-0-[checkingIndicator]-0-|",
"H:|-0-[checkingIndicator]-0-|"
], views: views)
allConstraints.append(NSLayoutConstraint.init(item: self.enableButton, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.enableButton.superview, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0))
if #available(iOS 8.0, *) {
NSLayoutConstraint.activate(allConstraints)
} else {
self.rightDetailsContainer.addConstraints(allConstraints)
}
}
self.enableButton.tintColor = self.tintColor
if status == .enabled {
if !self.permission.canBeDisabled {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle("", for: UIControlState())
self.enableButton.layer.cornerRadius = 0.0
self.enableButton.layer.borderColor = UIColor.clear.cgColor
self.enableButton.layer.borderWidth = 0.0
self.enableButton.setImage(UIImage(named: "pa_checkmark_icon", in: Bundle(for: PAPermissionsViewController.self), compatibleWith: nil), for: UIControlState())
self.enableButton.imageView?.contentMode = .scaleAspectFit
self.enableButton.isUserInteractionEnabled = false
}else{
self.setupEnableDisableButton(title: "Disable")
}
}else if status == .disabled || status == .denied {
self.setupEnableDisableButton(title: "Enable")
}else if status == .checking {
self.enableButton.isHidden = true
self.checkingIndicator.isHidden = false
self.checkingIndicator.startAnimating()
}else if status == .unavailable {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle("", for: UIControlState())
self.enableButton.layer.cornerRadius = 0.0
self.enableButton.layer.borderColor = UIColor.clear.cgColor
self.enableButton.layer.borderWidth = 0.0
self.enableButton.setImage(UIImage(named: "pa_cancel_icon", in: Bundle(for: PAPermissionsViewController.self), compatibleWith: nil), for: UIControlState())
self.enableButton.imageView?.contentMode = .scaleAspectFit
self.enableButton.isUserInteractionEnabled = false
}
}
private func setupEnableDisableButton(title: String) {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle(NSLocalizedString(title, comment: ""), for: UIControlState())
self.enableButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
self.enableButton.setImage(nil, for: UIControlState())
self.enableButton.titleLabel?.minimumScaleFactor = 0.1
self.enableButton.titleLabel?.adjustsFontSizeToFitWidth = true
self.enableButton.setTitleColor(self.tintColor, for: UIControlState())
self.enableButton.backgroundColor = UIColor.clear
self.enableButton.layer.cornerRadius = 2.0
self.enableButton.layer.borderColor = self.tintColor.cgColor
self.enableButton.layer.borderWidth = 1.0
self.enableButton.clipsToBounds = true
self.enableButton.isUserInteractionEnabled = true
}
@objc fileprivate func _didSelectItem() {
if self.didSelectItem != nil {
self.didSelectItem!(self.permission)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 35.150198 | 254 | 0.753851 |
90f978a2df91eb7ccc34d3490e4a906e2a0e89bc | 9,793 | //
// UserAPI.swift
// TestDemoApp
//
// Created by aniket ayachit on 04/05/19.
// Copyright © 2019 aniket ayachit. All rights reserved.
//
import Foundation
class UserAPI: BaseAPI {
class func signupUser(params: [String: Any],
onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.post(resource: "/signup",
params: params as [String : AnyObject]?,
onSuccess: { (apiParams) in
guard let data = apiParams?["data"] as? [String: Any] else {
onFailure?(apiParams)
return
}
let resultType = data["result_type"] as! String
guard let userData = data[resultType] as? [String: Any] else {
onFailure?(nil)
return
}
onSuccess?(userData)
},
onFailure: onFailure)
}
class func loginUser(params: [String: Any]? = nil,
onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.post(resource: "/login",
params: params as [String : AnyObject]?,
onSuccess: { (apiParams) in
guard let data = apiParams?["data"] as? [String: Any] else {
onFailure?(apiParams)
return
}
let resultType = data["result_type"] as! String
guard let userData = data[resultType] as? [String: Any] else {
onFailure?(nil)
return
}
onSuccess?(userData)
},
onFailure: onFailure)
}
class func getCurrentUser(onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.get(resource: "/users/current-user",
params: nil,
onSuccess: { (apiParams) in
guard let data = apiParams?["data"] as? [String: Any] else {
onFailure?(apiParams)
return
}
let resultType = data["result_type"] as! String
guard let userData = data[resultType] as? [String: Any] else {
onFailure?(nil)
return
}
onSuccess?(userData)
},
onFailure: onFailure)
}
class func notifyUserActivated(onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.post(resource: "/notify/user-activate",
params: nil,
onSuccess: { (apiParams) in
guard let data = apiParams?["data"] as? [String: Any] else {
onFailure?(nil)
return
}
let resultType = data["result_type"] as! String
guard let userData = data[resultType] as? [String: Any] else {
onFailure?(nil)
return
}
onSuccess?(userData)
},
onFailure: onFailure)
}
class func getUserBalance(userId: String,
onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.get(resource: "/users/\(userId)/balance",
params: nil,
onSuccess: { (apiParams) in
guard let data = apiParams?["data"] as? [String: Any] else {
onFailure?(nil)
return
}
let resultType = data["result_type"] as! String
guard let balanceData = data[resultType] as? [String: Any] else {
onFailure?(nil)
return
}
if let pricePoint = data["price_point"] as? [String: Any] {
CurrentUserModel.getInstance.pricePoint = pricePoint
}
onSuccess?(balanceData)
},
onFailure: onFailure)
}
class func updateCrashlyticsPreference(userId: String,
params: [String: Any]?,
onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.post(resource: "/users/\(userId)/set-preference",
params: params as [String: AnyObject]?,
onSuccess: { (apiParams) in
guard let data = (apiParams?["data"] as? [String: Any]) else {
onFailure?(nil)
return
}
onSuccess?(data)
},
onFailure: onFailure)
}
class func getCrashlyticsPreference(userId: String,
params: [String: Any]?,
onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.get(resource: "/users/\(userId)/get-preference",
params: params as [String: AnyObject]?,
onSuccess: { (apiParams) in
guard let data = (apiParams?["data"] as? [String: Any]) else {
onFailure?(nil)
return
}
onSuccess?(data)
},
onFailure: onFailure)
}
class func getUserDetails(onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.get(resource: "/users/current-user",
params: nil,
onSuccess: { (apiParams) in
guard let data = apiParams?["data"] as? [String: Any] else {
onFailure?(nil)
return
}
let resultType = data["result_type"] as! String
guard let userData = data[resultType] as? [String: Any] else {
onFailure?(nil)
return
}
onSuccess?(userData)
},
onFailure: onFailure)
}
class func getUsers(meta: [String: Any]? = nil,
onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.get(resource: "/users",
params: meta as [String : AnyObject]?,
onSuccess: onSuccess,
onFailure: onFailure)
}
class func getCurrentUserSalt(meta: [String: Any]? = nil,
onSuccess: ((String, [String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.get(resource: "/users/current-user-salt",
params: meta as [String : AnyObject]?,
onSuccess: { (apiResponse) in
guard let data = apiResponse?["data"] as? [String: Any] else {
var error:[String: Any] = apiResponse?["error"] as? [String: Any] ?? [:];
error["display_message"] = "Something went wrong";
error["extra_info"] = "Api returned error.";
onFailure?( apiResponse?["error"] as? [String: Any] )
return
}
guard let resultType = data["result_type"] as? String else {
var error:[String: Any] = [:];
error["display_message"] = "Something went wrong";
error["extra_info"] = "Api response is not as expected.";
onFailure?(error);
return;
}
guard let result = data[ resultType ] as? [String: Any] else {
var error:[String: Any] = [:];
error["display_message"] = "Something went wrong";
error["extra_info"] = "Api response is not as expected.";
onFailure?(error);
return;
}
guard let recoveryPinSalt = result["recovery_pin_salt"] as? String else {
var error:[String: Any] = [:];
error["display_message"] = "Something went wrong";
error["extra_info"] = "Api response is not as expected.";
onFailure?(error);
return;
}
onSuccess?(recoveryPinSalt, data);
},
onFailure: { (apiResponse) in
onFailure?( apiResponse?["error"] as? [String: Any] );
});
}
class func logoutUser(onSuccess: (([String: Any]?) -> Void)? = nil,
onFailure: (([String: Any]?) -> Void)? = nil) {
self.post(resource: "/users/logout", params: nil,
onSuccess: onSuccess, onFailure: onFailure)
}
}
| 42.030043 | 98 | 0.419177 |
9b10c67bbc6690f76046f1420ff05b1474d5526c | 4,335 | //
// ViewController.swift
// ios-foundation-notificationcenter-demo
//
// Created by OkuderaYuki on 2017/02/15.
// Copyright © 2017年 YukiOkudera. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let nc = NotificationCenter.default
var observers: NSObjectProtocol?
override func viewDidLoad() {
super.viewDidLoad()
self.registerNotifications()
}
// 別の画面へ遷移したら、通知を解除する
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//MARK: selectorを使用して通知を登録している場合
// 特定の通知のみ解除する
NotificationCenter.default.removeObserver(self,
name: .UIApplicationUserDidTakeScreenshot,
object: nil)
// すべての通知を解除する
NotificationCenter.default.removeObserver(self)
//MARK: closureを使用して通知を登録している場合
if let observers = observers {
NotificationCenter.default.removeObserver(observers)
self.observers = nil
}
}
/// 通知を登録する
private func registerNotifications() {
//MARK: あらかじめ定義されている通知名を使用して通知を登録する
/*
selector版
ユーザがスクリーンショットを撮ったことを検知する
通知された時に呼ばれる処理をSelectorで指定する
*/
nc.addObserver(self,
selector: #selector(type(of: self).detectUserDidTakeScreenshot),
name: .UIApplicationUserDidTakeScreenshot,
object: nil)
/*
closure版
端末の向きが変わったことを検知する
通知された時に呼ばれる処理をClosureで直接記述する
*/
observers = nc.addObserver(forName: .UIDeviceOrientationDidChange,
object: nil,
queue: nil,
using: { (notification) in
print("\(notification.name.rawValue)が通知されました。")
let currentOrientation = UIDevice.current.orientation
if UIDeviceOrientationIsLandscape(currentOrientation) {
print("横向きになりました。")
} else if UIDeviceOrientationIsPortrait(currentOrientation) {
print("縦向きになりました。")
}
})
//MARK: 自作の通知名を使用して通知を登録する
nc.addObserver(self,
selector: #selector(type(of: self).detectCustomNotification),
name: .customNotification,
object: nil)
}
//MARK:- 通知された時に呼ばれる処理
@objc private func detectUserDidTakeScreenshot(notification: Notification) {
print("\(notification.name.rawValue)が通知されました。")
}
@objc private func detectCustomNotification(notification: Notification) {
print("\(notification.name.rawValue)が通知されました。")
/*
通知で文字列を受け取っていたらタイトルに使用する
受け取っていなければ、タイトルは空文字にする
*/
let title = notification.object as? String ?? ""
let message = String(format: "%@が通知されました。",
notification.name.rawValue)
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK",
style: .default,
handler: nil)
alert.addAction(okAction)
// アラートを表示する
present(alert, animated: true, completion: nil)
}
//MARK:- ボタンタップイベント
@IBAction func tappedPostButton(_ sender: Any) {
// ボタンタップでcustomNotificationの通知を送る
//nc.post(name: .customNotification, object: nil)
// 通知を送る際にObjectを渡す場合
let postObject = "NotificationCenter-demo"
nc.post(name: .customNotification, object: postObject)
}
}
/// あらかじめ定義されている通知名と同じように使用するためにExtensionで自作の通知名を定義する
extension NSNotification.Name {
static let customNotification = NSNotification.Name("customNotification")
}
| 33.604651 | 97 | 0.531488 |
0156f9dc81b818ac74ef631d32baff1c0b0b243b | 702 | //
// RepositoriesTableViewCell.swift
// MVC-Code
//
// Created by giftbot on 2017. 9. 27..
// Copyright © 2017년 giftbot. All rights reserved.
//
import UIKit
final class RepositoriesTableViewCell: UITableViewCell {
// MARK: Properties
@IBOutlet private var nameLabel: UILabel!
@IBOutlet private var descLabel: UILabel!
@IBOutlet private var starLabel: UILabel!
@IBOutlet private var forkLabel: UILabel!
// MARK: Configure Cell
func configureWith(name: String, description: String?, star: Int, fork: Int) {
nameLabel.text = name
descLabel.text = description ?? ""
starLabel.text = String(describing: star)
forkLabel.text = String(describing: fork)
}
}
| 24.206897 | 80 | 0.702279 |
72cae5ebd9528c2ecd0d99a068e662a121cf0986 | 21,041 | // 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
//
import CoreFoundation
open class DateFormatter : Formatter {
typealias CFType = CFDateFormatter
private var __cfObject: CFType?
private var _cfObject: CFType {
guard let obj = __cfObject else {
#if os(macOS) || os(iOS)
let dateStyle = CFDateFormatterStyle(rawValue: CFIndex(self.dateStyle.rawValue))!
let timeStyle = CFDateFormatterStyle(rawValue: CFIndex(self.timeStyle.rawValue))!
#else
let dateStyle = CFDateFormatterStyle(self.dateStyle.rawValue)
let timeStyle = CFDateFormatterStyle(self.timeStyle.rawValue)
#endif
let obj = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, dateStyle, timeStyle)!
_setFormatterAttributes(obj)
if let dateFormat = _dateFormat {
CFDateFormatterSetFormat(obj, dateFormat._cfObject)
}
__cfObject = obj
return obj
}
return obj
}
public override init() {
super.init()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
open var formattingContext: Context = .unknown // default is NSFormattingContextUnknown
@available(*, unavailable, renamed: "date(from:)")
func getObjectValue(_ obj: UnsafeMutablePointer<AnyObject?>?,
for string: String,
range rangep: UnsafeMutablePointer<NSRange>?) throws {
NSUnsupported()
}
open override func string(for obj: Any) -> String? {
guard let date = obj as? Date else { return nil }
return string(from: date)
}
open func string(from date: Date) -> String {
return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, _cfObject, date._cfObject)._swiftObject
}
open func date(from string: String) -> Date? {
var range = CFRange(location: 0, length: string.length)
let date = withUnsafeMutablePointer(to: &range) { (rangep: UnsafeMutablePointer<CFRange>) -> Date? in
guard let res = CFDateFormatterCreateDateFromString(kCFAllocatorSystemDefault, _cfObject, string._cfObject, rangep) else {
return nil
}
return res._swiftObject
}
// range.length is updated with the last position of the input string that was parsed
guard range.length == string.length else {
// The whole string was not parsed
return nil
}
return date
}
open class func localizedString(from date: Date, dateStyle dstyle: Style, timeStyle tstyle: Style) -> String {
let df = DateFormatter()
df.dateStyle = dstyle
df.timeStyle = tstyle
return df.string(for: date._nsObject)!
}
open class func dateFormat(fromTemplate tmplate: String, options opts: Int, locale: Locale?) -> String? {
guard let res = CFDateFormatterCreateDateFormatFromTemplate(kCFAllocatorSystemDefault, tmplate._cfObject, CFOptionFlags(opts), locale?._cfObject) else {
return nil
}
return res._swiftObject
}
open func setLocalizedDateFormatFromTemplate(_ dateFormatTemplate: String) {
if let format = DateFormatter.dateFormat(fromTemplate: dateFormatTemplate, options: 0, locale: locale) {
dateFormat = format
}
}
private func _reset() {
__cfObject = nil
}
internal func _setFormatterAttributes(_ formatter: CFDateFormatter) {
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterIsLenient, value: isLenient._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterTimeZone, value: _timeZone?._cfObject)
if let ident = _calendar?.identifier {
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterCalendarName, value: Calendar._toNSCalendarIdentifier(ident).rawValue._cfObject)
} else {
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterCalendarName, value: nil)
}
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterTwoDigitStartDate, value: _twoDigitStartDate?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterDefaultDate, value: defaultDate?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterCalendar, value: _calendar?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterEraSymbols, value: _eraSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterMonthSymbols, value: _monthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortMonthSymbols, value: _shortMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterWeekdaySymbols, value: _weekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortWeekdaySymbols, value: _shortWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterAMSymbol, value: _amSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterPMSymbol, value: _pmSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterLongEraSymbols, value: _longEraSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortMonthSymbols, value: _veryShortMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterStandaloneMonthSymbols, value: _standaloneMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortStandaloneMonthSymbols, value: _shortStandaloneMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortStandaloneMonthSymbols, value: _veryShortStandaloneMonthSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortWeekdaySymbols, value: _veryShortWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterStandaloneWeekdaySymbols, value: _standaloneWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortStandaloneWeekdaySymbols, value: _shortStandaloneWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterVeryShortStandaloneWeekdaySymbols, value: _veryShortStandaloneWeekdaySymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterQuarterSymbols, value: _quarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortQuarterSymbols, value: _shortQuarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterStandaloneQuarterSymbols, value: _standaloneQuarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterShortStandaloneQuarterSymbols, value: _shortStandaloneQuarterSymbols?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFDateFormatterGregorianStartDate, value: _gregorianStartDate?._cfObject)
}
internal func _setFormatterAttribute(_ formatter: CFDateFormatter, attributeName: CFString, value: AnyObject?) {
if let value = value {
CFDateFormatterSetProperty(formatter, attributeName, value)
}
}
private var _dateFormat: String? { willSet { _reset() } }
open var dateFormat: String! {
get {
guard let format = _dateFormat else {
return __cfObject.map { CFDateFormatterGetFormat($0)._swiftObject } ?? ""
}
return format
}
set {
_dateFormat = newValue
}
}
open var dateStyle: Style = .none {
willSet {
_dateFormat = nil
}
didSet {
_dateFormat = CFDateFormatterGetFormat(_cfObject)._swiftObject
}
}
open var timeStyle: Style = .none {
willSet {
_dateFormat = nil
}
didSet {
_dateFormat = CFDateFormatterGetFormat(_cfObject)._swiftObject
}
}
/*@NSCopying*/ internal var _locale: Locale? { willSet { _reset() } }
open var locale: Locale! {
get {
guard let locale = _locale else { return .current }
return locale
}
set {
_locale = newValue
}
}
open var generatesCalendarDates = false { willSet { _reset() } }
/*@NSCopying*/ internal var _timeZone: TimeZone? { willSet { _reset() } }
open var timeZone: TimeZone! {
get {
guard let tz = _timeZone else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterTimeZone) as! NSTimeZone)._swiftObject
}
return tz
}
set {
_timeZone = newValue
}
}
/*@NSCopying*/ internal var _calendar: Calendar! { willSet { _reset() } }
open var calendar: Calendar! {
get {
guard let calendar = _calendar else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterCalendar) as! NSCalendar)._swiftObject
}
return calendar
}
set {
_calendar = newValue
}
}
open var isLenient = false { willSet { _reset() } }
/*@NSCopying*/ internal var _twoDigitStartDate: Date? { willSet { _reset() } }
open var twoDigitStartDate: Date? {
get {
guard let startDate = _twoDigitStartDate else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterTwoDigitStartDate) as? NSDate)?._swiftObject
}
return startDate
}
set {
_twoDigitStartDate = newValue
}
}
/*@NSCopying*/ open var defaultDate: Date? { willSet { _reset() } }
internal var _eraSymbols: [String]! { willSet { _reset() } }
open var eraSymbols: [String]! {
get {
guard let symbols = _eraSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterEraSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_eraSymbols = newValue
}
}
internal var _monthSymbols: [String]! { willSet { _reset() } }
open var monthSymbols: [String]! {
get {
guard let symbols = _monthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterMonthSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_monthSymbols = newValue
}
}
internal var _shortMonthSymbols: [String]! { willSet { _reset() } }
open var shortMonthSymbols: [String]! {
get {
guard let symbols = _shortMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortMonthSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_shortMonthSymbols = newValue
}
}
internal var _weekdaySymbols: [String]! { willSet { _reset() } }
open var weekdaySymbols: [String]! {
get {
guard let symbols = _weekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterWeekdaySymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_weekdaySymbols = newValue
}
}
internal var _shortWeekdaySymbols: [String]! { willSet { _reset() } }
open var shortWeekdaySymbols: [String]! {
get {
guard let symbols = _shortWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortWeekdaySymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_shortWeekdaySymbols = newValue
}
}
internal var _amSymbol: String! { willSet { _reset() } }
open var amSymbol: String! {
get {
guard let symbol = _amSymbol else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterAMSymbol) as! NSString)._swiftObject
}
return symbol
}
set {
_amSymbol = newValue
}
}
internal var _pmSymbol: String! { willSet { _reset() } }
open var pmSymbol: String! {
get {
guard let symbol = _pmSymbol else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterPMSymbol) as! NSString)._swiftObject
}
return symbol
}
set {
_pmSymbol = newValue
}
}
internal var _longEraSymbols: [String]! { willSet { _reset() } }
open var longEraSymbols: [String]! {
get {
guard let symbols = _longEraSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterLongEraSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_longEraSymbols = newValue
}
}
internal var _veryShortMonthSymbols: [String]! { willSet { _reset() } }
open var veryShortMonthSymbols: [String]! {
get {
guard let symbols = _veryShortMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortMonthSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_veryShortMonthSymbols = newValue
}
}
internal var _standaloneMonthSymbols: [String]! { willSet { _reset() } }
open var standaloneMonthSymbols: [String]! {
get {
guard let symbols = _standaloneMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterStandaloneMonthSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_standaloneMonthSymbols = newValue
}
}
internal var _shortStandaloneMonthSymbols: [String]! { willSet { _reset() } }
open var shortStandaloneMonthSymbols: [String]! {
get {
guard let symbols = _shortStandaloneMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortStandaloneMonthSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_shortStandaloneMonthSymbols = newValue
}
}
internal var _veryShortStandaloneMonthSymbols: [String]! { willSet { _reset() } }
open var veryShortStandaloneMonthSymbols: [String]! {
get {
guard let symbols = _veryShortStandaloneMonthSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortStandaloneMonthSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_veryShortStandaloneMonthSymbols = newValue
}
}
internal var _veryShortWeekdaySymbols: [String]! { willSet { _reset() } }
open var veryShortWeekdaySymbols: [String]! {
get {
guard let symbols = _veryShortWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortWeekdaySymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_veryShortWeekdaySymbols = newValue
}
}
internal var _standaloneWeekdaySymbols: [String]! { willSet { _reset() } }
open var standaloneWeekdaySymbols: [String]! {
get {
guard let symbols = _standaloneWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterStandaloneWeekdaySymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_standaloneWeekdaySymbols = newValue
}
}
internal var _shortStandaloneWeekdaySymbols: [String]! { willSet { _reset() } }
open var shortStandaloneWeekdaySymbols: [String]! {
get {
guard let symbols = _shortStandaloneWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortStandaloneWeekdaySymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_shortStandaloneWeekdaySymbols = newValue
}
}
internal var _veryShortStandaloneWeekdaySymbols: [String]! { willSet { _reset() } }
open var veryShortStandaloneWeekdaySymbols: [String]! {
get {
guard let symbols = _veryShortStandaloneWeekdaySymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterVeryShortStandaloneWeekdaySymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_veryShortStandaloneWeekdaySymbols = newValue
}
}
internal var _quarterSymbols: [String]! { willSet { _reset() } }
open var quarterSymbols: [String]! {
get {
guard let symbols = _quarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterQuarterSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_quarterSymbols = newValue
}
}
internal var _shortQuarterSymbols: [String]! { willSet { _reset() } }
open var shortQuarterSymbols: [String]! {
get {
guard let symbols = _shortQuarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortQuarterSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_shortQuarterSymbols = newValue
}
}
internal var _standaloneQuarterSymbols: [String]! { willSet { _reset() } }
open var standaloneQuarterSymbols: [String]! {
get {
guard let symbols = _standaloneQuarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterStandaloneQuarterSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_standaloneQuarterSymbols = newValue
}
}
internal var _shortStandaloneQuarterSymbols: [String]! { willSet { _reset() } }
open var shortStandaloneQuarterSymbols: [String]! {
get {
guard let symbols = _shortStandaloneQuarterSymbols else {
let cfSymbols = CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterShortStandaloneQuarterSymbols) as! NSArray
return cfSymbols.allObjects as! [String]
}
return symbols
}
set {
_shortStandaloneQuarterSymbols = newValue
}
}
internal var _gregorianStartDate: Date? { willSet { _reset() } }
open var gregorianStartDate: Date? {
get {
guard let startDate = _gregorianStartDate else {
return (CFDateFormatterCopyProperty(_cfObject, kCFDateFormatterGregorianStartDate) as? NSDate)?._swiftObject
}
return startDate
}
set {
_gregorianStartDate = newValue
}
}
open var doesRelativeDateFormatting = false { willSet { _reset() } }
}
extension DateFormatter {
public enum Style : UInt {
case none
case short
case medium
case long
case full
}
}
| 39.402622 | 161 | 0.640606 |
714aaa197fcb6f83ceb6a30e21cc85b8da94c9fe | 759 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import Cocoa
class AudioUnitGenericWindow: NSWindowController {
@IBOutlet var scrollView: NSScrollView!
public let toolbar = AudioUnitToolbarController(nibName: "AudioUnitToolbarController", bundle: Bundle.main)
private var audioUnit: AVAudioUnit?
convenience init(audioUnit: AVAudioUnit) {
self.init(windowNibName: "AudioUnitGenericWindow")
contentViewController?.view.wantsLayer = true
self.audioUnit = audioUnit
toolbar.audioUnit = audioUnit
}
override func windowDidLoad() {
super.windowDidLoad()
window?.addTitlebarAccessoryViewController(toolbar)
}
}
| 31.625 | 111 | 0.740448 |
29abad4518686630a0b8de7cafc100b8c4c19eba | 301 | //
// TabbarProtocol.swift
// Template
//
// Created by Levente Vig on 2019. 09. 21..
// Copyright © 2019. levivig. All rights reserved.
//
import UIKit
protocol TabbarProtocol {
var tabbarImage: UIImage? { get }
var selectedTabbarImage: UIImage? { get }
func setTabbarItem()
}
| 17.705882 | 51 | 0.66113 |
f9b6a6cec6e3360f009c3ee3eaa65fb147df16a6 | 3,807 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var SimpleModelTests = TestSuite("SimpleModel")
struct DenseLayer : Equatable {
@differentiable(wrt: self, vjp: vjpW)
let w: Float
func vjpW() -> (Float, (Float) -> DenseLayer) {
return (w, { dw in DenseLayer(w: dw, b: 0) } )
}
@differentiable(wrt: self, vjp: vjpB)
let b: Float
func vjpB() -> (Float, (Float) -> DenseLayer) {
return (b, { db in DenseLayer(w: 0, b: db) } )
}
}
extension DenseLayer : Differentiable, VectorNumeric {
typealias TangentVector = DenseLayer
typealias CotangentVector = DenseLayer
typealias Scalar = Float
static var zero: DenseLayer {
return DenseLayer(w: 0, b: 0)
}
static func + (lhs: DenseLayer, rhs: DenseLayer) -> DenseLayer {
return DenseLayer(w: lhs.w + rhs.w, b: lhs.b + rhs.b)
}
static func - (lhs: DenseLayer, rhs: DenseLayer) -> DenseLayer {
return DenseLayer(w: lhs.w - rhs.w, b: lhs.b - rhs.b)
}
static func * (lhs: DenseLayer, rhs: DenseLayer) -> DenseLayer {
return DenseLayer(w: lhs.w * rhs.w, b: lhs.b * rhs.b)
}
static func * (lhs: Float, rhs: DenseLayer) -> DenseLayer {
return DenseLayer(w: lhs * rhs.w, b: lhs * rhs.b)
}
}
extension DenseLayer {
func prediction(for input: Float) -> Float {
return input * w + b
}
}
struct Model : Equatable {
@differentiable(wrt: self, vjp: vjpL1)
let l1: DenseLayer
func vjpL1() -> (DenseLayer, (DenseLayer) -> Model) {
return (l1, { dl1 in Model(l1: dl1, l2: DenseLayer.zero, l3: DenseLayer.zero) } )
}
@differentiable(wrt: self, vjp: vjpL2)
let l2: DenseLayer
func vjpL2() -> (DenseLayer, (DenseLayer) -> Model) {
return (l2, { dl2 in Model(l1: DenseLayer.zero, l2: dl2, l3: DenseLayer.zero) } )
}
@differentiable(wrt: self, vjp: vjpL3)
let l3: DenseLayer
func vjpL3() -> (DenseLayer, (DenseLayer) -> Model) {
return (l3, { dl3 in Model(l1: DenseLayer.zero, l2: DenseLayer.zero, l3: dl3) } )
}
}
extension Model : Differentiable, VectorNumeric {
typealias TangentVector = Model
typealias CotangentVector = Model
typealias Scalar = Float
static var zero: Model {
return Model(l1: DenseLayer.zero, l2: DenseLayer.zero, l3: DenseLayer.zero)
}
static func + (lhs: Model, rhs: Model) -> Model {
return Model(l1: lhs.l1 + rhs.l1, l2: lhs.l2 + rhs.l2, l3: lhs.l3 + rhs.l3)
}
static func - (lhs: Model, rhs: Model) -> Model {
return Model(l1: lhs.l1 - rhs.l1, l2: lhs.l2 - rhs.l2, l3: lhs.l3 - rhs.l3)
}
static func * (lhs: Model, rhs: Model) -> Model {
return Model(l1: lhs.l1 * rhs.l1, l2: lhs.l2 * rhs.l2, l3: lhs.l3 * rhs.l3)
}
static func * (lhs: Float, rhs: Model) -> Model {
return Model(l1: lhs * rhs.l1, l2: lhs * rhs.l2, l3: lhs * rhs.l3)
}
}
extension Model {
func prediction(for input: Float) -> Float {
// This "model" is silly because it doesn't have nonlinearities. But it's
// simple and good enough for testing purposes.
let activation1 = l1.prediction(for: input)
let activation2 = l2.prediction(for: activation1)
return l3.prediction(for: activation2)
}
func loss(of prediction: Float, from label: Float) -> Float {
return (prediction - label) * (prediction - label)
}
}
SimpleModelTests.test("gradient") {
let layer = DenseLayer(w: 1.0, b: 0.0)
let model = Model(l1: layer, l2: layer, l3: layer)
let label: Float = 3
let input: Float = 1
let gradModel = model.gradient { model -> Float in
let pred = model.prediction(for: input)
return model.loss(of: pred, from: label)
}
let expectedGrad = Model(l1: DenseLayer(w: -4, b: -4),
l2: DenseLayer(w: -4, b: -4),
l3: DenseLayer(w: -4, b: -4))
expectEqual(expectedGrad, gradModel)
}
runAllTests()
| 31.725 | 85 | 0.638035 |
dd1ca8f1a7a9e8277efe5af258cba93d0ba8981f | 886 | import Foundation
extension Service {
open class Outlet: Service {
public init(characteristics: [AnyCharacteristic] = []) {
var unwrapped = characteristics.map { $0.wrapped }
powerState = getOrCreateAppend(
type: .powerState,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.powerState() })
name = get(type: .name, characteristics: unwrapped)
outletInUse = get(type: .outletInUse, characteristics: unwrapped)
super.init(type: .outlet, characteristics: unwrapped)
}
// MARK: - Required Characteristics
public let powerState: GenericCharacteristic<Bool>
// MARK: - Optional Characteristics
public let name: GenericCharacteristic<String>?
public let outletInUse: GenericCharacteristic<Bool>?
}
}
| 36.916667 | 77 | 0.632054 |
9048a916e9104d810f243ecb74e05c34184c08c9 | 4,801 | import HTTP
import DatabaseKit
/// A Elasticsearch client.
public final class ElasticsearchClient: DatabaseConnection, BasicWorker {
public typealias Database = ElasticsearchDatabase
/// See `BasicWorker`.
public var eventLoop: EventLoop {
return worker.eventLoop
}
/// See `DatabaseConnection`.
public var isClosed: Bool
/// See `Extendable`.
public var extend: Extend
/// The HTTP connection
private let esConnection: HTTPClient
public let worker: Worker
internal let encoder = JSONEncoder()
internal let decoder = JSONDecoder()
internal var isConnected: Bool
internal let config: ElasticsearchClientConfig
/// Creates a new Elasticsearch client.
init(client: HTTPClient, config: ElasticsearchClientConfig, worker: Worker) {
self.esConnection = client
self.extend = [:]
self.isClosed = false
self.isConnected = false
self.config = config
self.worker = worker
}
/// Closes this client.
public func close() {
self.isClosed = true
esConnection.close().do() {
self.isClosed = true
self.isConnected = false
}.catch() { error in
self.isClosed = true
self.isConnected = false
}
}
internal static func generateURL(
path: String,
routing: String? = nil,
version: Int? = nil,
storedFields: [String]? = nil,
realtime: Bool? = nil,
forceCreate: Bool? = nil
) -> URLComponents {
var url = URLComponents()
url.path = path
var query = [URLQueryItem]()
if routing != nil {
query.append(URLQueryItem(name: "routing", value: routing))
}
if version != nil {
query.append(URLQueryItem(name: "version", value: "\(version!)"))
}
if storedFields != nil {
query.append(URLQueryItem(name: "stored_fields", value: storedFields?.joined(separator: ",")))
}
if realtime != nil {
query.append(URLQueryItem(name: "realtime", value: realtime! ? "true" : "false"))
}
url.queryItems = query
return url
}
public func send(
_ method: HTTPMethod,
to path: String
) throws -> Future<Data> {
let httpReq = HTTPRequest(method: method, url: path)
return try send(httpReq)
}
public func send(
_ method: HTTPMethod,
to path: String,
with body: Dictionary<String, Any>
) throws -> Future<Data> {
let jsonData = try JSONSerialization.data(withJSONObject: body, options: [])
return try send(method, to: path, with: jsonData)
}
public func send(
_ method: HTTPMethod,
to path: String,
with body: Data
) throws -> Future<Data> {
let httpReq = HTTPRequest(method: method, url: path, body: HTTPBody(data: body))
return try send(httpReq)
}
public func send(
_ request: HTTPRequest
) throws -> Future<Data> {
var request = request
request.headers.add(name: "Content-Type", value: "application/json")
if self.config.username != nil && self.config.password != nil {
let token = "\(config.username!):\(config.password!)".data(using: String.Encoding.utf8)?.base64EncodedString()
if token != nil {
request.headers.add(name: "Authorization", value: "Basic \(token!)")
}
}
// TODO should be debug logged
print(request.description)
return self.esConnection.send(request).map(to: Data.self) { response in
if response.body.data == nil {
throw ElasticsearchError(identifier: "empty_response", reason: "Missing response body from Elasticsearch", source: .capture())
}
if response.status.code >= 400 {
guard let json = try JSONSerialization.jsonObject(with: response.body.data!, options: []) as? [String: Any] else {
throw ElasticsearchError(identifier: "invalid_response", reason: "Cannot parse response body from Elasticsearch", source: .capture())
}
let error = json["error"] as! Dictionary<String, Any>
throw ElasticsearchError(identifier: "elasticsearch_error", reason: error.description, source: .capture(), statusCode: response.status.code)
}
// TODO should be debug logged
let bodyString = String(data: response.body.data!, encoding: String.Encoding.utf8) as String?
print(bodyString!)
return response.body.data!
}
}
}
| 33.809859 | 156 | 0.583628 |
8f6d05f88e68932f33cca1eeb6ddad14d44a3314 | 1,109 | //
// AndesTextFieldStateWarning.swift
// AndesUI
//
// Created by Oscar Sierra Zuniga on 2/02/21.
//
import Foundation
struct AndesTextFieldStateWarning: AndesTextFieldStateProtocol {
var borderColor = AndesStyleSheetManager.styleSheet.feedbackColorWarning
var borderWidth: CGFloat = 1
var borderDashed: Bool = false
var labelTextColor = AndesStyleSheetManager.styleSheet.textColorWarning
var helperColor = AndesStyleSheetManager.styleSheet.textColorWarning
var helperIconTintColor: UIColor? = AndesStyleSheetManager.styleSheet.textColorWhite
var helperIconName: String? = "andes_ui_feedback_error_16"
var helperSemibold: Bool = true
var backgroundColor = AndesStyleSheetManager.styleSheet.bgColorWhite
var inputTextColor = AndesStyleSheetManager.styleSheet.textColorPrimary
var editingEnabled = true
var placeholderTextColor = AndesStyleSheetManager.styleSheet.textColorSecondary
init(focuesd: Bool) {
if focuesd {
backgroundColor = AndesStyleSheetManager.styleSheet.bgColorWhite
borderWidth = 2
}
}
}
| 32.617647 | 88 | 0.766456 |
2f4ffe28dceab05857316a556e9d96710466d626 | 3,957 | //
// SubjectConcurrencyTest.swift
// RxTests
//
// Created by Krunoslav Zaher on 11/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import XCTest
class ReplaySubjectConcurrencyTest : SubjectConcurrencyTest {
override func createSubject() -> (Observable<Int>, AnyObserver<Int>) {
let s = ReplaySubject<Int>.create(bufferSize: 1)
return (s.asObservable(), AnyObserver(eventHandler: s.asObserver().on))
}
}
class BehaviorSubjectConcurrencyTest : SubjectConcurrencyTest {
override func createSubject() -> (Observable<Int>, AnyObserver<Int>) {
let s = BehaviorSubject<Int>(value: -1)
return (s.asObservable(), AnyObserver(eventHandler: s.asObserver().on))
}
}
class SubjectConcurrencyTest : RxTest {
// default test is for publish subject
func createSubject() -> (Observable<Int>, AnyObserver<Int>) {
let s = PublishSubject<Int>()
return (s.asObservable(), AnyObserver(eventHandler: s.asObserver().on))
}
}
extension SubjectConcurrencyTest {
func testSubjectIsSynchronized() {
let (observable, _observer) = createSubject()
let o = RxMutableBox(_observer)
var allDone = false
var state = 0
_ = observable.subscribeNext { [unowned o] n in
if n < 0 {
return
}
if state == 0 {
state = 1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
o.value.on(.Next(1))
}
// if other thread can't fulfill the condition in 0.5 sek, that means it is synchronized
NSThread.sleepForTimeInterval(0.5)
XCTAssertEqual(state, 1)
dispatch_async(dispatch_get_main_queue()) {
o.value.on(.Next(2))
}
}
else if state == 1 {
XCTAssertTrue(!isMainThread())
state = 2
}
else if state == 2 {
XCTAssertTrue(isMainThread())
allDone = true
}
}
_observer.on(.Next(0))
// wait for second
for _ in 0 ..< 10 {
NSRunLoop.currentRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(0.1))
if allDone {
break
}
}
XCTAssertTrue(allDone)
}
func testSubjectIsReentrantForNextAndComplete() {
let (observable, _observer) = createSubject()
var state = 0
let o = RxMutableBox(_observer)
var ranAll = false
_ = observable.subscribeNext { [unowned o] n in
if n < 0 {
return
}
if state == 0 {
state = 1
// if isn't reentrant, this will cause deadlock
o.value.on(.Next(1))
}
else if state == 1 {
// if isn't reentrant, this will cause deadlock
o.value.on(.Completed)
ranAll = true
}
}
o.value.on(.Next(0))
XCTAssertTrue(ranAll)
}
func testSubjectIsReentrantForNextAndError() {
let (observable, _observer) = createSubject()
var state = 0
let o = RxMutableBox(_observer)
var ranAll = false
_ = observable.subscribeNext { [unowned o] n in
if n < 0 {
return
}
if state == 0 {
state = 1
// if isn't reentrant, this will cause deadlock
o.value.on(.Next(1))
}
else if state == 1 {
// if isn't reentrant, this will cause deadlock
o.value.on(.Error(testError))
ranAll = true
}
}
o.value.on(.Next(0))
XCTAssertTrue(ranAll)
}
}
| 26.38 | 104 | 0.528431 |
23c454f6f157369f620b5e8bdcd4201334a63ace | 1,041 | //
// LoginModelView.swift
// Slack001
//
// Created by Ankit Kumar Bharti on 07/09/18.
// Copyright © 2018 Exilant. All rights reserved.
//
import Cocoa
class LoginModelView: NSView {
@IBOutlet weak var view: NSView!
var didClose: (() -> ())?
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
Bundle.main.loadNibNamed(NSNib.Name("\(LoginModelView.self)"), owner: self, topLevelObjects: nil)
addSubview(self.view)
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
setupView()
}
private func setupView() {
self.view.frame = NSRect(x: 0, y: 0, width: 475, height: 300)
self.view.wantsLayer = true
self.view.layer?.backgroundColor = CGColor.white
self.view.layer?.cornerRadius = 10.0
}
@IBAction func closeModel(_ sender: Any) {
didClose?()
}
}
| 24.785714 | 105 | 0.612872 |
33923295d071771336ba2fe49ecd15c428e18f8c | 16,944 | ////
//// FileTreeViewController4.swift
//// RustCodeEditor
////
//// Created by Hoon H. on 11/13/14.
//// Copyright (c) 2014 Eonil. All rights reserved.
////
//
//import Foundation
//import AppKit
//import EonilDispatch
//import Precompilation
//
//
//
//
//
//protocol FileTreeViewController4Delegate: class {
// func fileTreeViewController4NotifyKillingRootURL()
//}
//
//
/////
/////
///// Take care that the file-system monitoring can be suspended by request,
///// and this class is using it to suspend file-system monitoring events
///// while column editing.
//class FileTreeViewController4 : NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate, NSMenuDelegate, NSTextFieldDelegate, FileTableCellTextFieldEditingDelegate {
// weak var delegate:FileTreeViewController4Delegate?
//
// /// Directories are excluded.
// let userIsWantingToEditFileAtURL = Notifier<NSURL>()
//
// private var _fileTreeRepository = nil as FileTreeRepository4?
// private var _fileSystemMonitor = nil as FileSystemMonitor3?
//
//
//
//
//
//
// /// Gets and sets URL for root node.
// var URLRepresentation:NSURL? {
// get {
// return self.representedObject as NSURL?
// }
// set(v) {
// self.representedObject = v
// }
// }
//
// /// Notifies invlidation of a node.
// /// The UI will be updated to reflect the invalidation.
// func invalidateNodeForURL(u:NSURL) {
// assert(NSThread.currentThread() == NSThread.mainThread())
// assert(_fileTreeRepository != nil)
// Debug.log("invalidateNodeForURL: \(u)")
//
// if u == URLRepresentation {
// self.delegate?.fileTreeViewController4NotifyKillingRootURL()
// self.URLRepresentation = nil // Self-destruction.
// self.outlineView.reloadData()
// return
// }
//
// let u2 = u.URLByDeletingLastPathComponent!
//
// // File-system notifications are sent asynchronously,
// // then a file-node for the URL may not exist.
// if let n1 = _fileTreeRepository![u2] {
// // Store currently selected URLs.
// // Getting and setting selection can show unexpected behavior if it is being performed
// // while a column is in editing. So ensure this will not be called while editing.
// let selus1 = outlineView.selectedRowIndexes.allIndexes.map { idx in
// return self.outlineView.itemAtRow(idx) as? FileNode4
// }.filter { (n:FileNode4?)->(Bool) in
// return n !== nil
// }.map { n in
// return n!.link
// } as [NSURL]
//
//// let selus0 = outlineView.selectedRowIndexes
//// let selus1 = selus0.allIndexes.map { (idx:Int)->(NSURL?) in
//// let node1 = self.outlineView.itemAtRow(idx) as FileNode4?
//// let url1 = node1?.link as NSURL?
//// return url1
//// }.filter { u in
//// return u != nil
//// }.map { u in
//// return u!
//// } as [NSURL]
//
//
// func reloadingOnlyChangedPortions() {
// func collectAllCurrentlyDisplayingNodes() -> [FileNode4] {
// var dns1 = [] as [FileNode4]
// for i in 0..<self.outlineView.numberOfRows {
// let dn1 = self.outlineView.itemAtRow(i)! as FileNode4
// dns1.append(dn1)
// }
// return dns1
// }
//
//// let oldlnks = n1.subnodes.links
//
// // Perform reloading.
// n1.reloadSubnodes()
// outlineView.reloadItem(n1, reloadChildren: true)
//
////
//// let n2 = n1.subnodes[0]
//// println(n2.link)
//// outlineView.reloadItem(n2, reloadChildren: false)
// }
//
// reloadingOnlyChangedPortions()
//
//
// // Restore previously selected URLs.
// // Just skip disappeared/missing URLs.
//// let selns2 = selus1.map({self._fileTreeRepository![$0]}).filter({$0 != nil})
//// let selrs3 = selns2.map({self.outlineView.rowForItem($0!)}).filter({$0 != -1})
//// let selrs4 = NSIndexSet(selrs3)
//// outlineView.selectRowIndexes(selrs4, byExtendingSelection: false)
//
// Debug.log("Tree partially reloaded.")
// }
// }
//
//
//
//
//
//
//
//
// override var representedObject:AnyObject? {
// willSet(v) {
// precondition(v == nil || v is NSURL)
//
// _fileSystemMonitor = nil
// _fileTreeRepository = nil
// }
// didSet {
// assert(URLRepresentation == nil || URLRepresentation?.existingAsDirectoryFile == true)
//
// if let v3 = URLRepresentation {
// _fileTreeRepository = FileTreeRepository4(rootlink: v3)
// _fileTreeRepository!.reload()
//
// let callback = { [weak self] (u:NSURL)->() in
// self?.invalidateNodeForURL(u)
// return ()
// }
// _fileSystemMonitor = FileSystemMonitor3(monitoringRootURL: v3, callback: callback)
// }
// self.outlineView.reloadData()
// if URLRepresentation != nil {
// self.outlineView.expandItem(_fileTreeRepository!.root, expandChildren: false)
// }
// }
// }
//
// var outlineView:NSOutlineView {
// get {
// return self.view as NSOutlineView
// }
// set(v) {
// self.view = v
// }
// }
// override func loadView() {
// super.view = NSOutlineView()
// }
// override func viewDidLoad() {
// super.viewDidLoad()
//
// let col1 = NSTableColumn(identifier: NAME, title: "Name", width: 100)
//
// outlineView.addTableColumn <<< col1
// outlineView.outlineTableColumn = col1
// outlineView.rowSizeStyle = NSTableViewRowSizeStyle.Small
// outlineView.selectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList
// outlineView.allowsMultipleSelection = true
// outlineView.focusRingType = NSFocusRingType.None
// outlineView.headerView = nil
// outlineView.doubleAction = "dummyDoubleAction:" // This is required to make column editing to be started with small delay like renaming in Finder.
//
// outlineView.sizeLastColumnToFit()
//
// outlineView.setDataSource(self)
// outlineView.setDelegate(self)
//
// outlineView.menu = NSMenu()
// outlineView.menu!.delegate = self
//
// ////
//
// func getURLFromRowAtIndex(v:NSOutlineView, index:Int) -> NSURL {
// let n = v.itemAtRow(index) as FileNode4
// return n.link
// }
// func getURLFromClickingPoint(v:NSOutlineView) -> NSURL? {
// let r1 = v.clickedRow
// if r1 >= 0 {
// return getURLFromRowAtIndex(v, r1)
// } else {
// return nil
// }
// }
// func collectTargetFileURLs(v:NSOutlineView) -> [NSURL] {
//
// func getURLsFromSelection(v:NSOutlineView) -> [NSURL] {
// return
// v.selectedRowIndexes.allIndexes.map { idx in
// return getURLFromRowAtIndex(v, idx)
// }
// }
//
// let clickingURL = getURLFromClickingPoint(v)
// let selectingURLs = getURLsFromSelection(v)
// if clickingURL == nil {
// return selectingURLs
// }
//
// if contains(selectingURLs, clickingURL!) {
// return selectingURLs
// } else {
// return [clickingURL!]
// }
// }
//
// func getParentFolderURLOfClickingPoint(v:NSOutlineView) -> NSURL? {
// if let u2 = getURLFromClickingPoint(v) {
// let parentFolderURL = u2.existingAsDirectoryFile ? u2 : u2.URLByDeletingLastPathComponent!
// assert(parentFolderURL.existingAsDirectoryFile)
// return parentFolderURL
// }
// return nil
// }
//
// outlineView.menu!.addItem(NSMenuItem(title: "Show in Finder", reaction: { [unowned self] () -> () in
// let targetURLs = collectTargetFileURLs(self.outlineView)
// NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs(targetURLs)
// }))
//
// outlineView.menu!.addSeparatorItem()
//
// outlineView.menu!.addItem(NSMenuItem(title: "New File", reaction: { [unowned self] () -> () in
// if let parentFolderURL = getParentFolderURLOfClickingPoint(self.outlineView) {
// let r = FileUtility.createNewFileInFolder(parentFolderURL)
// if r.ok {
// let newFolderURL = r.value!
// let parentNode = self._fileTreeRepository![parentFolderURL]! // Must be exists.
// parentNode.reloadSubnodes()
//
// let n1 = self._fileTreeRepository![newFolderURL] // Can be `nil` if the newly created directory has been deleted immediately. This is very unlikely to happen, but possible in theory.
// if let newFolderNode = n1 {
// self.outlineView.reloadItem(parentNode, reloadChildren: true) // Refresh view.
// self.outlineView.expandItem(parentNode)
//
// let idx = self.outlineView.rowForItem(newFolderNode) // Now it should have a node for the URL.
// assert(idx >= 0)
// if idx >= 0 {
// self.outlineView.selectRowIndexes(NSIndexSet(), byExtendingSelection: false)
// self.outlineView.selectRowIndexes(NSIndexSet(index: idx), byExtendingSelection: true)
//
//// if self._fileSystemMonitor!.isPending == false {
//// self._fileSystemMonitor!.suspendEventCallbackDispatch()
//// }
// self.outlineView.editColumn(0, row: idx, withEvent: nil, select: true)
// } else {
// // Shouldn't happen, but nobody knows...
// }
// }
// } else {
// self.presentError(r.error!)
// }
// } else {
// // Ignore. Happens by clicking empty space.
// }
// }))
//
// outlineView.menu!.addItem(NSMenuItem(title: "New Folder", reaction: { [unowned self] () -> () in
// if let parentFolderURL = getParentFolderURLOfClickingPoint(self.outlineView) {
// let r = FileUtility.createNewFolderInFolder(parentFolderURL)
// if r.ok {
// let newFolderURL = r.value!
// let parentNode = self._fileTreeRepository![parentFolderURL]! // Must be exists.
// parentNode.reloadSubnodes()
//
// let n1 = self._fileTreeRepository![newFolderURL] // Can be `nil` if the newly created directory has been deleted immediately. This is very unlikely to happen, but possible in theory.
// if let newFolderNode = n1 {
// self.outlineView.reloadItem(parentNode, reloadChildren: true) // Refresh view.
// self.outlineView.expandItem(parentNode)
//
// let idx = self.outlineView.rowForItem(newFolderNode) // Now it should have a node for the URL.
// assert(idx >= 0)
// if idx >= 0 {
// self.outlineView.selectRowIndexes(NSIndexSet(), byExtendingSelection: false)
// self.outlineView.selectRowIndexes(NSIndexSet(index: idx), byExtendingSelection: true)
//
//// if self._fileSystemMonitor!.isPending == false {
//// self._fileSystemMonitor!.suspendEventCallbackDispatch()
//// }
// self.outlineView.editColumn(0, row: idx, withEvent: nil, select: true)
// } else {
// // Shouldn't happen, but nobody knows...
// }
// }
// } else {
// self.presentError(r.error!)
// }
// } else {
// // Ignore. Happens by clicking empty space.
// }
// }))
//
// outlineView.menu!.addSeparatorItem()
//
// outlineView.menu!.addItem(NSMenuItem(title: "Delete", reaction: { [unowned self] () -> () in
// let targetURLs = collectTargetFileURLs(self.outlineView)
// if targetURLs.count > 0 {
// UIDialogues.queryDeletingFilesUsingWindowSheet(self.outlineView.window!, files: targetURLs, handler: { (b:UIDialogueButton) -> () in
// switch b {
// case .OKButton:
// for u in targetURLs {
// var err = nil as NSError?
// let ok = NSFileManager.defaultManager().trashItemAtURL(u, resultingItemURL: nil, error: &err)
// assert(ok || err != nil)
// if !ok {
// self.outlineView.presentError(err!)
// }
// }
//
// case .CancelButton:
// break
// }
// })
// }
// }))
//
//
// }
//
//
//
//
//
//
//
//
//
//
//
//
// @objc
// func dummyDoubleAction(AnyObject?) {
// println("AA")
// }
//
//
//// func outlineView(outlineView: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat {
//// return 16
//// }
//
// func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
// let n1 = item as FileNode4?
// if let n2 = n1 {
// if n2.subnodes.count == 0 {
// n2.reloadSubnodes()
// }
// return n2.subnodes.count
// } else {
// return _fileTreeRepository?.root == nil ? 0 : 1
// }
// }
// func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
// let n1 = item as FileNode4?
// if let n2 = n1 {
// return n2.subnodes[index]
// } else {
// return _fileTreeRepository!.root!
// }
// }
//
//// func outlineView(outlineView: NSOutlineView, isGroupItem item: AnyObject) -> Bool {
//// let n1 = item as FileNode4
//// let ns2 = n1.subnodes
//// return ns2 != nil
//// }
//
// func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
// let n1 = item as FileNode4
// return n1.directory
// }
//
// func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? {
// let tv1 = FileTableCellTextField()
// let iv1 = NSImageView()
// let cv1 = FileTableCellView()
// cv1.textField = tv1
// cv1.imageView = iv1
// cv1.addSubview(tv1)
// cv1.addSubview(iv1)
//
// tv1.editingDelegate = self
//
// /// Do not query on file-system here.
// /// The node is a local cache, and may not exist on
// /// underlying file-system.
// /// This is especially true for kqueue/GCD notification.
// /// GCD VNODE notifications are fired asynchronously, and
// /// the actual file can be already gone at the time of the
// /// notification arrives. In other words, file operation
// /// does not wait for notification returns.
// /// So do not query on file-system at this point, and just
// /// use cached data on the node.
//
// let n1 = item as FileNode4
// iv1.image = n1.icon
// cv1.textField!.stringValue = n1.displayName
// cv1.textField!.bordered = false
// cv1.textField!.backgroundColor = NSColor.clearColor()
// cv1.textField!.delegate = self
//
// (cv1.textField!.cell() as NSCell).lineBreakMode = NSLineBreakMode.ByTruncatingTail
// cv1.objectValue = n1.link.lastPathComponent
// cv1.textField!.stringValue = n1.link.lastPathComponent!
// return cv1
// }
//
//
//
// func outlineViewSelectionDidChange(notification: NSNotification) {
// let idx1 = self.outlineView.selectedRow
// if idx1 >= 0 {
// let n1 = self.outlineView.itemAtRow(idx1) as FileNode4
// userIsWantingToEditFileAtURL.signal(n1.link)
// }
// }
// func outlineViewItemDidCollapse(notification: NSNotification) {
// assert(notification.name == NSOutlineViewItemDidCollapseNotification)
// let n1 = notification.userInfo!["NSObject"]! as FileNode4
// n1.resetSubnodes()
// }
//
// func menuNeedsUpdate(menu: NSMenu) {
//// outlineView.selectedRowIndexes
// }
//
// private func fileTableCellTextFieldDidBecomeFirstResponder() {
//// if _fileSystemMonitor!.isPending == false {
// _fileSystemMonitor!.suspendEventCallbackDispatch()
//// }
// }
// private func fileTableCellTextFieldDidResignFirstResponder() {
//// if _fileSystemMonitor!.isPending {
// _fileSystemMonitor!.resumeEventCallbackDispatch() // This will trigger sending of pended events, and effectively reloading of some nodes.
//// }
// }
//// func control(control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
//// if _fileSystemMonitor!.isPending == false {
//// _fileSystemMonitor!.suspendEventCallbackDispatch()
//// }
//// return true
//// }
//// func control(control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
//// return true
//// }
//// override func controlTextDidEndEditing(obj: NSNotification) {
//// Debug.log("controlTextDidEndEditing")
////
//// if _fileSystemMonitor!.isPending {
//// _fileSystemMonitor!.resumeEventCallbackDispatch() // This will trigger sending of pended events, and effectively reloading of some nodes.
//// }
//// }
//}
//
//@objc
//class FileTableRowView: NSTableRowView {
// @objc
// var objectValue:AnyObject? {
// get {
// return "AAA"
// }
// set(v) {
//
// }
// }
//}
//@objc
//class FileTableCellView: NSTableCellView {
// @objc
// override var acceptsFirstResponder:Bool {
// get {
// return true
// }
// }
// @objc
// override func becomeFirstResponder() -> Bool {
// return true
// }
//}
//@objc
//private class FileTableCellTextField: NSTextField {
// weak var editingDelegate:FileTableCellTextFieldEditingDelegate?
//
// @objc
// override var acceptsFirstResponder:Bool {
// get {
// return true
// }
// }
// @objc
// override func becomeFirstResponder() -> Bool {
// editingDelegate?.fileTableCellTextFieldDidBecomeFirstResponder()
// return true
// }
// @objc
// override func resignFirstResponder() -> Bool {
// editingDelegate?.fileTableCellTextFieldDidResignFirstResponder()
// return true
// }
//}
//
//private protocol FileTableCellTextFieldEditingDelegate: class {
// func fileTableCellTextFieldDidBecomeFirstResponder()
// func fileTableCellTextFieldDidResignFirstResponder()
//}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//private let NAME = "NAME"
//
//
//
//
//
////private final class MenuManager : NSObject, NSMenuDelegate {
////
//// func menuNeedsUpdate(menu: NSMenu) {
////
//// }
////}
//
//
//
//
//
//
//
//
| 29.570681 | 190 | 0.652975 |
39d9a95749f609c97c2e631b903e3b9fdfa8f9b3 | 1,087 | //
// AuthKeyChainManager.swift
// AppEmpresas
//
// Created by Matheus Lima on 26/09/20.
//
import Foundation
import KeychainSwift
class AuthKeyChainManager {
static let shared = AuthKeyChainManager()
private let kAuthCredentialsKey = "auth_credentials_key"
private let keychain = KeychainSwift()
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
func storeAuth(accessToken: String, client: String, uid: String) {
let authCredentials = AuthCredentials(accessToken: accessToken, client: client, uid: uid)
guard let authCredentialsEncoded = try? self.encoder.encode(authCredentials) else {
return
}
self.keychain.set(authCredentialsEncoded, forKey: kAuthCredentialsKey)
}
func getAuthStoraged() -> AuthCredentials? {
guard let authCredentialsData = self.keychain.getData(kAuthCredentialsKey) else {
return nil
}
return try? self.decoder.decode(AuthCredentials.self, from: authCredentialsData)
}
}
| 27.871795 | 97 | 0.674333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.