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
|
---|---|---|---|---|---|
ab97d0be8b048392c7acb91a553bbf6de6d5c571
| 1,903 |
import Foundation
import UIKit
/// The base label that includes useful functionalities which occur commonly for a `UILabel`.
///
/// To apply automatic styling using the interface builder you can create many subclasses of
/// `Label` and apply custom stylings and inherit the labels inside of the interface builder
/// from your styles label classes.
///
/// Example:
///
/// ```swift
/// final class HeadlineLabel: Label {
/// // ... applies headline semantics related styling to itself ...
/// }
/// ```
@IBDesignable
open class Label: UILabel {
/// The localization key to be used to localize the content text of the label.
@IBInspectable
private(set) var localizationKey: String?
public override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
viewDidLoad()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
defaultInit()
viewDidLoad()
}
private func defaultInit() {
backgroundColor = .clear
if let localizationKey = localizationKey {
text = NSLocalizedString(localizationKey, bundle: Bundle(for: type(of: self)), comment: "")
}
}
/// This method is intended to be overridden by a subclass to perform setup after the initialization of the label.
///
/// - Attention: Always ensure calling `super.viewDidLoad()` to avoid unexpected behaviour.
open func viewDidLoad() {}
/// This method is intended to be overridden by a subclass to listen for state changes.
///
/// - Attention: Always ensure calling `super.didChangeModel()` to avoid unexpected behaviour.
open func didChangeModel() {}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
defaultInit()
}
}
| 28.833333 | 118 | 0.667367 |
e59ca186438e0b106c4aca305816288a8992b077
| 10,392 |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
func b(c) -> <d>(() -> d) {
}
func q(v: h) -> <r>(() -> r) -> h {
n { u o "\(v): \(u())" }
}
struct e<r> {
j p: , () -> ())] = []
}
protocol p {
}
protocol m : p {
}
protocol v : p {
}
protocol m {
v = m
}
func s<s : m, v : m u v.v == s> (m: v) {
}
func s<v : m u v.v == v> (m: v) {
}
s( {
({})
}
t
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
protocol a {
}
protocol h : a {
}
protocol k : a {
}
protocol g {
j n = a
}
struct n : g {
j n = h
}
func i<h : h, f : g m f.n == h> (g: f) {
}
func i<n : g m n.n = o) {
}
let k = a
k()
h
protocol k : h { func h
k
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
}
class i {
func d((h: (Any, AnyObject)) {
d(h)
}
}
d
h)
func d<i>() -> (i, i -> i) -> i {
i j i.f = {
}
protocol d {
class func f()
}
class i: d{ class func f {}
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e())
class l {
func f((k, l() -> f
}
class d
}
class i: d, g {
l func d() -> f {
m ""
}
}
}
func m<j n j: g, j: d
let l = h
l()
f
protocol l : f { func f
protocol g
func g<h>() -> (h, h -> h) -> h {
f f: ((h, h -> h) -> h)!
j f
}
protocol f {
class func j()
}
struct i {
f d: f.i
func j() {
d.j()
}
}
class g {
typealias f = f
}
func g(f: Int = k) {
}
let i = g
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
struct c<d : Sequence> {
var b: [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type
func e() {
d.e()
}
}
b
protocol c : b { func b
otocol A {
E == F>(f: B<T>)
}
struct }
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
func ^(d: e, Bool) -> Bool {g !(d)
}
protocol d {
f func g()
f e: d {
f func g() { }
}
(e() h d).i()
e
protocol g : e { func e
func a(b: Int = 0) {
}
let c = a
c()
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
class func s()
}
class p: m{ class func s {}
s p {
func m() -> String
}
class n {
func p() -> String {
q ""
}
}
class e: n, p {
v func> String {
q ""
}
{
r m = m
}
func s<o : m, o : p o o.m == o> (m: o) {
}
func s<v : p o v.m == m> (u: String) -> <t>(() -> t) -
func p<p>() -> (p, p -> p) -> p {
l c l.l = {
}
{
p) {
(e: o, h:o) -> e
})
}
j(k(m, k(2, 3)))
func l(p: j) -> <n>(() -> n
struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
d = i
}
class d<j : i, f : i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
typealias i
}
protocol e {
class func i()
}
i
(d() as e).j.i()
d
protocol i : d { func d
class k<g>: d {
var f: g
init(f: g) {
self.f = f
l. d {
typealias i = l
typealias j = j<i<l>, i>
}
class j {
typealias d = d
struct A<T> {
let a: [(T, () -> ())] = []
}
func b<d-> d { class d:b class b
class A<T : A> {
}
func c<d {
enum c {
func e
var _ = e
}
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicl A {
{
typealias b = b
d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}}
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}
{
m) {
n }
}
protocol f {
class func i()
}
class e: f{ class func i {}
func n<j>() -> (j, j -> j) -> j {
var m: ((j> j)!
f m
}
protocol k {
typealias m
}
struct e<j : k> {n: j
let i: j.m
}
l
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
import Foundation
class Foo<T>: NSObject {
var foo: T
init(foo: T) {
B>(t: T) {
t.c()
} x
x) {
}
class a {
var _ = i() {
}
}
a=1 as a=1
func k<q>() -> [n<q>] {
r []
}
func k(l: Int = 0) {
}
n n = k
n()
func n<q {
l n {
func o
o _ = o
}
}
func ^(k: m, q) -> q {
r !(k)
}
protocol k {
j q
j o = q
j f = q
}
class l<r : n, l : n p r.q == l> : k {
}
class l<r, l> {
}
protocol n {
j q
}
protocol k : k {
}
class k<f : l, q : l p f.q == q> {
}
protocol l {
j q
j o
}
struct n<r : l>
func k<q {
enum k {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
func b((Any, e))(e: (Any) -> <d>(()-> d) -> f
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
protocol f : f {
}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
}
}
protocol f {
i []
}
func f<g>() -> (g, g -> g) -> g
class A<T : A> n = {
return $u
}
l o: n = { (d: n, o: n -> n) -> n q
return o(d)
}
import Foundation
class m<j>: NSObject {
var h: j
g -> k = l $n
}
b f: _ = j() {
}
}
func k<g {
enum k {
func l
var _ = l
func o() as o).m.k()
func p(k: b) -> <i>(() -> i) -> b {
n { o f "\(k): \(o())" }
}
struct d<d : n, o:j n {
l p
}
protocol o : o {
}
func o<
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
class func f()
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
struct l<e : Sequence> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
struct c<e> {
let d: [( h
}
func b(g: f) -> <e>(()-> e) -> i
h
}
func e<l {
enum e {
func e
j {
class func n()
}
class l: j{ k() -> ())
}
({})
func j<o : Boolean>(l: o) {
}
j(j q Boolean)
func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(p: (Any, Any) -> Any) -> Any in
func n<n : l,) {
}
n(e())
e
func a<T>() {
enum b {
case c
}
}
o
class w<r>: c {
init(g: r) {
n.g = g
s.init()
(t: o
struct t : o {
p v = t
}
q t<where n.v == t<v : o u m : v {
}
struct h<t, j: v where t.h == j
f> {
c(d ())
}
func b(e)-> <d>(() -> d)
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
class A: A {
}
class B : C {
}
typealias C = B
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
class j {
func y((Any, j))(v: (Any, AnyObject)) {
y(v)
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
({})
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
u n
}
y q<x> {
s w(x, () -> ())
}
o n {
func j() p
}
class r {
func s() -> p {
t ""
}
}
class w: r, n {
k v: ))] = []
}
class n<x : n>
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protoc
protocol f : b { func b
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
import Foundation
class k<f>: NSObject {
d e: f
g(e: f) {
j h.g()
}
}
d
protocol i : d { func d
i
b
protocol d : b { func b
func d(e: = { (g: h, f: h -> h) -> h in
return f(g)
}
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
struct j<l : o> {
k b: l
}
func a<l>() -> [j<l>] {
return []
}
f
k)
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typealias l
typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
a=1 as a=1
enum S<T> {
case C(T, () -> ())
}
n)
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
o m = j
m()
class m {
func r((Any, m))(j: (Any, AnyObject)) {
r(j)
}
}
func m<o {
r m {
func n
n _ = n
}
}
class k<l : k
<c b:
func b<c {
enum b {
func b
var _ = b
func n<p>() -> (p, p -> p) -> p {
b, l]
g(o(q))
h e {
j class func r()
}
class k: h{ class func r {}
var k = 1
var s: r -> r t -> r) -> r m
u h>] {
u []
}
func r(e: () -> ()) {
}
class n {
var _ = r()
| 13.255102 | 79 | 0.411759 |
1662e82560ff710cef887562abd2730cb51cc28f
| 1,917 |
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
/// Encodable representation of a CLI command parameter.
/// Commands parameters (options, flags, arguments) are declared as properties on the command type
/// and annotated with `@propertyWrapper`s `@Option`, `@Flag` and `@Argument` provided by `ArgumentParser`.
/// `ArgumentParser` derives parameters names from property names (i.e., an`outputPath` option becomes `--output-path`)
/// making thus impossible to reliably generate a JSON representation of a command and its parameters.
/// Therefore we use the following enum to keep track of each parameter and their attributes (name, type and help text).
enum CLICommandParameter: Hashable {
case option(name: String, type: String, help: String)
case argument(name: String, type: String, help: String)
case flag(name: String, type: String, help: String)
var kind: String {
switch self {
case .option:
return "option"
case .argument:
return "argument"
case .flag:
return "flag"
}
}
}
// MARK: - CLICommandEncodableParameter + Encodable
extension CLICommandParameter: Encodable {
private enum CodingKeys: CodingKey {
case kind
case name
case type
case help
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .option(let name, let type, let help),
.argument(let name, let type, let help),
.flag(let name, let type, let help):
try container.encode(name, forKey: .name)
try container.encode(type, forKey: .type)
try container.encode(help, forKey: .help)
try container.encode(kind, forKey: .kind)
}
}
}
| 34.232143 | 120 | 0.651017 |
ac4377fd98658553843d6c6d34ee034e81172d76
| 402 |
//
// FeedImagePresenter.swift
// EssentialFeed
//
// Created by chihyin wang on 2020/9/10.
// Copyright © 2020 chihyinwang. All rights reserved.
//
import Foundation
public final class FeedImagePresenter {
public static func map(_ image: FeedImage) -> FeedImageViewModel {
FeedImageViewModel(
description: image.description,
location: image.location)
}
}
| 22.333333 | 70 | 0.681592 |
1e86b5edfc11dd7e9571b0a2ae6ce933bb774d2b
| 1,492 |
//
// NetworkInterface.swift
// WLAN
//
// Created by Alsey Coleman Miller on 7/5/18.
//
//
#if os(Linux)
import Glibc
#elseif canImport(Darwin)
import Darwin
#endif
import SystemPackage
/// UNIX Network Interface
internal struct NetworkInterface: Equatable, Hashable {
/// Interface name.
public let name: String
}
internal extension NetworkInterface {
static func interfaces() throws -> [NetworkInterface] {
var addressLinkedList: UnsafeMutablePointer<ifaddrs>? = nil
guard getifaddrs(&addressLinkedList) == 0
else { throw Errno(rawValue: errno) }
var interfaces = [NetworkInterface]()
var nextElement = addressLinkedList
while let interface = nextElement?.pointee {
nextElement = interface.ifa_next
guard interface.ifa_addr?.pointee.sa_family == sa_family_t(AF_PACKET)
else { continue }
let name = String(cString: interface.ifa_name)
interfaces.append(NetworkInterface(name: name))
}
return interfaces
}
/// Returns the index of the network interface corresponding to the name
static func index(for interface: NetworkInterface) throws -> UInt32 {
let index = if_nametoindex(interface.name)
guard index != 0 else { throw Errno(rawValue: errno) }
return index
}
}
#if !os(Linux)
var AF_PACKET: CInt { fatalError("AF_PACKET is Linux-only") }
#endif
| 26.175439 | 81 | 0.644772 |
4b36b6bbdd97fd58ea948f05d013596a0a7aa374
| 3,102 |
import Foundation
import CoreLocation
import SwiftHTTP
import SwiftyJSON
let SlackUrl: String = "https://slack.com/api"
class SlackAPI
{
private static func handleResponseError(res: Response) -> Bool
{
// print("API response code: \(res.statusCode)")
if res.statusCode == 403
{
MainStore.removeAccessToken()
}
if let err = res.error
{
print("API response error: \(err.code) \(err.localizedDescription) \(res.URL)")
return true
}
return res.statusCode != 200
}
static func postToAPI(accessToken: String!,endpoint:String!,extraParams:DictString, completion: ((Box<DictObject>) -> Void)? = nil )
{
print("\n *fetching from API")
do {
let url: String = "\(SlackUrl)/\(endpoint)"
var params: DictString = ["token": accessToken]
for (key,val) in extraParams {
params[key]=val
}
let opt = try HTTP.POST(url, parameters: params)
opt.start { response in
if !self.handleResponseError(response)
{
let data = JSON(data: response.data)
print(" response: \(data)")
completion?(Box.ok(data.object as! DictObject))
}
else
{
completion?(Box.error(response.statusCode))
}
}
} catch let error {
print("got an error creating the request: \(error)")
}
}
static func testAuthToken(accessToken: String!, completion: ((Box<DictObject>) -> Void)? = nil )
{
let endpoint: String = "/auth.test"
let extraParams: DictString = DictString()
postToAPI(accessToken,endpoint:endpoint,extraParams: extraParams,completion: completion)
}
static func fetchUserInfo(accessToken: String!, userId: String!,completion: ((Box<DictObject>) -> Void)? = nil )
{
let endpoint: String = "/users.info"
let extraParams: DictString = ["user":userId]
postToAPI(accessToken,endpoint:endpoint,extraParams: extraParams,completion: completion)
}
static func getUserInfo(token: String,completion: Box<DictObject> -> Void) -> Void {
testAuthToken(token) { (authBox: Box<DictObject>) in
authBox.map { (authInfo) in
if let userId = authInfo["user_id"] as? String {
fetchUserInfo(token,userId: userId,completion: completion)
}
}
}
}
static func mute(token:String) -> Void {
let endpoint: String = "/dnd.setSnooze"
postToAPI(token, endpoint: endpoint, extraParams: ["num_minutes":"10"])
}
static func unmute(token:String) -> Void {
let endpoint: String = "/dnd.endSnooze"
postToAPI(token, endpoint: endpoint, extraParams: DictString())
}
}
| 29.264151 | 136 | 0.541908 |
5d1e9c02a318adb6ea3f5c2ab2df1e6a77ac6be1
| 1,944 |
public struct Extractor {
@inlinable
public init(_ string: String) {
var contiguousString = string
contiguousString.makeContiguousUTF8()
self.string = contiguousString
self._currentIndex = string.startIndex
}
public let string: String
@usableFromInline
var _currentIndex: String.Index
@inlinable
public var currentIndex: String.Index {
_currentIndex
}
@inlinable
mutating public func matches(for matcher: Matcher) -> [Substring] {
var matches = [Substring]()
let endIndex = string.endIndex
while _currentIndex < string.endIndex {
if let nextIndex = matcher.advancedIndex(in: string, range: _currentIndex..<endIndex) {
matches.append(string[_currentIndex..<nextIndex])
_currentIndex = nextIndex
} else {
_currentIndex = string.index(after: _currentIndex)
}
}
return matches
}
@inlinable
public mutating func peekCurrent(with matcher: Matcher) -> Substring? {
guard _currentIndex < string.endIndex else {
return nil
}
let endIndex = string.endIndex
if let endIndex = matcher.advancedIndex(in: string, range: _currentIndex..<endIndex) {
return string[_currentIndex..<endIndex]
} else {
return nil
}
}
@discardableResult
@inlinable
public mutating func popCurrent(with matcher: Matcher) -> Substring? {
guard _currentIndex < string.endIndex else {
return nil
}
let endIndex = string.endIndex
if let endIndex = matcher.advancedIndex(in: string, range: _currentIndex..<endIndex) {
defer {
_currentIndex = endIndex
}
return string[_currentIndex..<endIndex]
} else {
return nil
}
}
}
| 30.857143 | 99 | 0.593107 |
21df820f4e78271c8fa016385d14996871e2d0fb
| 5,666 |
//
// ViewController.swift
// Recording Audio Files
//
// Created by Domenico on 23/05/15.
// License MIT
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate,
AVAudioRecorderDelegate{
var audioRecorder: AVAudioRecorder?
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
var error: NSError?
let session = AVAudioSession.sharedInstance()
if sprintntAndRecord, mode: AVAudioSessionCategoryOptions.DuckOthers, options: &error){
if session.setActive(true, error: nil){
println("Successfully activated the audio session")
session.requestRecordPermission{[weak self](allowed: Bool) in
if allowed{
self!.startRecordingAudio()
} else {
println("We don't have permission to record audio");
}
}
} else {
println("Could not activate the audio session")
}
}else{
if let theError = error{
println("An error occurred in setting the audio " +
"session category. Error = \(theError)")
}
}
}
//- MARK: AVAudioPlayerDelegate
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer!, successfully flag: Bool) {
if flag{
println("Successfully finished playing the file")
}else{
println("Failed to stop playing the file")
}
}
func audioPlayerBeginInterruption(_ player: AVAudioPlayer!) {
/* The audio session is deactivated here */
}
func audioPlayerEndInterruption(_ player: AVAudioPlayer!,
withOptions flags: Int) {
if flags == AVAudioSessionInterruptionFlags_ShouldResume{
player.play()
}
}
//- MARK: AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder!, successfully flag: Bool) {
if flag{
println("Successfully stopped the recording session")
/* Let's try to retrieve the data from the recorded file */
var playbackError: NSError?
var readingError: NSError?
let fileData = Data(bytesNoCopy: self.audioRecordingPath(), count: NSData.ReadingOptions.MappedRead, deallocator: &readingError)
self.audioPlayer = AVAudioPlayer(data: fileData, error: &playbackError)
if let player = self.audioPlayer{
// Set the delegate
player.delegate = self
if player.prepareToPlay() && player.play(){
println("Started playing the recorded audio")
}else{
println("Failed playing the recorded audio")
}
}else{
println("Failed to create the audio player")
}
}else{
println("Failed to stop the audio recording")
}
self.audioRecorder = nil
}
//- MARK: Helper methods
// Where the recording file will be saved
func audioRecordingPath() -> URL{
let fileManager = FileManager()
let documentFoldersUrl = fileManager.URLForDirectory(FileManager.SearchPathDirectory.DocumentDirectory, inDomain: FileManager.SearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false, error: nil)
return documentFoldersUrl!.URLByAppendingPathComponent("Recording.m4a")
}
// Audio Recorder settings
func audioRecordingSettings() -> NSDictionary{
/* Let's prepare the audio recorder options in the dictionary.
Later we will use this dictionary to instantiate an audio
recorder of type AVAudioRecorder */
return [
AVFormatIDKey : kAudioFormatMPEG4AAC as NSNumber,
AVSampleRateKey : 16000.0 as NSNumber,
AVNumberOfChannelsKey : 1 as NSNumber,
AVEncoderAudioQualityKey : AVAudioQuality.Low.rawValue as NSNumber
]
}
func startRecordingAudio(){
var error: NSError?
// File recording path
let audioRecordingURL = self.audioRecordingPath()
audioRecorder = AVAudioRecorder(
URL: audioRecordingURL,
settings: self.audioRecordingSettings() as! [AnyHashable: Any],
error: &error)
if let recorder = audioRecorder{
// Set the delegate
recorder.delegate = self
// Prepare to record
if recorder.prepareToRecord() && recorder.record(){
println("Successfully started to record")
// After 5 seconds, let's stop the recording process
let delay = 5.0
let delayInNanoSeconds = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(
deadline: delayInNanoSeconds, execute: {[weak self] in
self!.audioRecorder!.stop()
})
}else{
println("Failed to record...")
audioRecorder = nil
}
}else{
println("Error creating a new instance of the audio recorder")
}
}
}
| 34.760736 | 221 | 0.562125 |
6aa89aa49227e77e02b9294742c7493aba83ca6b
| 184 |
import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(MyLocalPackageTests.allTests),
]
}
#endif
| 18.4 | 51 | 0.608696 |
0ef1e339480706b4f22b6471364c51f93234a46b
| 777 |
import UIKit
import XCTest
import BXWebAppViewController
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.9 | 111 | 0.6139 |
8a84b7515d28bc0aaa5a654edd9187cc2138f500
| 1,854 |
//
// LayoutAnchorPairEquation.swift
// Layman
//
// Created by Brian Strobach on 1/10/19.
// Copyright © 2019 Brian Strobach. All rights reserved.
//
public final class LayoutAnchorPairEquation<F: AnchorVariable, S: AnchorVariable> {
public var variable: LayoutAnchorPair<F, S>
public var relation: LayoutRelation
public var relatedVariable: LayoutAnchorPair<F, S>?
public var coefficients: LayoutCoefficientPair
public init(_ variable: LayoutAnchorPair<F, S>,
_ relation: LayoutRelation,
_ relatedVariable: LayoutAnchorPair<F, S>?,
_ coefficients: LayoutCoefficientPair = .default) {
self.variable = variable
self.relation = relation
self.relatedVariable = relatedVariable
self.coefficients = coefficients
}
public convenience init(_ variable: LayoutAnchorPair<F, S>, _ relation: LayoutRelation, _ relativeConstant: RelativeLayoutConstant) {
self.init(variable, relation, .constant(relativeConstant))
}
public var solution: ConstraintPair {
let relationships = layoutRelationships
return ConstraintPair(relationships.0.constraint, relationships.1.constraint)
}
private var layoutRelationships: (LayoutAnchorEquation<F>, LayoutAnchorEquation<S>) {
return (LayoutAnchorEquation(variable.first, relation, relatedVariable?.first, coefficients.first),
LayoutAnchorEquation(variable.second, relation, relatedVariable?.second, coefficients.second))
}
}
extension LayoutAnchorPairEquation: LinearEquationProtocol, TupleVariableLinearEquation {
public static func inferred(variable: LayoutAnchorPair<F, S>, for view: View) -> LayoutAnchorPair<F, S> {
return view[keyPath: ...variable]
}
public typealias Expression = LayoutAnchorPairExpression<F, S>
}
| 37.836735 | 137 | 0.717907 |
22669f371340ab5f18f1dc8e3ea638e4d89963dc
| 28,766 |
//
// SwiftLinkPreview.swift
// SwiftLinkPreview
//
// Created by Leonardo Cardoso on 09/06/2016.
// Copyright © 2016 leocardz.com. All rights reserved.
//
import Foundation
public enum SwiftLinkResponseKey: String {
case url
case finalUrl
case canonicalUrl
case title
case description
case image
case images
case icon
case video
case price
}
open class Cancellable: NSObject {
public private(set) var isCancelled: Bool = false
open func cancel() {
isCancelled = true
}
}
open class SwiftLinkPreview: NSObject {
// MARK: - Vars
static let titleMinimumRelevant: Int = 15
static let decriptionMinimumRelevant: Int = 100
public var session: URLSession
public let workQueue: DispatchQueue
public let responseQueue: DispatchQueue
public let cache: Cache
public static let defaultWorkQueue = DispatchQueue.global(qos: .background)
// MARK: - Constructor
//Swift-only init with default parameters
@nonobjc public init(session: URLSession = URLSession.shared, workQueue: DispatchQueue = SwiftLinkPreview.defaultWorkQueue, responseQueue: DispatchQueue = DispatchQueue.main, cache: Cache = DisabledCache.instance) {
self.workQueue = workQueue
self.responseQueue = responseQueue
self.cache = cache
self.session = session
}
//Objective-C init with default parameters
@objc public override init() {
let _session = URLSession.shared
let _workQueue: DispatchQueue = SwiftLinkPreview.defaultWorkQueue
let _responseQueue: DispatchQueue = DispatchQueue.main
let _cache: Cache = DisabledCache.instance
self.workQueue = _workQueue
self.responseQueue = _responseQueue
self.cache = _cache
self.session = _session
}
//Objective-C init with paramaters. nil objects will default. Timeout values are ignored if InMemoryCache is disabled.
@objc public init(session: URLSession?, workQueue: DispatchQueue?, responseQueue: DispatchQueue?, disableInMemoryCache: Bool, cacheInvalidationTimeout: TimeInterval, cacheCleanupInterval: TimeInterval) {
let _session = session ?? URLSession.shared
let _workQueue = workQueue ?? SwiftLinkPreview.defaultWorkQueue
let _responseQueue = responseQueue ?? DispatchQueue.main
let _cache: Cache = disableInMemoryCache ? DisabledCache.instance : InMemoryCache(invalidationTimeout: cacheInvalidationTimeout, cleanupInterval: cacheCleanupInterval)
self.workQueue = _workQueue
self.responseQueue = _responseQueue
self.cache = _cache
self.session = _session
}
// MARK: - Functions
// Make preview
//Swift-only preview function using Swift specific closure types
@nonobjc @discardableResult open func preview(_ text: String, onSuccess: @escaping (Response) -> Void, onError: @escaping (PreviewError) -> Void) -> Cancellable {
let cancellable = Cancellable()
self.session = URLSession(configuration: self.session.configuration,
delegate: self, // To handle redirects
delegateQueue: self.session.delegateQueue)
let successResponseQueue = { [weak self] (response: Response) in
guard let self = self else { return }
if !cancellable.isCancelled {
self.responseQueue.async {
if !cancellable.isCancelled {
onSuccess(response)
}
}
}
}
let errorResponseQueue = { [weak self] (error: PreviewError) in
guard let self = self else { return }
if !cancellable.isCancelled {
self.responseQueue.async {
if !cancellable.isCancelled {
onError(error)
}
}
}
}
if let url = self.extractURL(text: text) {
workQueue.async { [weak self] in
guard let self = self else { return }
if cancellable.isCancelled {return}
if let result = self.cache.slp_getCachedResponse(url: url.absoluteString) {
successResponseQueue(result)
} else {
self.unshortenURL(url, cancellable: cancellable, completion: { [weak self] unshortened in
guard let self = self else { return }
if let result = self.cache.slp_getCachedResponse(url: unshortened.absoluteString) {
successResponseQueue(result)
} else {
var result = Response()
result.url = url
result.finalUrl = self.extractInURLRedirectionIfNeeded(unshortened)
result.canonicalUrl = self.extractCanonicalURL(unshortened)
self.extractInfo(response: result, cancellable: cancellable, completion: { [weak self] value in
guard let self = self else { return }
result.title = value.title
result.description = value.description
result.image = value.image
result.images = value.images
result.icon = value.icon
result.video = value.video
result.price = value.price
self.cache.slp_setCachedResponse(url: unshortened.absoluteString, response: result)
self.cache.slp_setCachedResponse(url: url.absoluteString, response: result)
successResponseQueue(result)
}, onError: errorResponseQueue)
}
}, onError: errorResponseQueue)
}
}
} else {
onError(.noURLHasBeenFound(text))
}
return cancellable
}
/*
Extract url redirection inside the GET query.
Like https://www.dji.com/404?url=http%3A%2F%2Fwww.dji.com%2Fmatrice600-pro%2Finfo#specs -> http://www.dji.com/de/matrice600-pro/info#specs
*/
private func extractInURLRedirectionIfNeeded(_ url: URL) -> URL {
var url = url
var absoluteString = url.absoluteString + "&id=12"
if let range = absoluteString.range(of: "url="),
let lastChar = absoluteString.last,
let lastCharIndex = absoluteString.range(of: String(lastChar), options: .backwards, range: nil, locale: nil) {
absoluteString = String(absoluteString[range.upperBound ..< lastCharIndex.upperBound])
if let range = absoluteString.range(of: "&"),
let firstChar = absoluteString.first,
let firstCharIndex = absoluteString.firstIndex(of: firstChar) {
absoluteString = String(absoluteString[firstCharIndex ..< absoluteString.index(before: range.upperBound)])
if let decoded = absoluteString.removingPercentEncoding, let newURL = URL(string: decoded) {
url = newURL
}
}
}
return url
}
}
// Extraction functions
extension SwiftLinkPreview {
// Extract first URL from text
open func extractURL(text: String) -> URL? {
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let range = NSRange(location: 0, length: text.utf16.count)
let matches = detector.matches(in: text, options: [], range: range)
return matches.compactMap { $0.url }.first
} catch {
return nil
}
}
// Unshorten URL by following redirections
fileprivate func unshortenURL(_ url: URL, cancellable: Cancellable, completion: @escaping (URL) -> Void, onError: @escaping (PreviewError) -> Void) {
if cancellable.isCancelled {return}
var task: URLSessionDataTask?
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
task = session.dataTask(with: request, completionHandler: { [weak self] data, response, error in
guard let self = self else { return }
guard !cancellable.isCancelled
else { return }
if error != nil {
self.workQueue.async {
if !cancellable.isCancelled {
onError(.cannotBeOpened("\(url.absoluteString): \(error.debugDescription)"))
}
}
task = nil
} else {
if let finalResult = response?.url {
if (finalResult.absoluteString == url.absoluteString) {
if response?.mimeType?.contains( "/html" ) ?? false {
var request = URLRequest( url: url )
request.addValue( "text/html,application/xhtml+xml,application/xml", forHTTPHeaderField: "Accept" )
self.session.dataTask( with: request, completionHandler: { [weak self] data, response, error in
guard let self = self else { return }
guard !cancellable.isCancelled
else { return }
if error != nil {
self.workQueue.async {
if !cancellable.isCancelled {
onError( .cannotBeOpened( "\(url.absoluteString): \(error.debugDescription)" ) )
}
}
return
}
if let response = response, let data = data {
let encoding = response.textEncodingName.flatMap {
String.Encoding( rawValue: CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding( $0 as CFString ) ) )
} ?? .utf8
if let html = String( data: data, encoding: encoding ) {
for meta in Regex.pregMatchAll( html, regex: Regex.metatagPattern, index: 1 ) {
if (meta.contains( "http-equiv=\"refresh\"" ) || meta.contains( "http-equiv='refresh'" )),
let value = Regex.pregMatchFirst( meta, regex: Regex.metatagContentPattern, index: 2 )?.decoded.extendedTrim,
let redirectString = value.split( separator: ";" )
.first( where: { $0.lowercased().starts( with: "url=" ) } )?
.split( separator: "=", maxSplits: 1 ).last,
let redirectURL = URL( string: self.addImagePrefixIfNeeded( String( redirectString ), url: url ) ) {
self.unshortenURL( redirectURL, cancellable: cancellable, completion: completion, onError: onError )
return
}
}
}
}
self.workQueue.async {
if !cancellable.isCancelled {
completion( url )
}
}
} ).resume()
}
else {
self.workQueue.async {
if !cancellable.isCancelled {
completion( url )
}
}
task = nil
}
} else {
task?.cancel()
task = nil
self.unshortenURL(finalResult, cancellable: cancellable, completion: completion, onError: onError)
}
} else {
self.workQueue.async {
if !cancellable.isCancelled {
completion(url)
}
}
task = nil
}
}
})
if let task = task {
task.resume()
} else {
self.workQueue.async {
if !cancellable.isCancelled {
onError(.cannotBeOpened(url.absoluteString))
}
}
}
}
// Extract HTML code and the information contained on it
fileprivate func extractInfo(response: Response, cancellable: Cancellable, completion: @escaping (Response) -> Void, onError: @escaping (PreviewError) -> Void) {
guard !cancellable.isCancelled, let url = response.finalUrl else { return }
func requestSync(sourceUrl: URL, request: URLRequest) -> (Bool, Data?, URLResponse?) {
let (data, urlResponse, error) = session.synchronousDataTask(with: request )
if let error = error {
if !cancellable.isCancelled {
let details = "\(sourceUrl.absoluteString): \(error.localizedDescription)"
onError( .cannotBeOpened( details ) )
return (false, data, urlResponse)
}
}
return (true, data, urlResponse)
}
if url.absoluteString.isImage() {
var result = response
result.title = ""
result.description = ""
result.images = [url.absoluteString]
result.image = url.absoluteString
completion(result)
} else {
guard let sourceUrl = url.scheme == "http" || url.scheme == "https" ? url: URL( string: "http://\(url)" )
else {
if !cancellable.isCancelled { onError(.invalidURL(url.absoluteString)) }
return
}
var request = URLRequest( url: sourceUrl )
request.addValue("text/html,application/xhtml+xml,application/xml", forHTTPHeaderField: "Accept")
request.addValue("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36", forHTTPHeaderField: "user-Agent")
let (data, urlResponse, error) = session.synchronousDataTask(with: request )
if let error = error {
if !cancellable.isCancelled {
let details = "\(sourceUrl.absoluteString): \(error.localizedDescription)"
onError( .cannotBeOpened( details ) )
return
}
}
if let data = data, let urlResponse = urlResponse, let encoding = urlResponse.textEncodingName,
let source = NSString( data: data, encoding:
CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding( encoding as CFString ) ) ) {
if !cancellable.isCancelled {
self.parseHtmlString(source as String, response: response, completion: completion)
}
} else {
do {
let data = try Data(contentsOf: sourceUrl)
var source: NSString? = nil
NSString.stringEncoding(for: data, encodingOptions: nil, convertedString: &source, usedLossyConversion: nil)
if let source = source {
if !cancellable.isCancelled {
self.parseHtmlString(source as String, response: response, completion: completion)
}
} else {
onError(.cannotBeOpened(sourceUrl.absoluteString))
}
} catch _ {
if !cancellable.isCancelled {
onError(.parseError(sourceUrl.absoluteString))
}
}
}
}
}
private func parseHtmlString(_ htmlString: String, response: Response, completion: @escaping (Response) -> Void) {
completion(self.performPageCrawling(self.cleanSource(htmlString), response: response))
}
// Removing unnecessary data from the source
private func cleanSource(_ source: String) -> String {
var source = source
source = source.deleteTagByPattern(Regex.inlineStylePattern)
source = source.deleteTagByPattern(Regex.inlineScriptPattern)
source = source.deleteTagByPattern(Regex.scriptPattern)
source = source.deleteTagByPattern(Regex.commentPattern)
return source
}
// Perform the page crawiling
private func performPageCrawling(_ htmlCode: String, response: Response) -> Response {
var result = self.crawIcon(htmlCode, result: response)
let sanitizedHtmlCode = htmlCode.deleteTagByPattern(Regex.linkPattern).extendedTrim
result = self.crawlMetaTags(sanitizedHtmlCode, result: result)
let otherResponse = self.crawlTitle(sanitizedHtmlCode, result: result)
return self.crawlImages(otherResponse.htmlCode, result: otherResponse.result)
}
// Extract canonical URL
internal func extractCanonicalURL(_ finalUrl: URL) -> String {
let preUrl: String = finalUrl.absoluteString
let url = preUrl
.replace("http://", with: "")
.replace("https://", with: "")
.replace("file://", with: "")
.replace("ftp://", with: "")
if preUrl != url {
if let canonicalUrl = Regex.pregMatchFirst(url, regex: Regex.cannonicalUrlPattern, index: 1) {
if !canonicalUrl.isEmpty {
return self.extractBaseUrl(canonicalUrl)
} else {
return self.extractBaseUrl(url)
}
} else {
return self.extractBaseUrl(url)
}
} else {
return self.extractBaseUrl(preUrl)
}
}
// Extract base URL
fileprivate func extractBaseUrl(_ url: String) -> String {
return String(url.split(separator: "/", maxSplits: 1, omittingEmptySubsequences: true)[0])
}
}
// Tag functions
extension SwiftLinkPreview {
// searc for favicn
internal func crawIcon(_ htmlCode: String, result: Response) -> Response {
var result = result
let metatags = Regex.pregMatchAll(htmlCode, regex: Regex.linkPattern, index: 1)
let filters = [ { (link: String) -> Bool in link.range(of: "apple-touch") != nil }, { (link: String) -> Bool in link.range(of: "shortcut") != nil }, { (link: String) -> Bool in link.range(of: "icon") != nil }
]
for filter in filters {
if let first = metatags.filter(filter).first {
let matches = Regex.pregMatchAll(first, regex: Regex.hrefPattern, index: 1)
if let val = matches.first {
result.icon = self.addImagePrefixIfNeeded(val.replace("\"", with: ""), result: result)
return result
}
}
}
return result
}
// Search for meta tags
internal func crawlMetaTags(_ htmlCode: String, result: Response) -> Response {
var result = result
let possibleTags: [String] = [
Response.Key.title.rawValue,
Response.Key.image.rawValue,
]
let metatags = Regex.pregMatchAll(htmlCode, regex: Regex.metatagPattern, index: 1)
for metatag in metatags {
for tag in possibleTags {
if (metatag.range(of: "property=\"og:\(tag)") != nil ||
metatag.range(of: "property='og:\(tag)") != nil ||
metatag.range(of: "name=\"twitter:\(tag)") != nil ||
metatag.range(of: "name='twitter:\(tag)") != nil ||
metatag.range(of: "name=\"\(tag)") != nil ||
metatag.range(of: "name='\(tag)") != nil ||
metatag.range(of: "itemprop=\"\(tag)") != nil ||
metatag.range(of: "itemprop='\(tag)") != nil) {
if let key = Response.Key(rawValue: tag),
result.value(for: key) == nil {
if let value = Regex.pregMatchFirst(metatag, regex: Regex.metatagContentPattern, index: 2) {
let value = value.decoded.extendedTrim
if tag == "image" {
let value = addImagePrefixIfNeeded(value, result: result)
if value.isOpenGraphImage(){ result.set(value, for: key) }
} else if tag == "video" {
let value = addImagePrefixIfNeeded(value, result: result)
if value.isVideo() { result.set(value, for: key) }
} else {
result.set(value, for: key)
}
}
}
}
}
}
return result
}
// Crawl for title if needed
internal func crawlTitle(_ htmlCode: String, result: Response) -> (htmlCode: String, result: Response) {
var result = result
let title = result.title
if title == nil || title?.isEmpty ?? true {
if let value = Regex.pregMatchFirst(htmlCode, regex: Regex.titlePattern, index: 2) {
if value.isEmpty {
let fromBody: String = self.crawlCode(htmlCode, minimum: SwiftLinkPreview.titleMinimumRelevant)
if !fromBody.isEmpty {
result.title = fromBody.decoded.extendedTrim
return (htmlCode.replace(fromBody, with: ""), result)
}
} else {
result.title = value.decoded.extendedTrim
}
}
}
return (htmlCode, result)
}
// Crawl for images
internal func crawlImages(_ htmlCode: String, result: Response) -> Response {
var result = result
let mainImage = result.image
if mainImage == nil || mainImage?.isEmpty == true {
let images = result.images
if images == nil || images?.isEmpty ?? true {
// Should look for <meta property="og:image" content=""/> first instead of <img/> tag.
let values = Regex.pregMatchAll(htmlCode, regex: Regex.secondaryImageTagPattern, index: 2)
if !values.isEmpty {
result.images = values
result.image = values.first(where: { $0.isImage() || $0.isOpenGraphImage() })
} else {
// If no OpenGraph image found pick any from <img/> tag to show.
let values = Regex.pregMatchAll(htmlCode, regex: Regex.imageTagPattern, index: 2)
if !values.isEmpty {
let imgs = values.map { self.addImagePrefixIfNeeded($0, result: result) }
result.images = imgs
result.image = imgs.first(where: { $0.isImage() || $0.isOpenGraphImage() })
}
}
}
} else {
let values = Regex.pregMatchAll(htmlCode, regex: Regex.secondaryImageTagPattern, index: 2)
if !values.isEmpty {
result.images = values
result.image = values.first(where: { $0.isImage() || $0.isOpenGraphImage() })
}
else{
result.images = [self.addImagePrefixIfNeeded(mainImage ?? String(), result: result)]
}
}
return result
}
// Add prefix image if needed
fileprivate func addImagePrefixIfNeeded(_ image: String, url: URL) -> String {
addImagePrefixIfNeeded( image, canonicalUrl: self.extractCanonicalURL( url ), finalUrl: self.extractInURLRedirectionIfNeeded( url ).absoluteString )
}
fileprivate func addImagePrefixIfNeeded(_ image: String, result: Response) -> String {
addImagePrefixIfNeeded( image, canonicalUrl: result.canonicalUrl, finalUrl: result.finalUrl?.absoluteString )
}
fileprivate func addImagePrefixIfNeeded(_ image: String, canonicalUrl: String?, finalUrl: String?) -> String {
var image = image
// TODO: account for HTML <base>
if let canonicalUrl = canonicalUrl, let finalUrl = finalUrl, let proto = finalUrl.split(separator: ":").first {
if image.hasPrefix("/") {
if image.hasPrefix("//") {
// image url is //domain/path
image = proto + ":" + image
} else {
// image url is /path relative to base url
image = proto + "://" + canonicalUrl + image
}
} else if !image.contains("://") {
// image is relative to request url
let requestUrl = removeSuffixIfNeeded(finalUrl)
if requestUrl.hasSuffix("/") {
image = requestUrl + image
} else {
image = (requestUrl as NSString).deletingLastPathComponent + "/" + image
}
}
}
return image
}
private func removeSuffixIfNeeded(_ image: String) -> String {
var image = image
if let index = image.firstIndex(of: "?") { image = String(image[..<index]) }
return image
}
// Crawl the entire code
internal func crawlCode(_ content: String, minimum: Int) -> String {
let resultFirstSearch = self.getTagContent("p", content: content, minimum: minimum)
if !resultFirstSearch.isEmpty {
return resultFirstSearch
} else {
let resultSecondSearch = self.getTagContent("div", content: content, minimum: minimum)
if !resultSecondSearch.isEmpty {
return resultSecondSearch
} else {
let resultThirdSearch = self.getTagContent("span", content: content, minimum: minimum)
if !resultThirdSearch.isEmpty {
return resultThirdSearch
} else {
if resultThirdSearch.count >= resultFirstSearch.count {
if resultThirdSearch.count >= resultThirdSearch.count {
return resultThirdSearch
} else {
return resultThirdSearch
}
} else {
return resultFirstSearch
}
}
}
}
}
// Get tag content
private func getTagContent(_ tag: String, content: String, minimum: Int) -> String {
let pattern = Regex.tagPattern(tag)
let index = 2
let rawMatches = Regex.pregMatchAll(content, regex: pattern, index: index)
let matches = rawMatches.filter({ $0.extendedTrim.tagsStripped.count >= minimum })
var result = matches.count > 0 ? matches[0] : ""
if result.isEmpty {
if let match = Regex.pregMatchFirst(content, regex: pattern, index: 2) {
result = match.extendedTrim.tagsStripped
}
}
return result
}
}
extension SwiftLinkPreview: URLSessionDataDelegate {
public func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
var request = request
request.httpMethod = "GET"
completionHandler(request)
}
}
| 39.031208 | 219 | 0.527533 |
7236d24f5f58f93456ea55c3c790754afc75a9b2
| 7,616 |
//
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
internal struct ConstraintAttributes: OptionSet {
internal init(rawValue: UInt) {
self.rawValue = rawValue
}
internal init(_ rawValue: UInt) {
self.init(rawValue: rawValue)
}
internal init(nilLiteral: ()) {
self.rawValue = 0
}
internal private(set) var rawValue: UInt
internal static var allZeros: ConstraintAttributes { return self.init(0) }
internal static func convertFromNilLiteral() -> ConstraintAttributes { return self.init(0) }
internal var boolValue: Bool { return self.rawValue != 0 }
internal func toRaw() -> UInt { return self.rawValue }
internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) }
internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) }
// normal
internal static var none: ConstraintAttributes { return self.init(0) }
internal static var left: ConstraintAttributes { return self.init(1) }
internal static var top: ConstraintAttributes { return self.init(2) }
internal static var right: ConstraintAttributes { return self.init(4) }
internal static var bottom: ConstraintAttributes { return self.init(8) }
internal static var leading: ConstraintAttributes { return self.init(16) }
internal static var trailing: ConstraintAttributes { return self.init(32) }
internal static var width: ConstraintAttributes { return self.init(64) }
internal static var height: ConstraintAttributes { return self.init(128) }
internal static var centerX: ConstraintAttributes { return self.init(256) }
internal static var centerY: ConstraintAttributes { return self.init(512) }
internal static var lastBaseline: ConstraintAttributes { return self.init(1024) }
@available(iOS 8.0, OSX 10.11, *)
internal static var firstBaseline: ConstraintAttributes { return self.init(2048) }
@available(iOS 8.0, *)
internal static var leftMargin: ConstraintAttributes { return self.init(4096) }
@available(iOS 8.0, *)
internal static var rightMargin: ConstraintAttributes { return self.init(8192) }
@available(iOS 8.0, *)
internal static var topMargin: ConstraintAttributes { return self.init(16384) }
@available(iOS 8.0, *)
internal static var bottomMargin: ConstraintAttributes { return self.init(32768) }
@available(iOS 8.0, *)
internal static var leadingMargin: ConstraintAttributes { return self.init(65536) }
@available(iOS 8.0, *)
internal static var trailingMargin: ConstraintAttributes { return self.init(131072) }
@available(iOS 8.0, *)
internal static var centerXWithinMargins: ConstraintAttributes { return self.init(262144) }
@available(iOS 8.0, *)
internal static var centerYWithinMargins: ConstraintAttributes { return self.init(524288) }
// aggregates
internal static var edges: ConstraintAttributes { return self.init(15) }
internal static var size: ConstraintAttributes { return self.init(192) }
internal static var center: ConstraintAttributes { return self.init(768) }
@available(iOS 8.0, *)
internal static var margins: ConstraintAttributes { return self.init(61440) }
@available(iOS 8.0, *)
internal static var centerWithinMargins: ConstraintAttributes { return self.init(786432) }
internal var layoutAttributes:[NSLayoutAttribute] {
var attrs = [NSLayoutAttribute]()
if (self.contains(ConstraintAttributes.left)) {
attrs.append(.left)
}
if (self.contains(ConstraintAttributes.top)) {
attrs.append(.top)
}
if (self.contains(ConstraintAttributes.right)) {
attrs.append(.right)
}
if (self.contains(ConstraintAttributes.bottom)) {
attrs.append(.bottom)
}
if (self.contains(ConstraintAttributes.leading)) {
attrs.append(.leading)
}
if (self.contains(ConstraintAttributes.trailing)) {
attrs.append(.trailing)
}
if (self.contains(ConstraintAttributes.width)) {
attrs.append(.width)
}
if (self.contains(ConstraintAttributes.height)) {
attrs.append(.height)
}
if (self.contains(ConstraintAttributes.centerX)) {
attrs.append(.centerX)
}
if (self.contains(ConstraintAttributes.centerY)) {
attrs.append(.centerY)
}
if (self.contains(ConstraintAttributes.lastBaseline)) {
attrs.append(.lastBaseline)
}
#if os(iOS) || os(tvOS)
if (self.contains(ConstraintAttributes.firstBaseline)) {
attrs.append(.firstBaseline)
}
if (self.contains(ConstraintAttributes.leftMargin)) {
attrs.append(.leftMargin)
}
if (self.contains(ConstraintAttributes.rightMargin)) {
attrs.append(.rightMargin)
}
if (self.contains(ConstraintAttributes.topMargin)) {
attrs.append(.topMargin)
}
if (self.contains(ConstraintAttributes.bottomMargin)) {
attrs.append(.bottomMargin)
}
if (self.contains(ConstraintAttributes.leadingMargin)) {
attrs.append(.leadingMargin)
}
if (self.contains(ConstraintAttributes.trailingMargin)) {
attrs.append(.trailingMargin)
}
if (self.contains(ConstraintAttributes.centerXWithinMargins)) {
attrs.append(.centerXWithinMargins)
}
if (self.contains(ConstraintAttributes.centerYWithinMargins)) {
attrs.append(.centerYWithinMargins)
}
#endif
return attrs
}
}
internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes {
return left.union(right)
}
internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) {
left.formUnion(right)
}
internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) {
left.subtract(right)
}
internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool {
return left.rawValue == right.rawValue
}
| 39.874346 | 99 | 0.665179 |
f84df9db2b3ac93b772c8a27eb5a6f736a813b6c
| 7,495 |
//
// 🦠 Corona-Warn-App
//
#if !RELEASE
import ExposureNotification
import UIKit
/// The root view controller of the developer menu.
final class DMViewController: UITableViewController, RequiresAppDependencies {
// MARK: Creating a developer menu view controller
init(
client: Client,
wifiClient: WifiOnlyHTTPClient,
exposureSubmissionService: ExposureSubmissionService,
otpService: OTPServiceProviding,
coronaTestService: CoronaTestService,
eventStore: EventStoringProviding,
qrCodePosterTemplateProvider: QRCodePosterTemplateProviding
) {
self.client = client
self.wifiClient = wifiClient
self.exposureSubmissionService = exposureSubmissionService
self.otpService = otpService
self.coronaTestService = coronaTestService
self.eventStore = eventStore
self.qrCodePosterTemplateProvider = qrCodePosterTemplateProvider
super.init(style: .plain)
title = "👩🏾💻 Developer Menu 🧑💻"
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Properties
private let client: Client
private let consumer = RiskConsumer()
private let exposureSubmissionService: ExposureSubmissionService
private let otpService: OTPServiceProviding
private let coronaTestService: CoronaTestService
private let eventStore: EventStoringProviding
private let qrCodePosterTemplateProvider: QRCodePosterTemplateProviding
private var keys = [SAP_External_Exposurenotification_TemporaryExposureKey]() {
didSet {
keys = self.keys.sorted()
}
}
// internal because of protocol RequiresAppDependencies
let wifiClient: WifiOnlyHTTPClient
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
consumer.didCalculateRisk = { _ in
// intentionally left blank
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setToolbarHidden(true, animated: animated)
}
// MARK: UITableView
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
DMMenuItem.allCases.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DMMenuCell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "DMMenuCell")
let menuItem = DMMenuItem.existingFromIndexPath(indexPath)
cell.textLabel?.text = menuItem.title
cell.detailTextLabel?.text = menuItem.subtitle
cell.accessoryType = .disclosureIndicator
return cell
}
// swiftlint:disable:next cyclomatic_complexity
override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
let menuItem = DMMenuItem.existingFromIndexPath(indexPath)
let vc: UIViewController?
switch menuItem {
case .keys:
vc = DMKeysViewController(
client: client,
store: store,
exposureManager: exposureManager
)
case .wifiClient:
vc = DMWifiClientViewController(wifiClient: wifiClient)
case .checkSubmittedKeys:
vc = DMSubmissionStateViewController(
client: client,
wifiClient: wifiClient,
delegate: self
)
case .appConfiguration:
vc = DMAppConfigurationViewController(appConfiguration: appConfigurationProvider)
case .backendConfiguration:
vc = DMBackendConfigurationViewController()
case .store:
vc = DMStoreViewController(store: store)
case .lastSubmissionRequest:
vc = DMLastSubmissionRequestViewController(lastSubmissionRequest: UserDefaults.standard.dmLastSubmissionRequest)
case .errorLog:
vc = DMLogsViewController()
case .sendFakeRequest:
vc = nil
sendFakeRequest()
case .manuallyRequestRisk:
vc = nil
manuallyRequestRisk()
case .debugRiskCalculation:
vc = DMDebugRiskCalculationViewController(store: store)
case .onboardingVersion:
vc = makeOnboardingVersionViewController()
case .serverEnvironment:
vc = makeServerEnvironmentViewController()
case .simulateNoDiskSpace:
vc = DMSQLiteErrorViewController(store: store)
case .listPendingNotifications:
vc = DMNotificationsViewController()
case .warnOthersNotifications:
vc = DMWarnOthersNotificationViewController(warnOthersReminder: WarnOthersReminder(store: store), store: store, coronaTestService: coronaTestService)
case .deviceTimeCheck:
vc = DMDeviceTimeCheckViewController(store: store)
case .ppacService:
vc = DMPPACViewController(store)
case .otpService:
vc = DMOTPServiceViewController(store: store, otpService: otpService)
case .ppaMostRecent:
vc = DMPPAnalyticsMostRecent(store: store, client: client, appConfig: appConfigurationProvider, coronaTestService: coronaTestService)
case .ppaActual:
vc = DMPPAnalyticsActualData(store: store, client: client, appConfig: appConfigurationProvider, coronaTestService: coronaTestService)
case .ppaSubmission:
vc = DMPPAnalyticsViewController(store: store, client: client, appConfig: appConfigurationProvider, coronaTestService: coronaTestService)
case .installationDate:
vc = DMInstallationDateViewController(store: store)
case .allTraceLocations:
vc = DMRecentCreatedEventViewController(store: store, eventStore: eventStore, qrCodePosterTemplateProvider: qrCodePosterTemplateProvider, isPosterGeneration: false)
case .mostRecentTraceLocationCheckedInto:
vc = DMDMMostRecentTraceLocationCheckedIntoViewController(store: store)
case .adHocPosterGeneration:
vc = DMRecentCreatedEventViewController(store: store, eventStore: eventStore, qrCodePosterTemplateProvider: qrCodePosterTemplateProvider, isPosterGeneration: true)
}
if let vc = vc {
navigationController?.pushViewController(
vc,
animated: true
)
}
}
// MARK: Performing developer menu related tasks
@objc
private func sendFakeRequest() {
FakeRequestService(client: client).fakeRequest {
let alert = self.setupErrorAlert(title: "Info", message: "Fake request was sent.")
self.present(alert, animated: true) {}
}
}
private func manuallyRequestRisk() {
let alert = UIAlertController(
title: "Manually request risk?",
message: "⚠️⚠️⚠️ WARNING ⚠️⚠️⚠️\n\nManually requesting the current risk works by purging the cache. This actually deletes the last calculated risk (among other things) from the store. Do you want to manually request your current risk?",
preferredStyle: .alert
)
alert.addAction(
UIAlertAction(
title: "Cancel",
style: .cancel
) { _ in
alert.dismiss(animated: true, completion: nil)
}
)
alert.addAction(
UIAlertAction(
title: "Purge Cache and request Risk",
style: .destructive
) { _ in
self.store.enfRiskCalculationResult = nil
self.store.checkinRiskCalculationResult = nil
self.riskProvider.requestRisk(userInitiated: true)
}
)
present(alert, animated: true, completion: nil)
}
private func makeOnboardingVersionViewController() -> DMDeltaOnboardingViewController {
return DMDeltaOnboardingViewController(store: store)
}
private func makeServerEnvironmentViewController() -> DMServerEnvironmentViewController {
return DMServerEnvironmentViewController(
store: store,
downloadedPackagesStore: downloadedPackagesStore
)
}
}
extension DMViewController: DMSubmissionStateViewControllerDelegate {
func submissionStateViewController(
_: DMSubmissionStateViewController,
getDiagnosisKeys completionHandler: @escaping ENGetDiagnosisKeysHandler
) {
exposureManager.getTestDiagnosisKeys(completionHandler: completionHandler)
}
}
#endif
| 33.163717 | 239 | 0.779053 |
560fd54465436f05654c3f6d9d55e5ad8d3de469
| 11,691 |
import XCTest
import Quick
import Nimble
import SMHTTPClient
import Swifter
@testable import UbiregiExtensionClient
class APIClientTests: QuickSpec {
var server: HttpServer?
override func spec() {
describe("#sendRequest") {
describe("result callback") {
it("invokes callback with UXCAPISuccessResult if API call succeeds") {
withSwifter { (server: HttpServer) in
waitUntil { done in
server["/test"] = { request in HttpResponse.OK(.Json([] as AnyObject)) }
let request = UXCAPIClient(hostname: "localhost", port: 8081, address: nil)
request.sendRequest("/test", query: [:], method: .GET, timeout: 3) { response in
expect(response is UXCAPISuccessResponse).to(beTrue())
done()
}
}
}
}
it("invokes callback with UXCAPIErrorResult if API call timeouts") {
withSwifter { (server: HttpServer) in
waitUntil(timeout: 5) { done in
server["/test"] = { request in
NSThread.sleepForTimeInterval(5)
return HttpResponse.OK(.Json([] as AnyObject))
}
let request = UXCAPIClient(hostname: "localhost", port: 8081, address: nil)
request.sendRequest("/test", query: [:], method: .GET, timeout: 2) { response in
let res = response as! UXCAPIErrorResponse
expect(res.error.code).to(equal(UXCErrorCode.Timeout.rawValue))
done()
}
}
}
}
it("invokes callback with UXCAPIErrorResult if API call failed by connection reset") {
withSwifter { (server: HttpServer) in
waitUntil { done in
server["/test"] = { request in
server.stop()
return HttpResponse.OK(.Json([] as AnyObject))
}
let request = UXCAPIClient(hostname: "localhost", port: 8081, address: nil)
request.sendRequest("/test", query: [:], method: .GET, timeout: 2) { response in
let res = response as! UXCAPIErrorResponse
expect(res.error.code).to(equal(UXCErrorCode.ConnectionFailure.rawValue))
done()
}
}
}
}
it("invokes callback with UXCAPIErrorResult if connection fails") {
waitUntil { done in
let request = UXCAPIClient(hostname: "localhost", port: 8081, address: nil)
request.sendRequest("/test", query: [:], method: .GET, timeout: 2) { response in
let res = response as! UXCAPIErrorResponse
expect(res.error.code).to(equal(UXCErrorCode.ConnectionFailure.rawValue))
done()
}
}
}
it("invokes callback with UXCAPIErrorResult if name resolution fails") {
waitUntil(timeout: 3) { done in
let request = UXCAPIClient(hostname: "no-such-host.local", port: 8081, address: nil)
request.sendRequest("/test", query: [:], method: .GET, timeout: 2) { response in
let res = response as! UXCAPIErrorResponse
expect(res.error.code).to(equal(UXCErrorCode.NameResolution.rawValue))
done()
}
}
}
}
describe("request header") {
it("sends Host header if host name resolved") {
withSwifter { server in
waitUntil { done in
server["/test"] = { (request: Swifter.HttpRequest) in
return HttpResponse.OK(.Json(request.headers))
}
let request = UXCAPIClient(hostname: "localhost", port: 8081, address: nil)
request.sendRequest("/test", query: [:], method: .GET, timeout: 2) { response in
let res = response as! UXCAPISuccessResponse
// Swifter downcase request header name
expect(res.JSONBody!["host"]).to(equal("localhost"))
done()
}
}
}
}
it("does not send Host header if host name failed to resolve and uses cached address") {
withSwifter { server in
waitUntil(timeout: 3) { done in
server["/test"] = { (request: Swifter.HttpRequest) in
return HttpResponse.OK(HttpResponseBody.Json(request.headers))
}
let resolver = NameResolver(hostname: "localhost", port: 8081)
resolver.run()
let address = resolver.IPv4Results.first!
let request = UXCAPIClient(hostname: "no-such-host.soutaro.com", port: 8081, address: address)
request.sendRequest("/test", query: [:], method: .GET, timeout: 2) { response in
let res = response as! UXCAPISuccessResponse
// Swifter downcase request header name
expect(res.JSONBody!["host"]).to(beNil())
done()
}
}
}
}
}
}
describe("#resolveAddress") {
context("name resolution succeeded") {
it("caches name resolution result if succeeds") {
let request = UXCAPIClient(hostname: "localhost", port: 80, address: nil)
waitUntil { done in
request.resolveAddress(1) { result in
switch result {
case .ResolvedToAddress(let addr, true):
expect(numericAddress(request.address!)).to(equal(numericAddress(addr)))
default:
XCTAssert(false)
}
done()
}
}
}
it("updates sockaddr cache if successfuly resolved") {
let resolver = NameResolver(hostname: "0.0.0.0", port: 80)
resolver.run()
let address = resolver.results.first!
let request = UXCAPIClient(hostname: "localhost", port: 80, address: address)
waitUntil { done in
request.resolveAddress(0.5) { result in
switch result {
case .ResolvedToAddress(let addr, true):
expect(numericAddress(request.address!)).notTo(equal(numericAddress(address)))
expect(numericAddress(request.address!)).to(equal(numericAddress(addr)))
default:
XCTAssert(false)
}
done()
}
}
}
}
context("name resolution timed out") {
it("uses cached sockaddr if name resolution timed out") {
let resolver = NameResolver(hostname: "localhost", port: 80)
resolver.run()
let address = resolver.IPv4Results.first!
let request = UXCAPIClient(hostname: "no-such-host.local", port: 80, address: address)
waitUntil { done in
// Resolving non existing .local host takes ~5secs to fail.
// The name resolution will result in timeout.
request.resolveAddress(0.5) { result in
switch result {
case .ResolvedToAddress(let addr, false):
expect(numericAddress(addr)).to(equal(numericAddress(address)))
default:
XCTAssert(false)
}
done()
}
}
}
}
context("name resolution failed") {
it("notifies error if no sockaddr is cached") {
let request = UXCAPIClient(hostname: "no-such-host", port: 80, address: nil)
waitUntil { done in
request.resolveAddress(0.5) { result in
switch result {
case .Error: fallthrough
case .NotFound:
expect(request.address).to(beNil())
default:
XCTAssert(false)
}
done()
}
}
}
it("uses cached sockaddr if present") {
let resolver = NameResolver(hostname: "localhost", port: 80)
resolver.run()
let address = resolver.IPv4Results.first!
let request = UXCAPIClient(hostname: "no-such-host", port: 80, address: address)
waitUntil { done in
request.resolveAddress(0.5) { result in
switch result {
case .ResolvedToAddress(let addr, false):
expect(numericAddress(addr)).to(equal(numericAddress(address)))
default:
XCTAssert(false)
}
done()
}
}
}
}
}
}
}
| 47.913934 | 122 | 0.39432 |
1e9c3e28935b8b031cf48393dafce7075d96db97
| 4,941 |
import UIKit
public protocol FooterViewDelegate: AnyObject {
func footerView(_ footerView: FooterView, didExpand expanded: Bool)
func footerView(_ footerView: FooterView, updateText text: String)
}
open class FooterView: UIView {
open fileprivate(set) lazy var infoLabel: InfoLabel = { [unowned self] in
let label = InfoLabel(text: "")
label.isHidden = !LightboxConfig.InfoLabel.enabled
label.textColor = LightboxConfig.InfoLabel.textColor
label.isUserInteractionEnabled = true
label.delegate = self
return label
}()
open fileprivate(set) lazy var infoField: InfoField = { [unowned self] in
let field = InfoField(text: "")
field.isHidden = !LightboxConfig.InfoLabel.enabled
field.textColor = LightboxConfig.InfoLabel.textColor
field.isUserInteractionEnabled = true
field.infoDelegate = self
return field
}()
open fileprivate(set) lazy var pageLabel: UILabel = { [unowned self] in
let label = UILabel(frame: CGRect.zero)
label.isHidden = !LightboxConfig.PageIndicator.enabled
label.numberOfLines = 1
return label
}()
open fileprivate(set) lazy var separatorView: UIView = { [unowned self] in
let view = UILabel(frame: CGRect.zero)
view.isHidden = !LightboxConfig.PageIndicator.enabled
view.backgroundColor = LightboxConfig.PageIndicator.separatorColor
return view
}()
let gradientColors = [UIColor(hex: "040404").withAlphaComponent(0.1), UIColor(hex: "040404")]
open weak var delegate: FooterViewDelegate?
// MARK: - Initializers
public init() {
super.init(frame: CGRect.zero)
_ = addGradientLayer(gradientColors)
if LightboxConfig.isEnableEditInfo {
[pageLabel, infoField, separatorView].forEach { addSubview($0) }
} else {
[pageLabel, infoLabel, separatorView].forEach { addSubview($0) }
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helpers
func expand(_ expand: Bool) {
expand ? infoLabel.expand() : infoLabel.collapse()
}
func updatePage(_ page: Int, _ numberOfPages: Int) {
let text = "\(page)/\(numberOfPages)"
pageLabel.attributedText = NSAttributedString(string: text,
attributes: LightboxConfig.PageIndicator.textAttributes)
pageLabel.sizeToFit()
}
func updateText(_ text: String) {
infoLabel.fullText = text
infoField.text = text
if infoField.superview == nil {
if text.isEmpty {
_ = removeGradientLayer()
} else if !infoLabel.expanded {
_ = addGradientLayer(gradientColors)
}
} else {
self.backgroundColor = UIColor.black.withAlphaComponent(0.6)
}
}
open override func layoutSubviews() {
super.layoutSubviews()
do {
let bottomPadding: CGFloat
if #available(iOS 11, *) {
bottomPadding = safeAreaInsets.bottom
} else {
bottomPadding = 0
}
pageLabel.frame.origin = CGPoint(
x: (frame.width - pageLabel.frame.width) / 2,
y: frame.height - pageLabel.frame.height - 2 - bottomPadding
)
}
separatorView.frame = CGRect(
x: 0,
y: pageLabel.frame.minY - 2.5,
width: frame.width,
height: 0.5
)
infoLabel.frame.origin.y = separatorView.frame.minY - infoLabel.frame.height - 15
infoField.frame.origin.y = separatorView.frame.minY - infoField.frame.height - 15
resizeGradientLayer()
}
}
// MARK: - LayoutConfigurable
extension FooterView: LayoutConfigurable {
@objc public func configureLayout() {
infoLabel.frame = CGRect(x: 17, y: 0, width: frame.width - 17 * 2, height: 35)
infoField.frame = CGRect(x: 17, y: 0, width: frame.width - 17 * 2, height: 35)
infoLabel.configureLayout()
infoField.configureLayout()
}
}
extension FooterView: InfoLabelDelegate {
public func infoLabel(_ infoLabel: InfoLabel, didExpand expanded: Bool) {
_ = (expanded || infoLabel.fullText.isEmpty) ? removeGradientLayer() : addGradientLayer(gradientColors)
delegate?.footerView(self, didExpand: expanded)
}
}
extension FooterView: InfoFieldDelegate {
public func infoFieldDidChange(_ infoField: InfoField) {
delegate?.footerView(self, updateText: infoField.text)
configureLayout()
}
}
| 31.471338 | 111 | 0.597045 |
89c39c7ae8d2709b9b750811d081519a36657df4
| 6,138 |
//
// NodeSelectorViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-08-03.
// Copyright © 2017 breadwallet LLC. All rights reserved.
//
import UIKit
import BRCore
class NodeSelectorViewController : UIViewController, Trackable {
let titleLabel = UILabel(font: .customBold(size: 26.0), color: .darkText)
private let nodeLabel = UILabel(font: .customBody(size: 14.0), color: .grayTextTint)
private let node = UILabel(font: .customBody(size: 14.0), color: .darkText)
private let statusLabel = UILabel(font: .customBody(size: 14.0), color: .grayTextTint)
private let status = UILabel(font: .customBody(size: 14.0), color: .darkText)
private let button: ShadowButton
private let walletManager: WalletManager
private var okAction: UIAlertAction?
private var timer: Timer?
init(walletManager: WalletManager) {
self.walletManager = walletManager
if UserDefaults.customNodeIP == nil {
button = ShadowButton(title: S.NodeSelector.manualButton, type: .primary)
} else {
button = ShadowButton(title: S.NodeSelector.automaticButton, type: .primary)
}
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
addSubviews()
addConstraints()
setInitialData()
}
private func addSubviews() {
view.addSubview(titleLabel)
view.addSubview(nodeLabel)
view.addSubview(node)
view.addSubview(statusLabel)
view.addSubview(status)
view.addSubview(button)
}
private func addConstraints() {
titleLabel.pinTopLeft(padding: C.padding[2])
nodeLabel.pinTopLeft(toView: titleLabel, topPadding: C.padding[2])
node.pinTopLeft(toView: nodeLabel, topPadding: 0)
statusLabel.pinTopLeft(toView: node, topPadding: C.padding[2])
status.pinTopLeft(toView: statusLabel, topPadding: 0)
button.constrain([
button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]),
button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]),
button.topAnchor.constraint(equalTo: status.bottomAnchor, constant: C.padding[2]),
button.heightAnchor.constraint(equalToConstant: 44.0) ])
}
private func setInitialData() {
view.backgroundColor = .whiteTint
titleLabel.text = S.NodeSelector.title
nodeLabel.text = S.NodeSelector.nodeLabel
statusLabel.text = S.NodeSelector.statusLabel
button.tap = strongify(self) { myself in
if UserDefaults.customNodeIP == nil {
myself.switchToManual()
} else {
myself.switchToAuto()
}
}
setStatusText()
timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(setStatusText), userInfo: nil, repeats: true)
}
@objc private func setStatusText() {
if let peerManager = walletManager.peerManager {
status.text = peerManager.isConnected ? S.NodeSelector.connected : S.NodeSelector.notConnected
}
node.text = walletManager.peerManager?.downloadPeerName
}
private func switchToAuto() {
guard UserDefaults.customNodeIP != nil else { return } //noop if custom node is already nil
saveEvent("nodeSelector.switchToAuto")
UserDefaults.customNodeIP = nil
UserDefaults.customNodePort = nil
button.title = S.NodeSelector.manualButton
DispatchQueue.walletQueue.async {
self.walletManager.peerManager?.setFixedPeer(address: 0, port: 0)
self.walletManager.peerManager?.connect()
}
}
private func switchToManual() {
let alert = UIAlertController(title: S.NodeSelector.enterTitle, message: S.NodeSelector.enterBody, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil))
let okAction = UIAlertAction(title: S.Button.ok, style: .default, handler: { action in
guard let ip = alert.textFields?.first, let port = alert.textFields?.last else { return }
if let addressText = ip.text {
self.saveEvent("nodeSelector.switchToManual")
var address = in_addr()
ascii2addr(AF_INET, addressText, &address)
UserDefaults.customNodeIP = Int(address.s_addr)
if let portText = port.text {
UserDefaults.customNodePort = Int(portText)
}
DispatchQueue.walletQueue.async {
self.walletManager.peerManager?.connect()
}
self.button.title = S.NodeSelector.automaticButton
}
})
self.okAction = okAction
self.okAction?.isEnabled = false
alert.addAction(okAction)
alert.addTextField { textField in
textField.placeholder = "192.168.0.1"
textField.keyboardType = .decimalPad
textField.addTarget(self, action: #selector(self.ipAddressDidChange(textField:)), for: .editingChanged)
}
alert.addTextField { textField in
textField.placeholder = "9526"
textField.keyboardType = .decimalPad
}
present(alert, animated: true, completion: nil)
}
private func setCustomNodeText() {
if var customNode = UserDefaults.customNodeIP {
if let buf = addr2ascii(AF_INET, &customNode, Int32(MemoryLayout<in_addr_t>.size), nil) {
node.text = String(cString: buf)
}
}
}
@objc private func ipAddressDidChange(textField: UITextField) {
if let text = textField.text {
if text.components(separatedBy: ".").count == 4 && ascii2addr(AF_INET, text, nil) > 0 {
self.okAction?.isEnabled = true
return
}
}
self.okAction?.isEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 40.117647 | 136 | 0.637015 |
235acd24aa2531283a1d4ebe84e1566ccfedcf27
| 1,417 |
//
// CompressionHelperTests.swift
// AirMessageTests
//
// Created by Cole Feuer on 2022-04-15.
//
import XCTest
@testable import AirMessage
class CompressionHelperTests: XCTestCase {
func testCompressDecompress() throws {
//Pseudorandom data
var rng = Xorshift128Plus()
var originalData = Data(repeating: 0, count: 1024 * 1024)
for i in originalData.indices {
originalData[i] = UInt8.random(in: UInt8.min...UInt8.max, using: &rng)
}
//Deflate and inflate the data
let deflatePipe = try CompressionPipeDeflate()
var compressedData = try deflatePipe.pipe(data: &originalData, isLast: true)
let inflatePipe = try CompressionPipeInflate()
let decompressedData = try inflatePipe.pipe(data: &compressedData)
//Make sure the data is the same
XCTAssertEqual(originalData, decompressedData, "Original data wasn't the same as decompressed data")
}
}
struct Xorshift128Plus: RandomNumberGenerator {
private var xS: UInt64
private var yS: UInt64
/// Two seeds, `x` and `y`, are required for the random number generator (default values are provided for both).
init(xSeed: UInt64 = 0, ySeed: UInt64 = UInt64.max) {
xS = xSeed == 0 && ySeed == 0 ? UInt64.max : xSeed // Seed cannot be all zeros.
yS = ySeed
}
mutating func next() -> UInt64 {
var x = xS
let y = yS
xS = y
x ^= x << 23 // a
yS = x ^ y ^ (x >> 17) ^ (y >> 26) // b, c
return yS &+ y
}
}
| 27.25 | 113 | 0.683839 |
3a2c6be6608603dea4587207a4fb2cb5fbceb398
| 3,765 |
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "AudioKit",
platforms: [
.macOS(.v10_14), .iOS(.v11), .tvOS(.v11)
],
products: [
.library(
name: "AudioKit",
type: .static,
targets: ["AudioKit"])
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
.target(name: "Stk",
exclude: ["LICENSE"],
resources: [.copy("rawwaves")],
publicHeadersPath: "include"),
.target(name: "soundpipe",
exclude: [
"README.md",
"lib/kissfft/COPYING",
"lib/kissfft/README",
"lib/inih/LICENSE.txt",
],
publicHeadersPath: "include",
cSettings: [
.headerSearchPath("lib/kissfft"),
.headerSearchPath("lib/inih"),
.headerSearchPath("Sources/soundpipe/lib/inih"),
.headerSearchPath("modules"),
.headerSearchPath("external")
]),
.target(
name: "sporth",
dependencies: ["soundpipe"],
exclude: ["README.md"],
publicHeadersPath: "include"),
.target(
name: "CAudioKit",
dependencies: ["Stk", "soundpipe", "sporth"],
exclude: [
"AudioKitCore/Modulated Delay/README.md",
"AudioKitCore/Sampler/Wavpack/license.txt",
"AudioKitCore/Common/README.md",
"Nodes/Effects/Distortion/DiodeClipper.soul",
"AudioKitCore/Common/Envelope.hpp",
"AudioKitCore/Sampler/README.md",
"AudioKitCore/README.md",
],
publicHeadersPath: "include",
cxxSettings: [
.headerSearchPath("CoreAudio"),
.headerSearchPath("AudioKitCore/Common"),
.headerSearchPath("Devoloop/include"),
.headerSearchPath("include"),
.headerSearchPath(".")
]
),
.target(
name: "AudioKit",
dependencies: ["CAudioKit"],
exclude: [
"Nodes/Generators/Physical Models/README.md",
"Internals/Table/README.md",
"Nodes/Playback/Samplers/Sampler/Sampler.md",
"Nodes/Playback/Samplers/Apple Sampler/AppleSamplerNotes.md",
"Nodes/Playback/Samplers/Samplers.md",
"Nodes/Playback/Samplers/Sampler/README.md",
"Nodes/Effects/Guitar Processors/README.md",
"Nodes/Playback/Samplers/PreparingSampleSets.md",
"Internals/README.md",
"Nodes/Effects/Modulation/ModDelay.svg",
"MIDI/README.md",
"Analysis/README.md",
"Nodes/Effects/Modulation/ModulatedDelayEffects.md",
"Nodes/Effects/Modulation/README.md",
"Nodes/Playback/Samplers/Apple Sampler/Skeleton.aupreset",
"Nodes/Effects/README.md",
"Operations/README.md",
"Nodes/README.md",
]),
.testTarget(
name: "AudioKitTests",
dependencies: ["AudioKit"],
resources: [.copy("TestResources/")]),
.testTarget(
name: "CAudioKitTests",
dependencies: ["CAudioKit"])
],
cxxLanguageStandard: .cxx14
)
| 37.65 | 96 | 0.505976 |
bf7ff3b13dbafe3c00dd01edac85ad4569952162
| 21,421 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct EdifactEnvelopeSettingsData : EdifactEnvelopeSettingsProtocol {
public var groupAssociationAssignedCode: String?
public var communicationAgreementId: String?
public var applyDelimiterStringAdvice: Bool
public var createGroupingSegments: Bool
public var enableDefaultGroupHeaders: Bool
public var recipientReferencePasswordValue: String?
public var recipientReferencePasswordQualifier: String?
public var applicationReferenceId: String?
public var processingPriorityCode: String?
public var interchangeControlNumberLowerBound: Int64
public var interchangeControlNumberUpperBound: Int64
public var rolloverInterchangeControlNumber: Bool
public var interchangeControlNumberPrefix: String?
public var interchangeControlNumberSuffix: String?
public var senderReverseRoutingAddress: String?
public var receiverReverseRoutingAddress: String?
public var functionalGroupId: String?
public var groupControllingAgencyCode: String?
public var groupMessageVersion: String?
public var groupMessageRelease: String?
public var groupControlNumberLowerBound: Int64
public var groupControlNumberUpperBound: Int64
public var rolloverGroupControlNumber: Bool
public var groupControlNumberPrefix: String?
public var groupControlNumberSuffix: String?
public var groupApplicationReceiverQualifier: String?
public var groupApplicationReceiverId: String?
public var groupApplicationSenderQualifier: String?
public var groupApplicationSenderId: String?
public var groupApplicationPassword: String?
public var overwriteExistingTransactionSetControlNumber: Bool
public var transactionSetControlNumberPrefix: String?
public var transactionSetControlNumberSuffix: String?
public var transactionSetControlNumberLowerBound: Int64
public var transactionSetControlNumberUpperBound: Int64
public var rolloverTransactionSetControlNumber: Bool
public var isTestInterchange: Bool
public var senderInternalIdentification: String?
public var senderInternalSubIdentification: String?
public var receiverInternalIdentification: String?
public var receiverInternalSubIdentification: String?
enum CodingKeys: String, CodingKey {case groupAssociationAssignedCode = "groupAssociationAssignedCode"
case communicationAgreementId = "communicationAgreementId"
case applyDelimiterStringAdvice = "applyDelimiterStringAdvice"
case createGroupingSegments = "createGroupingSegments"
case enableDefaultGroupHeaders = "enableDefaultGroupHeaders"
case recipientReferencePasswordValue = "recipientReferencePasswordValue"
case recipientReferencePasswordQualifier = "recipientReferencePasswordQualifier"
case applicationReferenceId = "applicationReferenceId"
case processingPriorityCode = "processingPriorityCode"
case interchangeControlNumberLowerBound = "interchangeControlNumberLowerBound"
case interchangeControlNumberUpperBound = "interchangeControlNumberUpperBound"
case rolloverInterchangeControlNumber = "rolloverInterchangeControlNumber"
case interchangeControlNumberPrefix = "interchangeControlNumberPrefix"
case interchangeControlNumberSuffix = "interchangeControlNumberSuffix"
case senderReverseRoutingAddress = "senderReverseRoutingAddress"
case receiverReverseRoutingAddress = "receiverReverseRoutingAddress"
case functionalGroupId = "functionalGroupId"
case groupControllingAgencyCode = "groupControllingAgencyCode"
case groupMessageVersion = "groupMessageVersion"
case groupMessageRelease = "groupMessageRelease"
case groupControlNumberLowerBound = "groupControlNumberLowerBound"
case groupControlNumberUpperBound = "groupControlNumberUpperBound"
case rolloverGroupControlNumber = "rolloverGroupControlNumber"
case groupControlNumberPrefix = "groupControlNumberPrefix"
case groupControlNumberSuffix = "groupControlNumberSuffix"
case groupApplicationReceiverQualifier = "groupApplicationReceiverQualifier"
case groupApplicationReceiverId = "groupApplicationReceiverId"
case groupApplicationSenderQualifier = "groupApplicationSenderQualifier"
case groupApplicationSenderId = "groupApplicationSenderId"
case groupApplicationPassword = "groupApplicationPassword"
case overwriteExistingTransactionSetControlNumber = "overwriteExistingTransactionSetControlNumber"
case transactionSetControlNumberPrefix = "transactionSetControlNumberPrefix"
case transactionSetControlNumberSuffix = "transactionSetControlNumberSuffix"
case transactionSetControlNumberLowerBound = "transactionSetControlNumberLowerBound"
case transactionSetControlNumberUpperBound = "transactionSetControlNumberUpperBound"
case rolloverTransactionSetControlNumber = "rolloverTransactionSetControlNumber"
case isTestInterchange = "isTestInterchange"
case senderInternalIdentification = "senderInternalIdentification"
case senderInternalSubIdentification = "senderInternalSubIdentification"
case receiverInternalIdentification = "receiverInternalIdentification"
case receiverInternalSubIdentification = "receiverInternalSubIdentification"
}
public init(applyDelimiterStringAdvice: Bool, createGroupingSegments: Bool, enableDefaultGroupHeaders: Bool, interchangeControlNumberLowerBound: Int64, interchangeControlNumberUpperBound: Int64, rolloverInterchangeControlNumber: Bool, groupControlNumberLowerBound: Int64, groupControlNumberUpperBound: Int64, rolloverGroupControlNumber: Bool, overwriteExistingTransactionSetControlNumber: Bool, transactionSetControlNumberLowerBound: Int64, transactionSetControlNumberUpperBound: Int64, rolloverTransactionSetControlNumber: Bool, isTestInterchange: Bool) {
self.applyDelimiterStringAdvice = applyDelimiterStringAdvice
self.createGroupingSegments = createGroupingSegments
self.enableDefaultGroupHeaders = enableDefaultGroupHeaders
self.interchangeControlNumberLowerBound = interchangeControlNumberLowerBound
self.interchangeControlNumberUpperBound = interchangeControlNumberUpperBound
self.rolloverInterchangeControlNumber = rolloverInterchangeControlNumber
self.groupControlNumberLowerBound = groupControlNumberLowerBound
self.groupControlNumberUpperBound = groupControlNumberUpperBound
self.rolloverGroupControlNumber = rolloverGroupControlNumber
self.overwriteExistingTransactionSetControlNumber = overwriteExistingTransactionSetControlNumber
self.transactionSetControlNumberLowerBound = transactionSetControlNumberLowerBound
self.transactionSetControlNumberUpperBound = transactionSetControlNumberUpperBound
self.rolloverTransactionSetControlNumber = rolloverTransactionSetControlNumber
self.isTestInterchange = isTestInterchange
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.groupAssociationAssignedCode) {
self.groupAssociationAssignedCode = try container.decode(String?.self, forKey: .groupAssociationAssignedCode)
}
if container.contains(.communicationAgreementId) {
self.communicationAgreementId = try container.decode(String?.self, forKey: .communicationAgreementId)
}
self.applyDelimiterStringAdvice = try container.decode(Bool.self, forKey: .applyDelimiterStringAdvice)
self.createGroupingSegments = try container.decode(Bool.self, forKey: .createGroupingSegments)
self.enableDefaultGroupHeaders = try container.decode(Bool.self, forKey: .enableDefaultGroupHeaders)
if container.contains(.recipientReferencePasswordValue) {
self.recipientReferencePasswordValue = try container.decode(String?.self, forKey: .recipientReferencePasswordValue)
}
if container.contains(.recipientReferencePasswordQualifier) {
self.recipientReferencePasswordQualifier = try container.decode(String?.self, forKey: .recipientReferencePasswordQualifier)
}
if container.contains(.applicationReferenceId) {
self.applicationReferenceId = try container.decode(String?.self, forKey: .applicationReferenceId)
}
if container.contains(.processingPriorityCode) {
self.processingPriorityCode = try container.decode(String?.self, forKey: .processingPriorityCode)
}
self.interchangeControlNumberLowerBound = try container.decode(Int64.self, forKey: .interchangeControlNumberLowerBound)
self.interchangeControlNumberUpperBound = try container.decode(Int64.self, forKey: .interchangeControlNumberUpperBound)
self.rolloverInterchangeControlNumber = try container.decode(Bool.self, forKey: .rolloverInterchangeControlNumber)
if container.contains(.interchangeControlNumberPrefix) {
self.interchangeControlNumberPrefix = try container.decode(String?.self, forKey: .interchangeControlNumberPrefix)
}
if container.contains(.interchangeControlNumberSuffix) {
self.interchangeControlNumberSuffix = try container.decode(String?.self, forKey: .interchangeControlNumberSuffix)
}
if container.contains(.senderReverseRoutingAddress) {
self.senderReverseRoutingAddress = try container.decode(String?.self, forKey: .senderReverseRoutingAddress)
}
if container.contains(.receiverReverseRoutingAddress) {
self.receiverReverseRoutingAddress = try container.decode(String?.self, forKey: .receiverReverseRoutingAddress)
}
if container.contains(.functionalGroupId) {
self.functionalGroupId = try container.decode(String?.self, forKey: .functionalGroupId)
}
if container.contains(.groupControllingAgencyCode) {
self.groupControllingAgencyCode = try container.decode(String?.self, forKey: .groupControllingAgencyCode)
}
if container.contains(.groupMessageVersion) {
self.groupMessageVersion = try container.decode(String?.self, forKey: .groupMessageVersion)
}
if container.contains(.groupMessageRelease) {
self.groupMessageRelease = try container.decode(String?.self, forKey: .groupMessageRelease)
}
self.groupControlNumberLowerBound = try container.decode(Int64.self, forKey: .groupControlNumberLowerBound)
self.groupControlNumberUpperBound = try container.decode(Int64.self, forKey: .groupControlNumberUpperBound)
self.rolloverGroupControlNumber = try container.decode(Bool.self, forKey: .rolloverGroupControlNumber)
if container.contains(.groupControlNumberPrefix) {
self.groupControlNumberPrefix = try container.decode(String?.self, forKey: .groupControlNumberPrefix)
}
if container.contains(.groupControlNumberSuffix) {
self.groupControlNumberSuffix = try container.decode(String?.self, forKey: .groupControlNumberSuffix)
}
if container.contains(.groupApplicationReceiverQualifier) {
self.groupApplicationReceiverQualifier = try container.decode(String?.self, forKey: .groupApplicationReceiverQualifier)
}
if container.contains(.groupApplicationReceiverId) {
self.groupApplicationReceiverId = try container.decode(String?.self, forKey: .groupApplicationReceiverId)
}
if container.contains(.groupApplicationSenderQualifier) {
self.groupApplicationSenderQualifier = try container.decode(String?.self, forKey: .groupApplicationSenderQualifier)
}
if container.contains(.groupApplicationSenderId) {
self.groupApplicationSenderId = try container.decode(String?.self, forKey: .groupApplicationSenderId)
}
if container.contains(.groupApplicationPassword) {
self.groupApplicationPassword = try container.decode(String?.self, forKey: .groupApplicationPassword)
}
self.overwriteExistingTransactionSetControlNumber = try container.decode(Bool.self, forKey: .overwriteExistingTransactionSetControlNumber)
if container.contains(.transactionSetControlNumberPrefix) {
self.transactionSetControlNumberPrefix = try container.decode(String?.self, forKey: .transactionSetControlNumberPrefix)
}
if container.contains(.transactionSetControlNumberSuffix) {
self.transactionSetControlNumberSuffix = try container.decode(String?.self, forKey: .transactionSetControlNumberSuffix)
}
self.transactionSetControlNumberLowerBound = try container.decode(Int64.self, forKey: .transactionSetControlNumberLowerBound)
self.transactionSetControlNumberUpperBound = try container.decode(Int64.self, forKey: .transactionSetControlNumberUpperBound)
self.rolloverTransactionSetControlNumber = try container.decode(Bool.self, forKey: .rolloverTransactionSetControlNumber)
self.isTestInterchange = try container.decode(Bool.self, forKey: .isTestInterchange)
if container.contains(.senderInternalIdentification) {
self.senderInternalIdentification = try container.decode(String?.self, forKey: .senderInternalIdentification)
}
if container.contains(.senderInternalSubIdentification) {
self.senderInternalSubIdentification = try container.decode(String?.self, forKey: .senderInternalSubIdentification)
}
if container.contains(.receiverInternalIdentification) {
self.receiverInternalIdentification = try container.decode(String?.self, forKey: .receiverInternalIdentification)
}
if container.contains(.receiverInternalSubIdentification) {
self.receiverInternalSubIdentification = try container.decode(String?.self, forKey: .receiverInternalSubIdentification)
}
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if self.groupAssociationAssignedCode != nil {try container.encode(self.groupAssociationAssignedCode, forKey: .groupAssociationAssignedCode)}
if self.communicationAgreementId != nil {try container.encode(self.communicationAgreementId, forKey: .communicationAgreementId)}
try container.encode(self.applyDelimiterStringAdvice, forKey: .applyDelimiterStringAdvice)
try container.encode(self.createGroupingSegments, forKey: .createGroupingSegments)
try container.encode(self.enableDefaultGroupHeaders, forKey: .enableDefaultGroupHeaders)
if self.recipientReferencePasswordValue != nil {try container.encode(self.recipientReferencePasswordValue, forKey: .recipientReferencePasswordValue)}
if self.recipientReferencePasswordQualifier != nil {try container.encode(self.recipientReferencePasswordQualifier, forKey: .recipientReferencePasswordQualifier)}
if self.applicationReferenceId != nil {try container.encode(self.applicationReferenceId, forKey: .applicationReferenceId)}
if self.processingPriorityCode != nil {try container.encode(self.processingPriorityCode, forKey: .processingPriorityCode)}
try container.encode(self.interchangeControlNumberLowerBound, forKey: .interchangeControlNumberLowerBound)
try container.encode(self.interchangeControlNumberUpperBound, forKey: .interchangeControlNumberUpperBound)
try container.encode(self.rolloverInterchangeControlNumber, forKey: .rolloverInterchangeControlNumber)
if self.interchangeControlNumberPrefix != nil {try container.encode(self.interchangeControlNumberPrefix, forKey: .interchangeControlNumberPrefix)}
if self.interchangeControlNumberSuffix != nil {try container.encode(self.interchangeControlNumberSuffix, forKey: .interchangeControlNumberSuffix)}
if self.senderReverseRoutingAddress != nil {try container.encode(self.senderReverseRoutingAddress, forKey: .senderReverseRoutingAddress)}
if self.receiverReverseRoutingAddress != nil {try container.encode(self.receiverReverseRoutingAddress, forKey: .receiverReverseRoutingAddress)}
if self.functionalGroupId != nil {try container.encode(self.functionalGroupId, forKey: .functionalGroupId)}
if self.groupControllingAgencyCode != nil {try container.encode(self.groupControllingAgencyCode, forKey: .groupControllingAgencyCode)}
if self.groupMessageVersion != nil {try container.encode(self.groupMessageVersion, forKey: .groupMessageVersion)}
if self.groupMessageRelease != nil {try container.encode(self.groupMessageRelease, forKey: .groupMessageRelease)}
try container.encode(self.groupControlNumberLowerBound, forKey: .groupControlNumberLowerBound)
try container.encode(self.groupControlNumberUpperBound, forKey: .groupControlNumberUpperBound)
try container.encode(self.rolloverGroupControlNumber, forKey: .rolloverGroupControlNumber)
if self.groupControlNumberPrefix != nil {try container.encode(self.groupControlNumberPrefix, forKey: .groupControlNumberPrefix)}
if self.groupControlNumberSuffix != nil {try container.encode(self.groupControlNumberSuffix, forKey: .groupControlNumberSuffix)}
if self.groupApplicationReceiverQualifier != nil {try container.encode(self.groupApplicationReceiverQualifier, forKey: .groupApplicationReceiverQualifier)}
if self.groupApplicationReceiverId != nil {try container.encode(self.groupApplicationReceiverId, forKey: .groupApplicationReceiverId)}
if self.groupApplicationSenderQualifier != nil {try container.encode(self.groupApplicationSenderQualifier, forKey: .groupApplicationSenderQualifier)}
if self.groupApplicationSenderId != nil {try container.encode(self.groupApplicationSenderId, forKey: .groupApplicationSenderId)}
if self.groupApplicationPassword != nil {try container.encode(self.groupApplicationPassword, forKey: .groupApplicationPassword)}
try container.encode(self.overwriteExistingTransactionSetControlNumber, forKey: .overwriteExistingTransactionSetControlNumber)
if self.transactionSetControlNumberPrefix != nil {try container.encode(self.transactionSetControlNumberPrefix, forKey: .transactionSetControlNumberPrefix)}
if self.transactionSetControlNumberSuffix != nil {try container.encode(self.transactionSetControlNumberSuffix, forKey: .transactionSetControlNumberSuffix)}
try container.encode(self.transactionSetControlNumberLowerBound, forKey: .transactionSetControlNumberLowerBound)
try container.encode(self.transactionSetControlNumberUpperBound, forKey: .transactionSetControlNumberUpperBound)
try container.encode(self.rolloverTransactionSetControlNumber, forKey: .rolloverTransactionSetControlNumber)
try container.encode(self.isTestInterchange, forKey: .isTestInterchange)
if self.senderInternalIdentification != nil {try container.encode(self.senderInternalIdentification, forKey: .senderInternalIdentification)}
if self.senderInternalSubIdentification != nil {try container.encode(self.senderInternalSubIdentification, forKey: .senderInternalSubIdentification)}
if self.receiverInternalIdentification != nil {try container.encode(self.receiverInternalIdentification, forKey: .receiverInternalIdentification)}
if self.receiverInternalSubIdentification != nil {try container.encode(self.receiverInternalSubIdentification, forKey: .receiverInternalSubIdentification)}
}
}
extension DataFactory {
public static func createEdifactEnvelopeSettingsProtocol(applyDelimiterStringAdvice: Bool, createGroupingSegments: Bool, enableDefaultGroupHeaders: Bool, interchangeControlNumberLowerBound: Int64, interchangeControlNumberUpperBound: Int64, rolloverInterchangeControlNumber: Bool, groupControlNumberLowerBound: Int64, groupControlNumberUpperBound: Int64, rolloverGroupControlNumber: Bool, overwriteExistingTransactionSetControlNumber: Bool, transactionSetControlNumberLowerBound: Int64, transactionSetControlNumberUpperBound: Int64, rolloverTransactionSetControlNumber: Bool, isTestInterchange: Bool) -> EdifactEnvelopeSettingsProtocol {
return EdifactEnvelopeSettingsData(applyDelimiterStringAdvice: applyDelimiterStringAdvice, createGroupingSegments: createGroupingSegments, enableDefaultGroupHeaders: enableDefaultGroupHeaders, interchangeControlNumberLowerBound: interchangeControlNumberLowerBound, interchangeControlNumberUpperBound: interchangeControlNumberUpperBound, rolloverInterchangeControlNumber: rolloverInterchangeControlNumber, groupControlNumberLowerBound: groupControlNumberLowerBound, groupControlNumberUpperBound: groupControlNumberUpperBound, rolloverGroupControlNumber: rolloverGroupControlNumber, overwriteExistingTransactionSetControlNumber: overwriteExistingTransactionSetControlNumber, transactionSetControlNumberLowerBound: transactionSetControlNumberLowerBound, transactionSetControlNumberUpperBound: transactionSetControlNumberUpperBound, rolloverTransactionSetControlNumber: rolloverTransactionSetControlNumber, isTestInterchange: isTestInterchange)
}
}
| 80.530075 | 945 | 0.808552 |
ac595d0b202072880b75a1e2a8df8077edab2ed5
| 592 |
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
final class CurrencyFormatter {
static var formatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.currencyCode = Config().currency.rawValue
formatter.numberStyle = .currency
return formatter
}
static var plainFormatter: EtherNumberFormatter {
let formatter = EtherNumberFormatter.full
formatter.groupingSeparator = ""
return formatter
}
}
| 28.190476 | 59 | 0.697635 |
fc9c3a80e1c0a4f50847e13b07f85416c83de6c7
| 2,279 |
//
// AppDelegate.swift
// IOS Helper
//
// Created by Andrew Apperley on 2016-11-22.
// Copyright © 2016 Humber College. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UINavigationController(rootViewController: MainViewController())
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47.479167 | 281 | 0.777973 |
fe7e5ca527f8ef67c9020920fa69e9654d81b372
| 506 |
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "network_ios",
products: [
.library(name: "network_ios", targets: ["network_ios"])
],
dependencies: [
],
targets: [
.binaryTarget(
name: "network_ios",
url: "https://github.com/holzschu/network_ios/releases/download/v0.2/network_ios.xcframework.zip",
checksum: "89a465b32e8aed3fcbab0691d8cb9abeecc54ec6f872181dad97bb105b72430a"
)
]
)
| 25.3 | 110 | 0.634387 |
62cdd8c0b4fb8f53e81920e931ebb50dad7a6c5d
| 1,998 |
//
// EncyclopediaViewModel.swift
// CleanMVVM
//
// Created by Tom on 2021/12/25.
//
import Foundation
import RxSwift
import RxCocoa
final class EncyclopediaViewModel: ViewModelType {
struct Dependency {
}
struct Input {
let getPokemonList: PublishSubject<Void>
let loadMore: PublishSubject<Void>
}
struct Output {
let pokemonList: BehaviorRelay<[ListedPokemon]>
}
private let disposeBag: DisposeBag = .init()
private let dependency: Dependency
private let provider: ServicesProviderType
private let coordinator: CoordinatorType
private let limit: Int = 20
private var isLoading: Bool = false
init(
dependency: Dependency,
provider: ServicesProviderType,
coordinator: CoordinatorType
) {
self.dependency = dependency
self.provider = provider
self.coordinator = coordinator
}
func transform(input: Input) -> Output {
let pokemonList: BehaviorRelay<[ListedPokemon]> = .init(value: [])
input.getPokemonList
.flatMap { [weak self] _ -> Observable<[ListedPokemon]> in
guard let self = self else { return .empty() }
return self.provider.pokemonService
.getPokemonList(
offset: 0,
limit: self.limit
)
.asObservable()
.map { $0.results }
}
.asDriver(onErrorDriveWith: .empty())
.drive(pokemonList)
.disposed(by: self.disposeBag)
input.loadMore
.flatMap { [weak self] _ -> Observable<[ListedPokemon]> in
guard let self = self else { return .empty() }
return self.provider.pokemonService
.getPokemonList(
offset: pokemonList.value.count,
limit: self.limit
)
.asObservable()
.map { pokemonList.value + $0.results }
}
.asDriver(onErrorDriveWith: .empty())
.drive(pokemonList)
.disposed(by: self.disposeBag)
return Output(pokemonList: pokemonList)
}
}
| 24.072289 | 70 | 0.631632 |
615b9b34ca27851575025c7a1441fe85768f7426
| 944 |
//
// OGSMoveTreeNode.swift
// Surround
//
// Created by Anh Khoa Hong on 29/05/2021.
//
import Foundation
struct OGSMoveTreeNode {
var branches: [OGSMoveTreeNode] = []
var move: Move?
var trunk = false
var position: BoardPosition?
}
extension OGSMoveTreeNode: Decodable {
enum CodingKeys: String, CodingKey {
case branches
case x
case y
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let row = try? container.decodeIfPresent(Int.self, forKey: .x),
let column = try? container.decodeIfPresent(Int.self, forKey: .y) {
if row == -1 {
move = .pass
} else {
move = .placeStone(row, column)
}
}
branches = try container.decodeIfPresent([OGSMoveTreeNode].self, forKey: .branches) ?? []
}
}
| 23.6 | 97 | 0.573093 |
89e80a76b5627e0a57a917bbe244a5fa3b40d00a
| 10,131 |
import WMF
public struct LibraryUsed {
let title:String
let licenseName:String
let licenseText:String
}
class LibrariesUsedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var libraries:[LibraryUsed] = []
@IBOutlet weak var tableView: UITableView!
@objc public static let storyboardName = "LibrariesUsed"
private static let cellReuseIdentifier = "org.wikimedia.libraries.used.cell"
private static let dataFileName = "LibrariesUsed.plist"
private static let plistLibrariesUsedKey = "LibrariesUsed"
private static let plistTitleKey = "Title"
private static let plistLicenseNameKey = "LicenseName"
private static let plistLicenseTextKey = "LicenseText"
fileprivate var theme = Theme.standard
@objc func closeButtonPushed(_ : UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:)))
navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
}
lazy private var tableHeaderView: UIView = {
let headerFrame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 56)
let headerView = UIView.init(frame: headerFrame)
let labelFrame = headerView.frame.insetBy(dx: 10, dy: 10)
let label = UILabel.init(frame: labelFrame)
label.adjustsFontForContentSizeCategory = true
label.font = UIFont.preferredFont(forTextStyle: .footnote)
label.textColor = self.theme.colors.primaryText
label.textAlignment = .center
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.text = String.localizedStringWithFormat(WMFLocalizedString("about-libraries-licenses-title", value:"We love open source software %1$@", comment:"Title for list of library licenses. %1$@ will be replaced with an emoji expressing our love for open source software"), "💖")
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
headerView.addSubview(label)
return headerView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.apply(theme: self.theme)
view.backgroundColor = .base50
tableView.register(UITableViewCell.self, forCellReuseIdentifier: LibrariesUsedViewController.cellReuseIdentifier)
tableView.estimatedRowHeight = 41
tableView.rowHeight = UITableView.automaticDimension
tableView.tableHeaderView = tableHeaderView
tableView.semanticContentAttribute = .forceLeftToRight
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target:nil, action:nil)
title = WMFLocalizedString("about-libraries", value:"Libraries used", comment:"Header text for libraries section (as in a collection of subprograms used to develop software) of the about page. Is not capitalised for aesthetic reasons, but could be capitalised in translations.")
let fileName = LibrariesUsedViewController.dataFileName
guard
let plistPath = Bundle.main.path(forResource: fileName.wmf_substring(before: "."), ofType: fileName.wmf_substring(after: "."))
else {
assertionFailure("Could find '\(fileName)' resource.")
return
}
libraries = librariesUsed(from: plistPath)
}
private func librariesUsed(from plistPath: String) -> [LibraryUsed] {
guard
let dict = NSDictionary(contentsOfFile: plistPath) as? [String: Any],
let librariesUsedDataArray = dict[LibrariesUsedViewController.plistLibrariesUsedKey] as? Array<Dictionary<String, Any>>
else {
assertionFailure("\n\nUnexpected items found in '\(plistPath)' or its '\(LibrariesUsedViewController.plistLibrariesUsedKey)' array.\n\n")
return []
}
return librariesUsedDataArray
.compactMap {library -> LibraryUsed? in
guard
let title = library[LibrariesUsedViewController.plistTitleKey] as? String,
let licenseName = library[LibrariesUsedViewController.plistLicenseNameKey] as? String,
let licenseText = library[LibrariesUsedViewController.plistLicenseTextKey] as? String
else {
assertionFailure("\n\nOne of the following required keys not found in '\(LibrariesUsedViewController.plistLibrariesUsedKey)' array in '\(LibrariesUsedViewController.dataFileName)': '\(LibrariesUsedViewController.plistTitleKey)', '\(LibrariesUsedViewController.plistLicenseNameKey)', '\(LibrariesUsedViewController.plistLicenseTextKey)'\n\n")
return nil
}
return LibraryUsed.init(title: title.wmf_stringByCapitalizingFirstCharacter(usingWikipediaLanguageCode: "en"), licenseName: licenseName, licenseText: licenseText)
}
.sorted(by: {
$0.title < $1.title
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return libraries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: LibrariesUsedViewController.cellReuseIdentifier, for: indexPath)
cell.contentView.semanticContentAttribute = .forceLeftToRight
cell.textLabel?.semanticContentAttribute = .forceLeftToRight
cell.textLabel?.textAlignment = .left
cell.backgroundColor = theme.colors.paperBackground;
cell.textLabel?.textColor = theme.colors.primaryText;
cell.selectionStyle = .default
cell.selectedBackgroundView = UIView()
cell.selectedBackgroundView?.backgroundColor = theme.colors.midBackground
let library:LibraryUsed = self.libraries[indexPath.row];
cell.textLabel?.text = library.title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let libraryVC = LibraryUsedViewController.wmf_viewControllerFromStoryboardNamed(LibrariesUsedViewController.storyboardName)
libraryVC.apply(theme: self.theme)
let library = self.libraries[indexPath.row];
libraryVC.library = library
libraryVC.title = library.title
navigationController?.pushViewController(libraryVC, animated: true)
}
}
class LibraryUsedViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
public var library: LibraryUsed?
fileprivate var theme = Theme.standard
override func viewDidLoad() {
super.viewDidLoad()
self.apply(theme: self.theme)
textView.adjustsFontForContentSizeCategory = true
textView.textContainerInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
guard let licenseText = library?.licenseText else { return }
textView.text = normalizeWhitespaceForBetterReadability(from: licenseText)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
textView.setContentOffset(.zero, animated: false)
}
private var newlineOptionalWhitespaceNewlineRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "\\R\\s*\\R", options: [])
} catch {
assertionFailure("regex failed to compile")
}
return nil
}()
private var oneOrMoreWhitespaceCharactersRegex: NSRegularExpression? = {
do {
return try NSRegularExpression(pattern: "\\s+", options: [])
} catch {
assertionFailure("regex failed to compile")
}
return nil
}()
// Minimal cleanups on license text.
// - consecutive line breaks reduce to 2 line breaks
// - non-consecutive line breaks converted to spaces (similar to HTML)
// Imperfect but *vast* improvement in readability especially with line wrapping.
private func normalizeWhitespaceForBetterReadability(from licenseString: String) -> String {
guard
let multiNewlineRegex = newlineOptionalWhitespaceNewlineRegex,
let whitespaceRegex = oneOrMoreWhitespaceCharactersRegex
else {
assertionFailure("regex(s) failed to compile")
return licenseString
}
var string = licenseString
let placeholder = "#temporary_placeholder#"
string = multiNewlineRegex.stringByReplacingMatches(in: string, options: [], range: string.fullRange, withTemplate: placeholder)
string = string.components(separatedBy: .newlines).joined(separator: " ")
string = whitespaceRegex.stringByReplacingMatches(in: string, options: [], range: string.fullRange, withTemplate: " ")
string = string.replacingOccurrences(of: placeholder, with: "\n\n")
return string
}
}
extension LibrariesUsedViewController: Themeable {
public func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
tableView.backgroundColor = theme.colors.baseBackground
tableView.separatorColor = theme.colors.chromeBackground
tableView.reloadData()
}
}
extension LibraryUsedViewController: Themeable {
public func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
self.view.backgroundColor = theme.colors.baseBackground
self.textView.backgroundColor = theme.colors.baseBackground
self.textView.textColor = theme.colors.primaryText
}
}
| 45.026667 | 361 | 0.683842 |
cc477ebd13269a3d110b0351b1a406919b613642
| 2,166 |
//
// AppDelegate.swift
// pokemongo
//
// Created by 張凱翔 on 2017/11/17.
// Copyright © 2017年 Kai.Siang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.085106 | 285 | 0.754848 |
893b5a4b3e8009467a03776aabba5f25da60dd03
| 5,105 |
// Copyright 2016 LinkedIn Corp.
// 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.
import XCTest
import LayoutKit // intentionally not @testable
class ReloadableViewTests: XCTestCase {
// MARK: collection view
func testCanOverrideCollectionViewRegisterViews() {
let registerViewsCollectionView = RegisterViewsCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
registerViewsCollectionView.registerViewsExpectation = expectation(description: "registerViews")
// upcast to UICollectionView to make sure that overloading works correctly
let collectionView: UICollectionView = registerViewsCollectionView
collectionView.registerViews(withReuseIdentifier: "reuseIdentifier")
waitForExpectations(timeout: 10.0, handler: nil)
}
func testCanOverride_CollectionView_PerformBatchUpdates() {
let registerViewsCollectionView = RegisterViewsCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
registerViewsCollectionView.reloadDataSynchronouslyExpectation = expectation(description: "reloadDataSynchronously")
// upcast to UICollectionView to make sure that overloading works correctly
let collectionView: UICollectionView = registerViewsCollectionView
collectionView.reloadDataSynchronously()
waitForExpectations(timeout: 10.0, handler: nil)
}
func testCanOverride_CollectionView_ReloadDataSynchronouslyExpectation() {
let registerViewsCollectionView = RegisterViewsCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
registerViewsCollectionView.performExpectation = expectation(description: "perform")
// upcast to UICollectionView to make sure that overloading works correctly
let collectionView: UICollectionView = registerViewsCollectionView
collectionView.perform(batchUpdates: BatchUpdates(), completion: nil)
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: table view
func testCanOverrideTableViewRegisterViews() {
let registerViewsTableView = RegisterViewsTableView(frame: .zero)
registerViewsTableView.registerViewsExpectation = expectation(description: "registerViews")
// upcast to UITableView to make sure that overloading works correctly
let tableView: UITableView = registerViewsTableView
tableView.registerViews(withReuseIdentifier: "reuseIdentifier")
waitForExpectations(timeout: 10.0, handler: nil)
}
func testCanOverride_PerformBatchUpdates() {
let registerViewsTableView = RegisterViewsTableView(frame: .zero)
registerViewsTableView.reloadDataSynchronouslyExpectation = expectation(description: "reloadDataSynchronously")
// upcast to UITableView to make sure that overloading works correctly
let tableView: UITableView = registerViewsTableView
tableView.reloadDataSynchronously()
waitForExpectations(timeout: 10.0, handler: nil)
}
func testCanOverride_ReloadDataSynchronouslyExpectation() {
let registerViewsTableView = RegisterViewsTableView(frame: .zero)
registerViewsTableView.performExpectation = expectation(description: "perform")
// upcast to UITableView to make sure that overloading works correctly
let tableView: UITableView = registerViewsTableView
tableView.perform(batchUpdates: BatchUpdates(), completion: nil)
waitForExpectations(timeout: 10.0, handler: nil)
}
}
class RegisterViewsCollectionView: UICollectionView {
var registerViewsExpectation: XCTestExpectation?
override func registerViews(withReuseIdentifier reuseIdentifier: String) {
registerViewsExpectation?.fulfill()
}
var reloadDataSynchronouslyExpectation: XCTestExpectation?
override func reloadDataSynchronously() {
reloadDataSynchronouslyExpectation?.fulfill()
}
var performExpectation: XCTestExpectation?
override func perform(batchUpdates: BatchUpdates, completion: (() -> Void)?) {
performExpectation?.fulfill()
}
}
class RegisterViewsTableView: UITableView {
var registerViewsExpectation: XCTestExpectation?
override func registerViews(withReuseIdentifier reuseIdentifier: String) {
registerViewsExpectation?.fulfill()
}
var reloadDataSynchronouslyExpectation: XCTestExpectation?
override func reloadDataSynchronously() {
reloadDataSynchronouslyExpectation?.fulfill()
}
var performExpectation: XCTestExpectation?
override func perform(batchUpdates: BatchUpdates, completion: (() -> Void)?) {
performExpectation?.fulfill()
}
}
| 40.19685 | 135 | 0.758472 |
22daa01ad8f42c7960b720a0c6b3af8b01732696
| 2,030 |
//
// CreateCoachingAppointmentRequest.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Create coaching appointment request */
public class CreateCoachingAppointmentRequest: Codable {
/** The name of coaching appointment. */
public var name: String?
/** The description of coaching appointment. */
public var _description: String?
/** The date/time the coaching appointment starts. Times will be rounded down to the minute. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z */
public var dateStart: Date?
/** The duration of coaching appointment in minutes. */
public var lengthInMinutes: Int?
/** The facilitator ID of coaching appointment. */
public var facilitatorId: String?
/** IDs of attendees in the coaching appointment. */
public var attendeeIds: [String]?
/** IDs of conversations associated with this coaching appointment. */
public var conversationIds: [String]?
/** IDs of documents associated with this coaching appointment. */
public var documentIds: [String]?
public init(name: String?, _description: String?, dateStart: Date?, lengthInMinutes: Int?, facilitatorId: String?, attendeeIds: [String]?, conversationIds: [String]?, documentIds: [String]?) {
self.name = name
self._description = _description
self.dateStart = dateStart
self.lengthInMinutes = lengthInMinutes
self.facilitatorId = facilitatorId
self.attendeeIds = attendeeIds
self.conversationIds = conversationIds
self.documentIds = documentIds
}
public enum CodingKeys: String, CodingKey {
case name
case _description = "description"
case dateStart
case lengthInMinutes
case facilitatorId
case attendeeIds
case conversationIds
case documentIds
}
}
| 30.757576 | 196 | 0.665025 |
eb534fcb348d1372ce3532fe9229fe66a6277f5e
| 699 |
//
// AnalyticEvent.swift
// sdkApiVideo
//
// Created by romain PETIT on 13/01/2020.
// Copyright © 2020 Romain. All rights reserved.
//
import Foundation
public struct AnalyticEvent: Codable{
public var type: String
public var emitted_at: String
public var at: Int
public var from: Int
public var to: Int
init(type: String, emitted_at: String, at: Int, from: Int, to: Int) {
self.type = type
self.emitted_at = emitted_at
self.at = at
self.from = from
self.to = to
}
enum CodingKeys : String, CodingKey {
case type
case emitted_at
case at
case from
case to
}
}
| 19.971429 | 73 | 0.590844 |
890b72de67aabb82fd868f4f9ed6e7a043a7ffd5
| 949 |
//
// Color.swift
// Color guess
//
// Created by Alessio De Gaetano on 21/02/2020.
// Copyright © 2020 Alessio De Gaetano. All rights reserved.
//
import Foundation
class RandomColor {
private var rRandom: Double = 0
private var gRandom: Double = 0
private var bRandom: Double = 0
init() {
self.rRandom = Double.random(in: 0..<1)
self.gRandom = Double.random(in: 0..<1)
self.bRandom = Double.random(in: 0..<1)
}
func newRandomColors() {
self.rRandom = Double.random(in: 0..<1)
self.gRandom = Double.random(in: 0..<1)
self.bRandom = Double.random(in: 0..<1)
print(rRandom, gRandom, bRandom)
}
func getrRandom() -> Double {
return self.rRandom
}
func getgRandom() -> Double {
return self.gRandom
}
func getbRandom() -> Double {
return self.bRandom
}
}
| 19.770833 | 61 | 0.555321 |
1abc5009cc7ed510043fbfd0264bffb1c1435d9d
| 27,576 |
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// UNSUPPORTED: OS=watchos
import Network
import Foundation
import StdlibUnittest
defer { runAllTests() }
var NetworkAPI = TestSuite("NetworkAPI")
#if !os(watchOS)
if #available(macOS 10.14, iOS 12.0, tvOS 12.0, *) {
NetworkAPI.test("constants") {
expectNotNil(NWConnection.ContentContext.defaultMessage)
expectNotNil(NWConnection.ContentContext.finalMessage)
expectNotNil(NWConnection.ContentContext.defaultStream)
expectNotNil(NWParameters.tcp)
expectNotNil(NWParameters.tls)
expectNotNil(NWParameters.udp)
expectNotNil(NWParameters.dtls)
expectNotNil(IPv4Address.any)
expectNotNil(IPv4Address.broadcast)
expectNotNil(IPv4Address.loopback)
expectNotNil(IPv4Address.allHostsGroup)
expectNotNil(IPv4Address.allRoutersGroup)
expectNotNil(IPv4Address.allReportsGroup)
expectNotNil(IPv4Address.mdnsGroup)
expectNotNil(IPv6Address.any)
expectNotNil(IPv6Address.loopback)
expectNotNil(IPv6Address.nodeLocalNodes)
expectNotNil(IPv6Address.linkLocalNodes)
expectNotNil(IPv6Address.linkLocalRouters)
expectNotNil(NWEndpoint.Port.any)
expectNotNil(NWEndpoint.Port.ssh)
expectNotNil(NWEndpoint.Port.smtp)
expectNotNil(NWEndpoint.Port.http)
expectNotNil(NWEndpoint.Port.pop)
expectNotNil(NWEndpoint.Port.imap)
expectNotNil(NWEndpoint.Port.https)
expectNotNil(NWEndpoint.Port.imaps)
expectNotNil(NWEndpoint.Port.socks)
}
NetworkAPI.test("NWEndpoint") {
let hostEndpoint = NWEndpoint.hostPort(host: "www.apple.com", port: .http)
expectNotNil(hostEndpoint)
expectNil(hostEndpoint.interface)
let bonjourEndpoint = NWEndpoint.service(name: "myprinter", type: "_ipp._tcp", domain: "local", interface: nil)
expectNotNil(bonjourEndpoint)
expectNil(bonjourEndpoint.interface)
let unixEndpoint = NWEndpoint.unix(path: "/foo/bar")
expectNotNil(unixEndpoint)
expectNil(unixEndpoint.interface)
}
NetworkAPI.test("NWEndpoint.Host") {
var host = NWEndpoint.Host("www.apple.com")
expectNotNil(host)
expectNil(host.interface)
host = NWEndpoint.Host("127.0.0.1")
expectNotNil(host)
expectNil(host.interface)
host = NWEndpoint.Host("::1")
expectNotNil(host)
expectNil(host.interface)
host = NWEndpoint.Host("::1%lo0")
expectNotNil(host)
expectNotNil(host.interface)
if let interface = host.interface {
expectEqual(interface.name, "lo0")
expectEqual(interface.type, .loopback)
}
var ipv4Address = IPv4Address("127.0.0.1")
expectNotNil(ipv4Address)
expectNotNil(ipv4Address!.rawValue)
expectEqual(ipv4Address!.rawValue.count, 4)
expectNil(ipv4Address!.interface)
expectTrue(ipv4Address!.isLoopback)
let otherIPv4Address = IPv4Address("127.0.0.1")
expectEqual(ipv4Address, otherIPv4Address)
ipv4Address = IPv4Address("169.254.1.0")
expectNotNil(ipv4Address)
expectTrue(ipv4Address!.isLinkLocal)
ipv4Address = IPv4Address("224.0.0.1")
expectNotNil(ipv4Address)
expectTrue(ipv4Address!.isMulticast)
var ipv6Address = IPv6Address("::0")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isAny)
expectNotNil(ipv6Address!.rawValue)
expectEqual(ipv6Address!.rawValue.count, 16)
expectNil(ipv6Address!.interface)
ipv6Address = IPv6Address("::1")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isLoopback)
expectNil(ipv6Address!.interface)
ipv6Address = IPv6Address("::1%lo0")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isLoopback)
expectNotNil(ipv6Address!.interface)
if let interface = ipv6Address!.interface {
expectEqual(interface.name, "lo0")
expectEqual(interface.type, .loopback)
}
ipv6Address = IPv6Address("::1.2.3.4")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isIPv4Compatabile)
ipv6Address = IPv6Address("::ffff:1.2.3.4")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isIPv4Mapped)
ipv4Address = ipv6Address!.asIPv4
expectNotNil(ipv4Address)
ipv6Address = IPv6Address("2002::1")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.is6to4)
ipv6Address = IPv6Address("fe80::1")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isLinkLocal)
ipv6Address = IPv6Address("ff02::1")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isMulticast)
expectEqual(ipv6Address!.multicastScope, .linkLocal)
// Try a bad multicast scope
ipv6Address = IPv6Address("ff03::1")
expectNotNil(ipv6Address)
expectTrue(ipv6Address!.isMulticast)
expectTrue(ipv6Address!.multicastScope != .linkLocal)
}
NetworkAPI.test("NWEndpoint.Port") {
let port: NWEndpoint.Port = 1234
expectNotNil(port)
expectEqual(port.rawValue, 1234)
expectEqual(NWEndpoint.Port.https, 443)
expectEqual(NWEndpoint.Port("https")!.rawValue, 443)
}
NetworkAPI.test("NWParameters") {
var parameters = NWParameters.tcp
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.internetProtocol is NWProtocolIP.Options)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0)
parameters = parameters.copy()
expectTrue(parameters.defaultProtocolStack.internetProtocol is NWProtocolIP.Options)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0)
parameters = NWParameters.udp
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0)
parameters = NWParameters.tls
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1)
expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options)
parameters.defaultProtocolStack.transportProtocol = NWProtocolUDP.Options()
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options)
parameters = NWParameters.tls
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
parameters = NWParameters.dtls
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1)
expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options)
parameters = NWParameters(tls:nil, tcp:NWProtocolTCP.Options())
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0)
parameters = NWParameters(dtls:nil, udp:NWProtocolUDP.Options())
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0)
parameters = NWParameters(tls:NWProtocolTLS.Options(), tcp:NWProtocolTCP.Options())
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1)
expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options)
parameters = NWParameters(dtls:NWProtocolTLS.Options(), udp:NWProtocolUDP.Options())
expectNotNil(parameters)
expectTrue(parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 1)
expectTrue(parameters.defaultProtocolStack.applicationProtocols[0] is NWProtocolTLS.Options)
parameters = NWParameters()
expectNotNil(parameters)
expectNotNil(parameters.defaultProtocolStack)
expectTrue(parameters.defaultProtocolStack.applicationProtocols.count == 0)
expectNil(parameters.defaultProtocolStack.transportProtocol)
parameters.defaultProtocolStack.transportProtocol = NWProtocolTCP.Options()
expectNil(parameters.requiredInterface)
expectEqual(parameters.requiredInterfaceType, NWInterface.InterfaceType.other)
parameters.requiredInterfaceType = .wifi
expectEqual(parameters.requiredInterfaceType, NWInterface.InterfaceType.wifi)
expectTrue(parameters.prohibitedInterfaces == nil ||
parameters.prohibitedInterfaces!.count == 0)
expectTrue(parameters.prohibitedInterfaceTypes == nil ||
parameters.prohibitedInterfaceTypes!.count == 0)
parameters.prohibitedInterfaceTypes = [ .cellular ]
expectTrue(parameters.prohibitedInterfaceTypes!.count == 1)
expectEqual(parameters.prohibitedInterfaceTypes![0], .cellular)
expectEqual(parameters.prohibitExpensivePaths, false)
parameters.prohibitExpensivePaths = true;
expectEqual(parameters.prohibitExpensivePaths, true)
expectEqual(parameters.preferNoProxies, false)
parameters.preferNoProxies = true;
expectEqual(parameters.preferNoProxies, true)
expectNil(parameters.requiredLocalEndpoint)
parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: 1234)
expectNotNil(parameters.requiredLocalEndpoint)
expectEqual(parameters.allowLocalEndpointReuse, false)
parameters.allowLocalEndpointReuse = true;
expectEqual(parameters.allowLocalEndpointReuse, true)
expectEqual(parameters.acceptLocalOnly, false)
parameters.acceptLocalOnly = true;
expectEqual(parameters.acceptLocalOnly, true)
expectEqual(parameters.serviceClass, NWParameters.ServiceClass.bestEffort)
parameters.serviceClass = .background;
expectEqual(parameters.serviceClass, NWParameters.ServiceClass.background)
expectEqual(parameters.multipathServiceType, NWParameters.MultipathServiceType.disabled)
parameters.multipathServiceType = .handover;
expectEqual(parameters.multipathServiceType, NWParameters.MultipathServiceType.handover)
expectEqual(parameters.expiredDNSBehavior, NWParameters.ExpiredDNSBehavior.systemDefault)
parameters.expiredDNSBehavior = .allow;
expectEqual(parameters.expiredDNSBehavior, NWParameters.ExpiredDNSBehavior.allow)
expectEqual(parameters.allowFastOpen, false)
parameters.allowFastOpen = true;
expectEqual(parameters.allowFastOpen, true)
}
NetworkAPI.test("NWProtocolTCP") {
expectNotNil(NWProtocolTCP.definition)
expectEqual(NWProtocolTCP.definition.name, "tcp")
let options = NWProtocolTCP.Options()
expectNotNil(options)
expectEqual(options.noDelay, false)
options.noDelay = true;
expectEqual(options.noDelay, true)
expectEqual(options.noPush, false)
options.noPush = true;
expectEqual(options.noDelay, true)
expectEqual(options.noOptions, false)
options.noOptions = true;
expectEqual(options.noOptions, true)
expectEqual(options.enableKeepalive, false)
options.enableKeepalive = true;
expectEqual(options.enableKeepalive, true)
expectEqual(options.keepaliveCount, 0)
options.keepaliveCount = 5;
expectEqual(options.keepaliveCount, 5)
expectEqual(options.keepaliveIdle, 0)
options.keepaliveIdle = 5;
expectEqual(options.keepaliveIdle, 5)
expectEqual(options.keepaliveInterval, 0)
options.keepaliveInterval = 5;
expectEqual(options.keepaliveInterval, 5)
expectEqual(options.maximumSegmentSize, 0)
options.maximumSegmentSize = 500;
expectEqual(options.maximumSegmentSize, 500)
expectEqual(options.connectionTimeout, 0)
options.connectionTimeout = 60;
expectEqual(options.connectionTimeout, 60)
expectEqual(options.persistTimeout, 0)
options.persistTimeout = 60;
expectEqual(options.persistTimeout, 60)
expectEqual(options.connectionDropTime, 0)
options.connectionDropTime = 60;
expectEqual(options.connectionDropTime, 60)
expectEqual(options.retransmitFinDrop, false)
options.retransmitFinDrop = true;
expectEqual(options.retransmitFinDrop, true)
expectEqual(options.disableAckStretching, false)
options.disableAckStretching = true;
expectEqual(options.disableAckStretching, true)
expectEqual(options.enableFastOpen, false)
options.enableFastOpen = true;
expectEqual(options.enableFastOpen, true)
expectEqual(options.disableECN, false)
options.disableECN = true;
expectEqual(options.disableECN, true)
}
NetworkAPI.test("NWProtocolUDP") {
expectNotNil(NWProtocolUDP.definition)
expectEqual(NWProtocolUDP.definition.name, "udp")
let options = NWProtocolUDP.Options()
expectNotNil(options)
expectEqual(options.preferNoChecksum, false)
options.preferNoChecksum = true;
expectEqual(options.preferNoChecksum, true)
}
NetworkAPI.test("NWProtocolIP") {
expectNotNil(NWProtocolIP.definition)
expectEqual(NWProtocolIP.definition.name, "ip")
let parameters = NWParameters()
let options = parameters.defaultProtocolStack.internetProtocol
expectNotNil(options)
expectTrue(options is NWProtocolIP.Options)
let ipOptions = options as! NWProtocolIP.Options
expectEqual(ipOptions.version, .any)
ipOptions.version = .v6;
expectEqual(ipOptions.version, .v6)
expectEqual(ipOptions.hopLimit, 0)
ipOptions.hopLimit = 5;
expectEqual(ipOptions.hopLimit, 5)
expectEqual(ipOptions.useMinimumMTU, false)
ipOptions.useMinimumMTU = true;
expectEqual(ipOptions.useMinimumMTU, true)
expectEqual(ipOptions.disableFragmentation, false)
ipOptions.disableFragmentation = true;
expectEqual(ipOptions.disableFragmentation, true)
let metadata = NWProtocolIP.Metadata()
expectNotNil(metadata)
expectEqual(metadata.ecn, .nonECT)
metadata.ecn = .ect0;
expectEqual(metadata.ecn, .ect0)
expectEqual(metadata.serviceClass, .bestEffort)
metadata.serviceClass = .background;
expectEqual(metadata.serviceClass, .background)
}
NetworkAPI.test("NWProtocolTLS") {
expectNotNil(NWProtocolTLS.definition)
expectEqual(NWProtocolTLS.definition.name, "tls")
let options = NWProtocolTLS.Options()
expectNotNil(options)
expectNotNil(options.securityProtocolOptions)
}
NetworkAPI.test("NWPath")
.skip(.iOSSimulatorAny("Path not fully supported on simulator"))
.skip(.tvOSSimulatorAny("Path not fully supported on simulator"))
.code {
let testQueue = DispatchQueue(label: "testQueue")
let group = DispatchGroup()
let monitor = NWPathMonitor()
expectNotNil(monitor)
monitor.pathUpdateHandler = { (newPath) in
expectNotNil(newPath)
group.leave()
}
group.enter();
monitor.start(queue: testQueue)
let path = monitor.currentPath
expectNotNil(path)
let result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
expectEqual(monitor.queue, testQueue)
expectNil(path.localEndpoint)
expectNil(path.remoteEndpoint)
for interface in path.availableInterfaces {
expectNotNil(interface.name)
expectTrue(interface.index != 0)
}
monitor.cancel()
let wifiMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
expectNotNil(wifiMonitor)
wifiMonitor.start(queue: testQueue)
let wifiPath = wifiMonitor.currentPath
expectNotNil(wifiPath)
if wifiPath.status == .satisfied {
expectTrue(wifiPath.usesInterfaceType(.wifi))
expectTrue(wifiPath.supportsIPv4 || wifiPath.supportsIPv6 || wifiPath.supportsDNS)
expectTrue(wifiPath.availableInterfaces.count > 0)
var someInterfaceWiFi = false
for interface in wifiPath.availableInterfaces {
if (interface.type == .wifi) {
someInterfaceWiFi = true
break
}
}
expectTrue(someInterfaceWiFi)
}
wifiMonitor.cancel()
let loopbackMonitor = NWPathMonitor(requiredInterfaceType: .loopback)
expectNotNil(loopbackMonitor)
loopbackMonitor.start(queue: testQueue)
let loopbackPath = loopbackMonitor.currentPath
expectNotNil(loopbackPath)
expectTrue(!loopbackPath.isExpensive)
loopbackMonitor.cancel()
}
NetworkAPI.test("NWListener failure")
.skip(.iOSSimulatorAny("Path not fully supported on simulator"))
.skip(.tvOSSimulatorAny("Path not fully supported on simulator"))
.code {
let parameters: NWParameters = .tcp
parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: 1234)
var listener: NWListener? = nil
do {
listener = try NWListener(using: parameters, on: 2345)
} catch {
print("Received listener error: \(error).")
}
expectNil(listener)
}
NetworkAPI.test("NWListener")
.skip(.iOSSimulatorAny("Path not fully supported on simulator"))
.skip(.tvOSSimulatorAny("Path not fully supported on simulator"))
.code {
let testQueue = DispatchQueue(label: "testQueue")
let group = DispatchGroup()
let advertiseGroup = DispatchGroup()
let listener = try! NWListener(using: .tcp, on: 1234)
expectNotNil(listener)
listener.service = NWListener.Service(type: "_ipp._tcp")
listener.stateUpdateHandler = { (newState) in
switch(newState) {
case .ready:
group.leave()
case .failed(let error):
expectNotNil(error)
listener.cancel()
case .cancelled:
group.leave()
default:
break
}
}
listener.newConnectionHandler = { (newConn) in
expectNotNil(newConn)
newConn.forceCancel()
}
listener.serviceRegistrationUpdateHandler = { (serviceChange) in
switch(serviceChange) {
case .add(let endpoint):
expectNotNil(endpoint)
case .remove(let endpoint):
expectNotNil(endpoint)
}
advertiseGroup.leave()
}
group.enter()
advertiseGroup.enter()
listener.start(queue: testQueue)
// Wait for ready
var result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
// Wait for advertise
result = advertiseGroup.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
expectEqual(listener.queue, testQueue)
expectTrue(listener.parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
expectEqual(listener.port, 1234)
group.enter()
listener.cancel()
// Wait for cancelled
result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
}
NetworkAPI.test("NWConnection creation") {
var connection = NWConnection(host: "localhost", port: 2345, using:.tcp)
expectNotNil(connection)
connection = NWConnection(to: .hostPort(host: "localhost", port: 2345), using:.tcp)
expectNotNil(connection)
connection = NWConnection(to: .service(name: "myprinter", type: "_ipp._tcp", domain: "local", interface: nil), using:.tcp)
expectNotNil(connection)
connection = NWConnection(to: .unix(path: "/foo/bar"), using:.tcp)
expectNotNil(connection)
}
NetworkAPI.test("NWConnection Waiting Reset")
.skip(.iOSSimulatorAny("Path not fully supported on simulator"))
.skip(.tvOSSimulatorAny("Path not fully supported on simulator"))
.code {
let testQueue = DispatchQueue(label: "testQueue")
let group = DispatchGroup()
let connection = NWConnection(host: "localhost", port: 3456, using:.tls)
expectNotNil(connection)
connection.stateUpdateHandler = { (newState) in
switch(newState) {
case .waiting(let error):
expectNotNil(error)
switch(error) {
case .posix(let code):
expectEqual(code, .ECONNREFUSED)
default:
break
}
group.leave()
case .failed(let error):
expectNotNil(error)
connection.cancel()
case .cancelled:
group.leave()
default:
break
}
}
group.enter()
connection.start(queue: testQueue)
// Wait for waiting
var result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
connection.restart()
group.enter()
connection.cancel()
// Wait for cancelled
result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
}
NetworkAPI.test("NWConnection Waiting DNS")
.skip(.iOSSimulatorAny("Path not fully supported on simulator"))
.skip(.tvOSSimulatorAny("Path not fully supported on simulator"))
.code {
let testQueue = DispatchQueue(label: "testQueue")
let group = DispatchGroup()
let connection = NWConnection(host: "foobar.fake.apple.com", port: .https, using:.tls)
expectNotNil(connection)
connection.stateUpdateHandler = { (newState) in
switch(newState) {
case .waiting(let error):
expectNotNil(error)
switch(error) {
case .dns(let code):
expectEqual(code, DNSServiceErrorType(kDNSServiceErr_NoSuchRecord))
default:
break
}
group.leave()
case .failed(let error):
expectNotNil(error)
connection.cancel()
case .cancelled:
group.leave()
default:
break
}
}
group.enter()
connection.start(queue: testQueue)
// Wait for waiting
var result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
group.enter()
connection.cancel()
// Wait for cancelled
result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
}
NetworkAPI.test("NWConnection TCP")
.skip(.iOSSimulatorAny("Path not fully supported on simulator"))
.skip(.tvOSSimulatorAny("Path not fully supported on simulator"))
.code {
let testQueue = DispatchQueue(label: "testQueue")
let group = DispatchGroup()
let viableGroup = DispatchGroup()
let pathGroup = DispatchGroup()
let sendGroup = DispatchGroup()
let receiveGroup = DispatchGroup()
let listener = try! NWListener(using: .tcp, on: 2345)
expectNotNil(listener)
var inboundConnection: NWConnection? = nil
listener.newConnectionHandler = { (newConn) in
expectNotNil(newConn)
inboundConnection = newConn
newConn.receive(minimumIncompleteLength: 5, maximumLength: 5) { (receivedContent, context, isComplete, receivedError) in
expectTrue(!isComplete)
expectNil(receivedError)
expectNotNil(receivedContent)
expectNotNil(context)
receiveGroup.leave()
}
newConn.start(queue: testQueue)
}
listener.start(queue: testQueue)
// Make sure connecting by address works
let ipv4Address = IPv4Address("127.0.0.1")
let connection = NWConnection(to: NWEndpoint.hostPort(host: .ipv4(ipv4Address!), port: 2345), using:.tcp)
expectNotNil(connection)
connection.stateUpdateHandler = { (newState) in
switch(newState) {
case .ready:
group.leave()
case .failed(let error):
expectNotNil(error)
connection.cancel()
case .cancelled:
group.leave()
default:
break
}
}
connection.pathUpdateHandler = { (newPath) in
expectNotNil(newPath)
pathGroup.leave()
}
connection.viabilityUpdateHandler = { (isViable) in
expectTrue(isViable)
viableGroup.leave()
}
connection.betterPathUpdateHandler = { (betterPathAvailable) in
expectTrue(!betterPathAvailable)
}
group.enter()
viableGroup.enter()
pathGroup.enter()
receiveGroup.enter()
connection.start(queue: testQueue)
// Wait for ready
var result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
let path = connection.currentPath
expectNotNil(path)
if let path = path {
expectTrue(path.usesInterfaceType(.loopback))
expectNotNil(path.localEndpoint)
expectNotNil(path.remoteEndpoint)
}
let metadata = connection.metadata(definition: NWProtocolTCP.definition)
expectNotNil(metadata)
expectTrue(metadata is NWProtocolTCP.Metadata)
let tcpMetadata = metadata as! NWProtocolTCP.Metadata
expectEqual(tcpMetadata.availableReceiveBuffer, 0)
expectEqual(tcpMetadata.availableSendBuffer, 0)
// Wait for viable
result = viableGroup.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
// Wait for path
result = pathGroup.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
expectEqual(connection.queue, testQueue)
expectTrue(connection.parameters.defaultProtocolStack.transportProtocol is NWProtocolTCP.Options)
expectNotNil(connection.endpoint)
sendGroup.enter()
let sendContent: Data = "hello".data(using: .utf8)!
connection.send(content: sendContent, isComplete: false, completion: .contentProcessed({ (sendError) in
expectNil(sendError)
sendGroup.leave()
}))
// Wait for send
result = sendGroup.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
// Wait for receive
result = receiveGroup.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
// Send complete
connection.send(content: sendContent, contentContext: .finalMessage, isComplete: true, completion: .idempotent)
group.enter()
connection.cancel()
// Wait for cancelled
result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
if let inboundConnection = inboundConnection {
inboundConnection.forceCancel()
}
listener.cancel()
}
NetworkAPI.test("NWConnection UDP")
.skip(.iOSSimulatorAny("Path not fully supported on simulator"))
.skip(.tvOSSimulatorAny("Path not fully supported on simulator"))
.code {
let testQueue = DispatchQueue(label: "testQueue")
let group = DispatchGroup()
let cancelGroup = DispatchGroup()
let receiveGroup = DispatchGroup()
var inboundConnection: NWConnection? = nil
let listener = try! NWListener(using: .udp, on: 4567)
expectNotNil(listener)
listener.newConnectionHandler = { (newConn) in
expectNotNil(newConn)
inboundConnection = newConn
newConn.receive() { (receivedContent, context, isComplete, receivedError) in
expectTrue(isComplete)
expectNil(receivedError)
expectNotNil(receivedContent)
expectNotNil(context)
receiveGroup.leave()
}
newConn.start(queue: testQueue)
}
listener.start(queue: testQueue)
let connection = NWConnection(host: "localhost", port: 4567, using:.udp)
expectNotNil(connection)
connection.stateUpdateHandler = { (newState) in
switch(newState) {
case .ready:
group.leave()
case .failed(let error):
expectNotNil(error)
connection.cancel()
case .cancelled:
cancelGroup.leave()
default:
break
}
}
group.enter()
receiveGroup.enter()
connection.start(queue: testQueue)
// Wait for ready
var result = group.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
expectEqual(connection.queue, testQueue)
expectTrue(connection.parameters.defaultProtocolStack.transportProtocol is NWProtocolUDP.Options)
expectNotNil(connection.endpoint)
let ipMetadata = NWProtocolIP.Metadata()
ipMetadata.ecn = .ect0
let sendContext = NWConnection.ContentContext(identifier: "sendHello", expiration: 5000, priority: 1.0, isFinal: false, antecedent: nil, metadata: [ipMetadata])
expectNotNil(sendContext)
expectNotNil(sendContext.protocolMetadata)
expectNil(sendContext.antecedent)
expectEqual(sendContext.expirationMilliseconds, 5000)
expectEqual(sendContext.relativePriority, 1.0)
expectEqual(sendContext.isFinal, false)
expectEqual(sendContext.identifier, "sendHello")
let sendContent: Data = "hello".data(using: .utf8)!
connection.batch {
connection.send(content: sendContent, contentContext: sendContext, completion: .idempotent)
}
// Wait for receive
result = receiveGroup.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
cancelGroup.enter()
connection.cancelCurrentEndpoint()
connection.cancel()
// Wait for cancelled
result = cancelGroup.wait(timeout: DispatchTime.now() + .seconds(10))
expectTrue(result == .success)
if let inboundConnection = inboundConnection {
inboundConnection.forceCancel()
}
listener.cancel()
}
}
#endif
| 30.538206 | 162 | 0.763127 |
6af8135a78181f82938f27b6abb75a1f8752c99e
| 1,740 |
//
// MIT License
//
// Copyright (c) 2019 Alexandre Frigon
//
// 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
class UserService {
let userId: String
init?(for token: String) {
self.userId = ""
// guard let info = JSONWebToken.decodeData(from: token) else { return nil }
// guard let userId = info["id"] as? String else { return nil }
// self.userId = userId
}
func getUsername(callback: @escaping (String) -> Void) {
return callback("Xehos")
}
func getProfilePicture(callback: @escaping (UIImage?) -> Void) {
return callback(#imageLiteral(resourceName: "profile"))
}
}
| 37.826087 | 84 | 0.69023 |
144ba838f0cc1d2a37f020f8e6dcfd223050cea2
| 6,294 |
/**
Copyright IBM Corporation 2016, 2017
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
import SwiftKuery
@testable import SwiftKueryPostgreSQL
#if os(Linux)
let tableAlias = "tableAliasLinux"
#else
let tableAlias = "tableAliasOSX"
#endif
class TestAlias: XCTestCase {
static var allTests: [(String, (TestAlias) -> () throws -> Void)] {
return [
("testAlias", testAlias),
]
}
class MyTable : Table {
let a = Column("a")
let b = Column("b")
let tableName = tableAlias
}
func testAlias() {
let t = MyTable()
let pool = CommonUtils.sharedInstance.getConnectionPool()
performTest(asyncTasks: { expectation in
pool.getConnection() { connection, error in
guard let connection = connection else {
XCTFail("Failed to get connection")
return
}
cleanUp(table: t.tableName, connection: connection) { result in
executeRawQuery("CREATE TABLE \"" + t.tableName + "\" (a varchar(40), b integer)", connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "CREATE TABLE failed")
XCTAssertNil(result.asError, "Error in CREATE TABLE: \(result.asError!)")
let i1 = Insert(into: t, rows: [["apple", 10], ["apricot", 3], ["banana", 17], ["apple", 17], ["banana", -7], ["banana", 27]])
executeQuery(query: i1, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "INSERT failed")
XCTAssertNil(result.asError, "Error in INSERT: \(result.asError!)")
let s1 = Select(t.a.as("\"fruit name\""), t.b.as("number"), from: t)
executeQuery(query: s1, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "SELECT failed")
XCTAssertNotNil(result.asResultSet, "SELECT returned no rows")
XCTAssertNotNil(rows, "SELECT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 6, "SELECT returned wrong number of rows: \(rows!.count) instead of 6")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles[1], "number", "Wrong column name: \(titles[1]) instead of 'number'")
XCTAssertEqual(titles[0], "fruit name", "Wrong column name: \(titles[0]) instead of 'fruit name'")
let s2 = Select(from: t.as("new"))
executeQuery(query: s2, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "SELECT failed")
XCTAssertNotNil(rows, "SELECT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 6, "SELECT returned wrong number of rows: \(rows!.count) instead of 6")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles[0], "a", "Wrong column name: \(titles[0]) instead of 'a'")
XCTAssertEqual(titles[1], "b", "Wrong column name: \(titles[1]) instead of 'b'")
let t2 = t.as("\"t 2\"")
let s3 = Select(t2.a, from: t2)
executeQuery(query: s3, connection: connection) { result, rows in
XCTAssertEqual(result.success, true, "SELECT failed")
XCTAssertNotNil(rows, "SELECT returned no rows")
let resultSet = result.asResultSet!
XCTAssertEqual(rows!.count, 6, "SELECT returned wrong number of rows: \(rows!.count) instead of 6")
resultSet.getColumnTitles() { titles, error in
guard let titles = titles else {
XCTFail("No titles in result set")
return
}
XCTAssertEqual(titles[0], "a", "Wrong column name: \(titles[0]) instead of 'a'")
expectation.fulfill()
}
}
}
}
}
}
}
}
}
}
})
}
}
| 52.45 | 150 | 0.449952 |
08e4036ac72bc50dffa23cf7868a2c6d09f06bc9
| 4,556 |
//
// StatisticsPageViewController.swift
// cena
//
// Created by Thibault Gagnaux on 21.08.18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import UICircularProgressRing
import PromiseKit
import SwiftEntryKit
struct pageNames {
static let YourContribution = "Your Contribution"
static let CommunityContribution = "Community Contribution"
}
class StatisticsPageViewController: UIPageViewController {
// MARK: Properties
weak var customPageControlDelegate: CustomPageControlDelegate?
fileprivate lazy var pages: [UIViewController] = {
return [
self.getViewController(withIdentifier: pageNames.YourContribution),
self.getViewController(withIdentifier: pageNames.CommunityContribution)]
}()
fileprivate var currentIndex: Int!
fileprivate func getViewController(withIdentifier identifier: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier)
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
currentIndex = 0
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reload))
navigationItem.rightBarButtonItem?.tintColor = .white
customPageControlDelegate?.didUpadtePageCount(viewController: self, newPageCount: pages.count)
if let firstVC = pages.first {
setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
}
}
@objc func reload() {
guard let currentPage = pages[currentIndex] as? ProgressRingProtocol else { return }
navigationItem.rightBarButtonItem?.isEnabled = false
if let communityPage = pages[currentIndex] as? CommunityContributionController {
communityPage.resetProgressRing()
communityPage.setSwipesCount()
} else {
currentPage.resetProgressRing()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
currentPage.startNormalAnimation()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.navigationItem.rightBarButtonItem?.isEnabled = true
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
for page in self.pages {
guard let page = page as? ProgressRingProtocol else { return }
page.willAnimate = true
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
}
extension StatisticsPageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = getPageIndex(page: viewController, pages: pages) else { return nil }
return index > 0 ? pages[index - 1] : nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = getPageIndex(page: viewController, pages: pages) else { return nil }
return index + 1 < pages.count ? pages[index + 1] : nil
}
}
extension StatisticsPageViewController: UIPageViewControllerDelegate {
private func getPageIndex(page: UIViewController?, pages: [UIViewController]) -> Int? {
return pages.index(where: {$0 == page })
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if finished && completed {
let currentPage = pageViewController.viewControllers?.first
guard let index = getPageIndex(page: currentPage, pages: pages) else { return }
currentIndex = index
customPageControlDelegate?.didUpdatePageIndex(viewController: self, newPageIndex: currentIndex)
self.navigationItem.title = currentPage?.navigationItem.title
}
}
}
protocol CustomPageControlDelegate: class {
func didUpadtePageCount(viewController: UIViewController, newPageCount: Int)
func didUpdatePageIndex(viewController: UIViewController, newPageIndex: Int)
}
| 38.940171 | 190 | 0.68986 |
5d5604a759eec937862b63f6799658158d2cde43
| 8,413 |
//
// InformationVC.swift
// Partner
//
// Created by LiuXinQiang on 2018/3/5.
//
import UIKit
import SDWebImage
import MJRefresh
class InformationVC: UIViewController ,UITableViewDelegate , UITableViewDataSource, UITextFieldDelegate{
//初始化资讯模型数组
var infoModelArr = [TypeListModel]()
@IBOutlet weak var InformationChildsView: UIScrollView!
@IBOutlet weak var scrollH: NSLayoutConstraint!
@IBOutlet weak var searchTextF: UITextField!
var pageNum = 1
//标记nextPage 是否为空
var nextPage = 1
var newsModelArr = [infoModel]()
var type = 0
@IBOutlet weak var newsListTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
getInfoList(type:type, fuzzy: nil)
getTypeList()
loadRefreshComponet(tableView: newsListTableView)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text ?? ""
let fuzzy = (currentText as NSString).replacingCharacters(in: range, with: string)
if fuzzy == "" {
scrollH.constant = 100
}else{
scrollH.constant = 0
}
self.newsModelArr.removeAll()
setdeafultStatus()
getInfoList(type:0, fuzzy: fuzzy)
return true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.searchTextF.resignFirstResponder()
}
//初始化scrollView
func initScroll(){
self.InformationChildsView.showsHorizontalScrollIndicator = false
let modelCount = infoModelArr.count
self.InformationChildsView.contentSize.width = CGFloat(modelCount * 110)
for i in 0..<modelCount {
//取出模型
let model = infoModelArr[i]
let x = CGFloat(i) * 100 + CGFloat(i + 1) * 10
let btn = UIButton.init(frame: CGRect.init(x: x, y: 0, width: 100, height: 100))
btn.contentHorizontalAlignment = .center
btn.contentVerticalAlignment = .center
btn.layer.cornerRadius = 5
btn.clipsToBounds = true
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.setTitle(model.typeName, for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.backgroundColor = UIColor.blue
btn.addTarget(self, action: #selector(btnClickShowTbaleList(btn:)), for: .touchUpInside)
btn.tag = Int(truncating: model.typeId!) + 9231
if let imageUrl = model.imgUrl {
btn.setBackgroundImageFor(.normal, with:URL.init(string: imageUrl)!)
}
self.InformationChildsView.addSubview(btn)
}
}
func loadRefreshComponet(tableView : UITableView) -> () {
//默认下拉刷新
tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refresh))
//上拉刷新
tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(endrefresh))
//自动根据有无数据来显示和隐藏
tableView.mj_footer.isAutomaticallyHidden = true
// 设置自动切换透明度(在导航栏下面自动隐藏)
tableView.mj_header.isAutomaticallyChangeAlpha = true
}
@objc func refresh() -> () {
self.newsModelArr.removeAll()
setdeafultStatus()
getInfoList(type:type, fuzzy: nil)
}
@objc func endrefresh() -> (){
getInfoList(type:type, fuzzy: nil)
}
//设置初始状态
func setdeafultStatus(){
self.newsModelArr.removeAll()
pageNum = 1
nextPage = 1
}
//展示列表
@objc func btnClickShowTbaleList(btn : UIButton){
type = btn.tag - 9231
self.newsModelArr.removeAll()
setdeafultStatus()
getInfoList(type:type, fuzzy: nil)
}
}
extension InformationVC {
//资讯类型列表(info/type/list)
func getTypeList(){
self.newsModelArr.removeAll()
setdeafultStatus()
//TypeListModel
NetWorkTool.shareInstance.getTypeList {[weak self](result, error) in
guard error == nil else {
return
}
if result?["code"] as? Int == 200 {
guard result != nil else{
return
}
if let dictArr = result!["result"] as? [NSDictionary]{
for i in 0..<dictArr.count{
if let statusViewModel = TypeListModel.mj_object(withKeyValues: dictArr[i]){
self?.infoModelArr.append(statusViewModel)
}
}
self?.initScroll()
}
}else{
let errorShow = result!["msg"] as! String
self?.presentHintMessage(hintMessgae: errorShow, completion: nil)
}
}
}
//加载资讯列表
func getInfoList(type : Int?, fuzzy : String?){
if self.nextPage == 0 {
newsListTableView.mj_footer.endRefreshingWithNoMoreData()
return
}
NetWorkTool.shareInstance.getInfoList(type: type, fuzzy: fuzzy, pageNum: pageNum) { [weak self](info, error) in
if error == nil {
// MARK:- judge the return data from server
if info?["code"] as? Int == 200 {
guard let resultArray = info else{
return
}
let dict = resultArray["result"] as? NSDictionary
if let statusViewModel = StatusViewModel.mj_object(withKeyValues: dict)
{
if statusViewModel.nextPage == 0 {
self?.nextPage = 0
}else{
self?.nextPage = statusViewModel.nextPage as! Int
}
self?.pageNum += 1
}
if let dictARR = info?["result"]!["list"] as? [NSDictionary]{
for dict in dictARR{
let model = infoModel.mj_object(withKeyValues: dict)
self?.newsModelArr.append(model!)
}
self?.newsListTableView.mj_header.endRefreshing()
self?.newsListTableView.reloadData()
}
} else {
let errorShow = info!["msg"] as! String
self?.presentHintMessage(hintMessgae: errorShow, completion: nil)
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsModelArr.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfomationCellID", for: indexPath) as! InfomationCell
if self.newsModelArr.count > 0 {
//取出模型
let model = newsModelArr[indexPath.row]
cell.viewModel = model
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if self.newsModelArr.count > 0 {
//取出模型
let informationVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "InfoNewsDetailVCID") as! InfoNewsDetailVC
let model = newsModelArr[indexPath.row]
if let urlStr = model.infoUrl{
let url = NSURL.init(string: urlStr)
informationVC.url = url
}
if let id = model.infoId{
NetWorkTool.shareInstance.apiScan(id: Int(truncating: id), finished: { (result, error) in
})
}
self.navigationController?.pushViewController(informationVC, animated: true)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.view.endEditing(true)
}
}
| 34.764463 | 158 | 0.55652 |
ede4771337f00b8e6a58a14c16d139e93fab53b4
| 787 |
//
// DataCore.swift
// WeatherMap
//
// Created by Ahmed Alsamani on 14/02/2019.
// Copyright © 2019 Ahmed Alsamani. All rights reserved.
//
import Foundation
import CoreData
class DataController {
let persistentContainer:NSPersistentContainer
static let shared = DataController()
var viewContext:NSManagedObjectContext {
return persistentContainer.viewContext
}
private init() {
persistentContainer = NSPersistentContainer(name: "WeatherMap")
}
func load(completion: (() -> Void)? = nil) {
persistentContainer.loadPersistentStores { storeDescription, error in
guard error == nil else {
fatalError(error!.localizedDescription)
}
completion?()
}
}
}
| 23.848485 | 77 | 0.641677 |
4660070e41f69f8034b446a8afb9b63016e617e0
| 1,523 |
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
extension VisualTriggerView {
/// The view in the visual trigger view that shows that a trigger fired.
class TriggerFiredView: UIView {
// The title label. Must be layed out.
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
private func configureView() {
clipsToBounds = true
backgroundColor = MDCPalette.red.tint500
titleLabel.font = MDCTypography.body2Font()
titleLabel.text = String.triggerFiredText
titleLabel.textColor = .white
addSubview(titleLabel)
}
}
}
| 28.203704 | 87 | 0.724228 |
67bc3175321007b1d3b6adb3e01ce69026a496bd
| 1,162 |
//
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.4.0-29ad3ab0
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
The media type of the expression language.
URL: http://hl7.org/fhir/expression-language
ValueSet: http://hl7.org/fhir/ValueSet/expression-language
*/
public enum ExpressionLanguage: String, FHIRPrimitiveType {
/// Clinical Quality Language.
case textCql = "text/cql"
/// FHIRPath.
case textFhirpath = "text/fhirpath"
/// FHIR's RESTful query syntax - typically independent of base URL.
case applicationXFhirQuery = "application/x-fhir-query"
}
| 29.794872 | 76 | 0.731497 |
c12884f78a135ddc1643d32f14df3b59f7a2bf70
| 19,243 |
//
// LGButton.swift
// LGButtonDemo
//
// Created by Lorenzo Greco on 28/05/2017.
// Copyright © 2017 Lorenzo Greco. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
public class LGButton: UIControl {
enum TouchAlphaValues : CGFloat {
case touched = 0.7
case untouched = 1.0
}
let touchDisableRadius : CGFloat = 100.0
let availableFontIcons = ["fa", "io", "oc", "ic", "ma", "ti", "mi"]
var gradient : CAGradientLayer?
fileprivate var rootView : UIView!
@IBOutlet fileprivate weak var titleLbl: UILabel!
@IBOutlet fileprivate weak var mainStackView: UIStackView!
@IBOutlet fileprivate weak var bgContentView: UIView!
@IBOutlet fileprivate weak var leftIcon: UILabel!
@IBOutlet fileprivate weak var leftImage: UIImageView!
@IBOutlet fileprivate weak var rightIcon: UILabel!
@IBOutlet fileprivate weak var rightImage: UIImageView!
@IBOutlet fileprivate weak var trailingMainConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var leadingMainConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var bottomMainConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var topMainConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var leftImageHeightConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var leftImageWidthConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var rightImageHeightConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var rightImageWidthConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var loadingStackView: UIStackView!
@IBOutlet fileprivate weak var loadingSpinner: UIActivityIndicatorView!
@IBOutlet fileprivate weak var loadingLabel: UILabel!
@IBOutlet fileprivate var trailingLoadingConstraint: NSLayoutConstraint!
@IBOutlet fileprivate var leadingLoadingConstraint: NSLayoutConstraint!
public var isLoading = false {
didSet {
showLoadingView()
}
}
// MARK: - Inspectable properties
// MARK:
@IBInspectable public var bgColor: UIColor = UIColor.gray {
didSet{
setupView()
}
}
@IBInspectable public var showTouchFeedback: Bool = true
@IBInspectable public var gradientStartColor: UIColor? = nil {
didSet{
setupView()
}
}
@IBInspectable public var gradientEndColor: UIColor? = nil {
didSet{
setupView()
}
}
@IBInspectable public var gradientHorizontal: Bool = false {
didSet{
if gradient != nil {
gradient?.removeFromSuperlayer()
gradient = nil
setupView()
}
}
}
@IBInspectable public var gradientRotation: CGFloat = 0 {
didSet{
if gradient != nil {
gradient?.removeFromSuperlayer()
gradient = nil
setupView()
}
}
}
@IBInspectable public var cornerRadius: CGFloat = 0.0 {
didSet{
setupView()
}
}
@IBInspectable public var fullyRoundedCorners: Bool = false {
didSet{
setupBorderAndCorners()
}
}
@IBInspectable public var borderColor: UIColor = UIColor.white {
didSet{
setupView()
}
}
@IBInspectable public var borderWidth: CGFloat = 0.0 {
didSet{
setupView()
}
}
@IBInspectable public var titleColor: UIColor = UIColor.white {
didSet{
setupView()
}
}
@IBInspectable public var titleString: String = "" {
didSet{
setupView()
}
}
@IBInspectable public var titleFontName: String? {
didSet{
setupView()
}
}
@IBInspectable public var titleFontSize: CGFloat = 14.0 {
didSet{
setupView()
}
}
@IBInspectable public var verticalOrientation: Bool = false {
didSet {
setupView()
}
}
@IBInspectable public var leftIconString: String = "" {
didSet{
setupView()
}
}
@IBInspectable public var leftIconFontName: String = " " {
didSet{
setupView()
}
}
@IBInspectable public var leftIconFontSize: CGFloat = 14.0 {
didSet{
setupView()
}
}
@IBInspectable public var leftIconColor: UIColor = UIColor.white {
didSet{
setupView()
}
}
@IBInspectable public var leftImageSrc: UIImage? = nil {
didSet{
setupView()
}
}
@IBInspectable public var leftImageWidth: CGFloat = 20 {
didSet{
setupView()
}
}
@IBInspectable public var leftImageHeight: CGFloat = 20 {
didSet{
setupView()
}
}
@IBInspectable public var leftImageColor: UIColor? = nil {
didSet{
setupView()
}
}
@IBInspectable public var rightIconString: String = "" {
didSet{
setupView()
}
}
@IBInspectable public var rightIconFontName: String = " " {
didSet{
setupView()
}
}
@IBInspectable public var rightIconFontSize: CGFloat = 14.0 {
didSet{
setupView()
}
}
@IBInspectable public var rightIconColor: UIColor = UIColor.white {
didSet{
setupView()
}
}
@IBInspectable public var rightImageSrc: UIImage? = nil {
didSet{
setupView()
}
}
@IBInspectable public var rightImageWidth: CGFloat = 20 {
didSet{
setupView()
}
}
@IBInspectable public var rightImageHeight: CGFloat = 20 {
didSet{
setupView()
}
}
@IBInspectable public var rightImageColor: UIColor? = nil {
didSet{
setupView()
}
}
@IBInspectable public var spacingTitleIcon: CGFloat = 16.0 {
didSet{
setupView()
}
}
@IBInspectable public var spacingTop: CGFloat = 8.0 {
didSet{
setupView()
}
}
@IBInspectable public var spacingBottom: CGFloat = 8.0 {
didSet{
setupView()
}
}
@IBInspectable public var spacingLeading: CGFloat = 16.0 {
didSet{
setupView()
}
}
@IBInspectable public var spacingTrailing: CGFloat = 16.0 {
didSet{
setupView()
}
}
@IBInspectable public var shadowOffset: CGSize = CGSize.init(width:0, height:0) {
didSet{
setupView()
}
}
@IBInspectable public var shadowRadius: CGFloat = 0 {
didSet{
setupView()
}
}
@IBInspectable public var shadowOpacity: CGFloat = 1 {
didSet{
setupView()
}
}
@IBInspectable public var shadowColor: UIColor = UIColor.black {
didSet{
setupView()
}
}
@IBInspectable public var loadingSpinnerColor: UIColor = UIColor.white {
didSet{
setupView()
}
}
@IBInspectable public var loadingColor: UIColor = UIColor.white {
didSet{
setupView()
}
}
@IBInspectable public var loadingString: String = "" {
didSet{
setupView()
}
}
@IBInspectable public var loadingFontName: String? {
didSet{
setupView()
}
}
@IBInspectable public var loadingFontSize: CGFloat = 14.0 {
didSet{
setupView()
}
}
// MARK: - Overrides
// MARK:
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
setupView()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
xibSetup()
setupView()
}
override public func layoutSubviews() {
if gradient != nil {
gradient?.removeFromSuperlayer()
gradient = nil
setupGradientBackground()
}
setupBorderAndCorners()
}
override public var intrinsicContentSize: CGSize {
return CGSize(width: 10, height: 10)
}
// MARK: - Internal functions
// MARK:
// Setup the view appearance
fileprivate func setupView(){
bgContentView.clipsToBounds = true
layer.masksToBounds = false
setIconOrientation()
setupBackgroundColor()
setupGradientBackground()
setupBorderAndCorners()
setupTitle()
setupLeftIcon()
setupRightIcon()
setupLeftImage()
setupRightImage()
setupSpacings()
setupShadow()
setupLoadingView()
}
fileprivate func setIconOrientation() {
if verticalOrientation {
mainStackView.axis = .vertical
}else{
mainStackView.axis = .horizontal
}
}
fileprivate func setupBackgroundColor() {
bgContentView.backgroundColor = bgColor
}
fileprivate func setupGradientBackground() {
if gradientStartColor != nil && gradientEndColor != nil && gradient == nil{
gradient = CAGradientLayer()
gradient!.frame.size = frame.size
gradient!.colors = [gradientStartColor!.cgColor, gradientEndColor!.cgColor]
var rotation:CGFloat!
if gradientRotation >= 0 {
rotation = min(gradientRotation, CGFloat(360.0))
} else {
rotation = max(gradientRotation, CGFloat(-360.0))
}
var xAngle:Float = Float(rotation/360)
if (gradientHorizontal) {
xAngle = 0.25
}
let a = pow(sinf((2*Float(Double.pi)*((xAngle+0.75)/2))),2)
let b = pow(sinf((2*Float(Double.pi)*((xAngle+0.0)/2))),2)
let c = pow(sinf((2*Float(Double.pi)*((xAngle+0.25)/2))),2)
let d = pow(sinf((2*Float(Double.pi)*((xAngle+0.5)/2))),2)
gradient!.startPoint = CGPoint(x: CGFloat(a), y: CGFloat(b))
gradient!.endPoint = CGPoint(x: CGFloat(c), y: CGFloat(d))
bgContentView.layer.addSublayer(gradient!)
}
}
fileprivate func setupBorderAndCorners() {
if fullyRoundedCorners {
bgContentView.layer.cornerRadius = frame.size.height/2
layer.cornerRadius = frame.size.height/2
}else{
bgContentView.layer.cornerRadius = cornerRadius
layer.cornerRadius = cornerRadius
}
bgContentView.layer.borderColor = borderColor.cgColor
bgContentView.layer.borderWidth = borderWidth
}
fileprivate func setupTitle() {
titleLbl.isHidden = titleString.isEmpty
titleLbl.text = titleString
titleLbl.textColor = titleColor
if titleFontName != nil {
titleLbl.font = UIFont.init(name:titleFontName! , size:titleFontSize)
}else{
titleLbl.font = UIFont.systemFont(ofSize: titleFontSize)
}
}
fileprivate func setupLeftIcon(){
setupIcon(icon: leftIcon,
fontName: leftIconFontName,
iconName: leftIconString,
fontSize: leftIconFontSize,
color: leftIconColor)
}
fileprivate func setupRightIcon(){
setupIcon(icon: rightIcon,
fontName: rightIconFontName,
iconName: rightIconString,
fontSize: rightIconFontSize,
color: rightIconColor)
}
fileprivate func setupLeftImage(){
setupImage(imageView: leftImage,
image: leftImageSrc,
color: leftImageColor,
widthConstraint: leftImageWidthConstraint,
heightConstraint: leftImageHeightConstraint,
widthValue: leftImageWidth,
heightValue: leftImageHeight)
leftIcon.isHidden = (leftImageSrc != nil || !availableFontIcons.contains(leftIconFontName))
}
fileprivate func setupRightImage(){
rightIcon.isHidden = rightImageSrc != nil
setupImage(imageView: rightImage,
image: rightImageSrc,
color: rightImageColor,
widthConstraint: rightImageWidthConstraint,
heightConstraint: rightImageHeightConstraint,
widthValue: rightImageWidth,
heightValue: rightImageHeight)
rightIcon.isHidden = (rightImageSrc != nil || !availableFontIcons.contains(rightIconFontName))
}
fileprivate func setupSpacings(){
mainStackView.spacing = spacingTitleIcon
topMainConstraint.constant = spacingTop
bottomMainConstraint.constant = spacingBottom
leadingMainConstraint.constant = spacingLeading
trailingMainConstraint.constant = spacingTrailing
setupBorderAndCorners()
}
fileprivate func setupShadow(){
layer.shadowOffset = shadowOffset
layer.shadowRadius = shadowRadius
layer.shadowOpacity = Float(shadowOpacity)
layer.shadowColor = shadowColor.cgColor
}
fileprivate func setupLoadingView(){
loadingLabel.isHidden = loadingString.isEmpty
loadingLabel.text = loadingString
loadingLabel.textColor = loadingColor
if loadingFontName != nil {
loadingLabel.font = UIFont.init(name:loadingFontName! , size:titleFontSize)
}else{
loadingLabel.font = UIFont.systemFont(ofSize: loadingFontSize)
}
loadingSpinner.color = loadingSpinnerColor
setupBorderAndCorners()
}
fileprivate func setupIcon(icon:UILabel, fontName:String, iconName:String, fontSize:CGFloat, color:UIColor){
icon.isHidden = !availableFontIcons.contains(fontName)
if !icon.isHidden {
icon.textColor = color
switch fontName {
case "fa":
icon.font = UIFont.icon(from: .FontAwesome, ofSize: fontSize)
icon.text = String.fontAwesomeIcon(iconName)
break;
case "io":
icon.font = UIFont.icon(from: .Ionicon, ofSize: fontSize)
icon.text = String.fontIonIcon(iconName)
break;
case "oc":
icon.font = UIFont.icon(from: .Octicon, ofSize: fontSize)
icon.text = String.fontOcticon(iconName)
break;
case "ic":
icon.font = UIFont.icon(from: .Iconic, ofSize: fontSize)
icon.text = String.fontIconicIcon(iconName)
break;
case "ma":
icon.font = UIFont.icon(from: .MaterialIcon, ofSize: fontSize)
icon.text = String.fontMaterialIcon(iconName.replacingOccurrences(of: "-", with: "."))
break;
case "ti":
icon.font = UIFont.icon(from: .Themify, ofSize: fontSize)
icon.text = String.fontThemifyIcon(iconName.replacingOccurrences(of: "-", with: "."))
break;
case "mi":
icon.font = UIFont.icon(from: .MapIcon, ofSize: fontSize)
icon.text = String.fontMapIcon(iconName.replacingOccurrences(of: "-", with: "."))
break;
default:
break;
}
}
setupBorderAndCorners()
}
fileprivate func setupImage(imageView:UIImageView, image:UIImage?, color:UIColor?, widthConstraint:NSLayoutConstraint, heightConstraint:NSLayoutConstraint, widthValue:CGFloat, heightValue:CGFloat){
imageView.isHidden = image == nil
if image != nil {
if color != nil {
imageView.image = image?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = color
}else{
image?.withRenderingMode(.alwaysOriginal)
imageView.image = image
}
widthConstraint.constant = widthValue
heightConstraint.constant = heightValue
}
setupBorderAndCorners()
}
fileprivate func showLoadingView() {
leadingLoadingConstraint.isActive = isLoading
trailingLoadingConstraint.isActive = isLoading
mainStackView.isHidden = isLoading
loadingStackView.isHidden = !isLoading
isUserInteractionEnabled = !isLoading
}
// MARK: - Xib file
// MARK:
fileprivate func xibSetup() {
rootView = loadViewFromNib()
rootView.frame = bounds
rootView.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
addSubview(rootView)
leadingLoadingConstraint.isActive = false
trailingLoadingConstraint.isActive = false
}
fileprivate func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "LGButton", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
// MARK: - Touches
// MARK:
var touchAlpha : TouchAlphaValues = .untouched {
didSet {
updateTouchAlpha()
}
}
var pressed : Bool = false {
didSet {
if !showTouchFeedback {
return
}
touchAlpha = (pressed) ? .touched : .untouched
}
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
pressed = true
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
let shouldSendActions = pressed
pressed = false
if shouldSendActions{
sendActions(for: .touchUpInside)
}
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?){
if let touchLoc = touches.first?.location(in: self){
if (touchLoc.x < -touchDisableRadius ||
touchLoc.y < -touchDisableRadius ||
touchLoc.x > self.bounds.size.width + touchDisableRadius ||
touchLoc.y > self.bounds.size.height + touchDisableRadius){
pressed = false
}
else if self.touchAlpha == .untouched {
pressed = true
}
}
}
override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
pressed = false
}
func updateTouchAlpha() {
if self.alpha != self.touchAlpha.rawValue {
UIView.animate(withDuration: 0.3) {
self.alpha = self.touchAlpha.rawValue
}
}
}
}
| 29.378626 | 201 | 0.571013 |
ac42684ac566cfdccd1c0c68c76e658b4c9a189f
| 3,838 |
//
// AKFormantFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// When fed with a pulse train, it will generate a series of overlapping
/// grains. Overlapping will occur when 1/freq < dec, but there is no upper
/// limit on the number of overlaps.
///
open class AKFormantFilter: AKNode, AKToggleable, AKComponent, AKInput {
public typealias AKAudioUnitType = AKFormantFilterAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(effect: "fofi")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var xParameter: AUParameter?
fileprivate var yParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// x
@objc open dynamic var x: Double = 0 {
willSet {
if x != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
xParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.x = Float(newValue)
}
}
}
}
/// y
@objc open dynamic var y: Double = 0 {
willSet {
if y != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
yParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.y = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - Parameters:
/// - input: Input node to process
/// - x: X Value
/// - y: Y Value
///
@objc public init(
_ input: AKNode? = nil,
x: Double = 0,
y: Double = 0) {
self.x = x
self.y = y
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
input?.connect(to: self!)
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
xParameter = tree["x"]
yParameter = tree["y"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.x = Float(x)
internalAU?.y = Float(y)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| 29.29771 | 95 | 0.560188 |
1d10cd8660779f9a1d69374f73bdc0d9b3538475
| 432 |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
if{protocol A{
enum a{let a{class
case,
| 36 | 78 | 0.75 |
48f07f7a9dc92af9a5af811b6b64453d4a1f082e
| 1,941 |
//
// Enum+UserType.swift
// DDD
//
// Created by ParkSungJoon on 02/03/2019.
// Copyright © 2019 Gunter. All rights reserved.
//
import Foundation
import UIKit
enum UserType: Int {
case general = 2
case admin = 1
init(userType: Int) {
switch userType {
case 1: self = .admin
default: self = .general
}
}
var backgroundColor: UIColor {
switch self {
case .general: return UIColor.white
case .admin: return UIColor.black
}
}
var circleImage: UIImage {
switch self {
case .general: return #imageLiteral(resourceName: "normalBlackRound")
case .admin: return #imageLiteral(resourceName: "adminWhiteRound")
}
}
var titleColor: UIColor {
switch self {
case .general: return UIColor.dddGray
case .admin: return UIColor.white
}
}
var descriptionColor: UIColor {
switch self {
case .general: return UIColor.dddLightGray
case .admin: return UIColor.white
}
}
var textFieldColor: UIColor {
switch self {
case .general: return UIColor.white
case .admin: return UIColor.dddBlack
}
}
var textFieldEditable: Bool {
switch self {
case .general: return true
case .admin: return false
}
}
var titleText: String {
switch self {
case .general: return "번호 입력해주세요"
case .admin: return "출석체크를 시작해주세요"
}
}
var descriptionText: String {
switch self {
case .general: return "라운드에 번호를 입력해주셔야 출석 체크 버튼이\n 활성화가 되어 출석 체크가 가능합니다."
case .admin: return "라운드에 나오는 숫자를 멤버들에게 알려주셔야\n 멤버분들이 출석 체크가 가능합니다."
}
}
var buttonText: String {
switch self {
case .general: return "출석체크"
case .admin: return "출석체크 시작"
}
}
}
| 22.569767 | 81 | 0.561051 |
2f7cb2e08f5793a2c90126c6e58fbe9d8e0195f8
| 9,631 |
import Foundation
import Stripe
import Capacitor
internal enum StripePluginError : Error {
case InvalidApplePayRequest(String)
}
internal enum ApplePayMode {
case PaymentIntent
case Token
}
internal struct ApplePayContext {
var callbackId: String
var mode: ApplePayMode
var completion: ((PKPaymentAuthorizationResult) -> Void)?
var clientSecret: String?
}
internal func pmTypeToStr(_ pmType: STPPaymentMethodType?) -> String {
switch pmType {
case .typeCard:
return "card"
case .typeCardPresent:
return "card_present"
case .typeFPX:
return "fpx"
case .typeiDEAL:
return "ideal"
// TODO add more types
default:
return "unknown"
}
}
internal func strToPmType(_ pmTypeStr: String?) -> STPPaymentMethodType {
switch pmTypeStr {
case "card":
return .typeCard
// TODO add more types
default:
return .typeUnknown
}
}
internal func strToBrand(_ brand: String?) -> STPCardBrand {
switch brand {
case "American Express":
return STPCardBrand.amex
case "Discover":
return STPCardBrand.discover
case "JCB":
return STPCardBrand.JCB
case "Diners Club":
return STPCardBrand.dinersClub
case "Visa":
return STPCardBrand.visa
case "MasterCard":
return STPCardBrand.masterCard
case "UnionPay":
return STPCardBrand.unionPay
default:
return STPCardBrand.unknown
}
}
internal func brandToStr(_ brand: STPCardBrand) -> String {
switch brand {
case STPCardBrand.amex:
return "American Express"
case STPCardBrand.discover:
return "Discover"
case STPCardBrand.JCB:
return "JCB"
case STPCardBrand.dinersClub:
return "Diners Club"
case STPCardBrand.visa:
return "Visa"
case STPCardBrand.masterCard:
return "MasterCard"
case STPCardBrand.unionPay:
return "UnionPay"
default:
return "Unknown"
}
}
internal func ensurePluginInitialized(_ call: CAPPluginCall) -> Bool {
let key = Stripe.defaultPublishableKey()
if key == nil || key == "" {
call.error("you must call setPublishableKey to initialize the plugin before calling this method")
return false
}
return true
}
internal func address(_ obj: [String: String]) -> STPPaymentMethodAddress {
let a = STPPaymentMethodAddress()
a.line1 = obj["address_line1"]
a.line2 = obj["address_line2"]
a.city = obj["address_city"]
a.state = obj["address_state"]
a.postalCode = obj["address_zip"]
a.country = obj["country"]
return a
}
internal func address(fromObj: [String: Any]) -> STPPaymentMethodAddress {
return address(addressDict(fromObj: fromObj))
}
internal func addressDict(fromObj: [String: Any]) -> [String: String] {
return [
"address_line1": fromObj["address_line1"] as? String ?? "",
"address_line2": fromObj["address_line2"] as? String ?? "",
"address_city": fromObj["address_city"] as? String ?? "",
"address_state": fromObj["address_state"] as? String ?? "",
"address_zip": fromObj["address_zip"] as? String ?? "",
"address_country": fromObj["address_country"] as? String ?? "",
]
}
internal func addressDict(fromCall: CAPPluginCall) -> [String: String] {
return [
"address_line1": fromCall.getString("address_line1") ?? "",
"address_line2": fromCall.getString("address_line2") ?? "",
"address_city": fromCall.getString("address_city") ?? "",
"address_state": fromCall.getString("address_state") ?? "",
"address_zip": fromCall.getString("address_zip") ?? "",
"address_country": fromCall.getString("address_country") ?? "",
]
}
internal func cardParams(fromObj: [String: Any]) -> STPCardParams {
let p = STPCardParams()
p.number = fromObj["number"] as? String ?? ""
p.cvc = fromObj["cvc"] as? String ?? ""
if let exp_yearStr = fromObj["exp_year"] as? String {
p.expYear = UInt(exp_yearStr) ?? 0
} else if let exp_yearInt = fromObj["exp_year"] as? Int {
p.expYear = UInt(exp_yearInt)
}
if let exp_monthStr = fromObj["exp_month"] as? String {
p.expMonth = UInt(exp_monthStr) ?? 0
} else if let exp_monthInt = fromObj["exp_month"] as? Int {
p.expMonth = UInt(exp_monthInt)
}
if let n = fromObj["name"] as? String, n != "" {
p.name = n
}
if let c = fromObj["currency"] as? String, c != "" {
p.currency = c
}
return p
}
internal func cardParams(
fromObj: [String: Any],
withAddress: [String: String]) -> STPCardParams {
let p = cardParams(fromObj: fromObj)
let pmbd = STPPaymentMethodBillingDetails()
pmbd.address = address(withAddress)
p.address = STPAddress.init(paymentMethodBillingDetails: pmbd)
return p
}
internal func cardParams(fromCall: CAPPluginCall) -> STPCardParams {
var c = [
"number": fromCall.getString("number"),
"cvc": fromCall.getString("cvc"),
"exp_month": fromCall.getString("exp_month"),
"exp_year": fromCall.getString("exp_year"),
"name": fromCall.getString("name"),
"currency": fromCall.getString("currency"),
"country": fromCall.getString("country")
]
if c["exp_month"] == nil, fromCall.hasOption("exp_month"), let em = fromCall.getInt("exp_month") {
c["exp_month"] = String(em)
}
if c["exp_year"] == nil, fromCall.hasOption("exp_year"), let em = fromCall.getInt("exp_year") {
c["exp_year"] = String(em)
}
let a = addressDict(fromCall: fromCall)
return cardParams(fromObj: c as [String: Any], withAddress: a)
}
internal func applePayOpts(obj: [String: Any]) throws -> PKPaymentRequest {
let merchantId = obj["merchantId"] as? String ?? ""
let country = obj["country"] as? String ?? ""
let currency = obj["currency"] as? String ?? ""
let items = obj["items"] as? [[String: Any]] ?? []
if merchantId == "" {
throw StripePluginError.InvalidApplePayRequest("you must provide a valid merchant identifier")
}
if country == "" {
throw StripePluginError.InvalidApplePayRequest("you must provide a country")
}
if currency == "" {
throw StripePluginError.InvalidApplePayRequest("you must provide a currency")
}
if items.count == 0 {
throw StripePluginError.InvalidApplePayRequest("you must provide at least one item")
}
let paymentRequest = Stripe.paymentRequest(withMerchantIdentifier: merchantId, country: country, currency: currency)
paymentRequest.paymentSummaryItems = []
for it in items {
let label = it["label"] as? String ?? ""
let amount = it["amount"] as? NSNumber
let amountD: NSDecimalNumber;
if amount == nil {
if let a = it["amount"] as? String, let ad = Decimal(string: a) {
amountD = NSDecimalNumber(decimal: ad)
}
throw StripePluginError.InvalidApplePayRequest("each item must have an amount greater than 0")
} else {
amountD = NSDecimalNumber(decimal: amount!.decimalValue)
}
paymentRequest.paymentSummaryItems.append(
PKPaymentSummaryItem(label: label, amount: amountD)
)
}
if Stripe.canSubmitPaymentRequest(paymentRequest) {
return paymentRequest
} else {
throw StripePluginError.InvalidApplePayRequest("invalid request")
}
}
internal func applePayOpts(call: CAPPluginCall) throws -> PKPaymentRequest {
let obj = call.getObject("applePayOptions")
if obj == nil {
throw StripePluginError.InvalidApplePayRequest("you must provide applePayOptions")
}
return try applePayOpts(obj: obj!)
}
internal func pmCardToJSON(c: STPPaymentMethodCard) -> [String: Any] {
var cval: [String: Any] = [
"brand": brandToStr(c.brand),
"exp_month": c.expMonth,
"exp_year": c.expYear,
]
if let c = c.country {
cval["country"] = c
}
if let f = c.funding {
cval["funding"] = f
}
if let l = c.last4 {
cval["last4"] = l
}
if let t = c.threeDSecureUsage {
cval["three_d_secure_usage"] = [
"supported": t.supported
]
}
return cval
}
internal func pmToJSON(m: STPPaymentMethod) -> [String: Any] {
var val: [String: Any] = [
"id": m.stripeId,
"livemode": m.liveMode,
"type": pmTypeToStr(m.type),
]
if let cid = m.customerId {
val["customerId"] = cid
}
if let c = m.created {
val["created"] = c.timeIntervalSince1970
}
if let c = m.card {
val["card"] = pmCardToJSON(c: c)
}
return val
}
internal func makeBankAccountParams(call: [AnyHashable: Any]!) -> STPBankAccountParams {
let params = STPBankAccountParams()
params.accountNumber = call["account_number"] as? String ?? ""
params.country = call["country"] as? String ?? ""
params.currency = call["currency"] as? String ?? ""
params.routingNumber = call["routing_number"] as? String ?? ""
params.accountHolderName = call["account_holder_name"] as? String ?? ""
let accountHolderType = call["account_holder_type"] as? String ?? ""
if accountHolderType == "individual" {
params.accountHolderType = STPBankAccountHolderType.individual
} else if accountHolderType == "company" {
params.accountHolderType = STPBankAccountHolderType.company
}
return params
}
| 29.096677 | 120 | 0.629737 |
39cb20a2ca7c6df8b8ae85c983b8e9e9ec0f01b9
| 2,134 |
//
// UITableViewCellExtension.swift
// FluxWithRxSwiftSample
//
// Created by Yuji Hato on 2016/10/13.
// Copyright © 2016年 dekatotoro. All rights reserved.
//
import UIKit
extension UITableView {
func reloadToStartPosition(includeInset: Bool = false) {
reloadData()
contentOffset = includeInset ? CGPoint(x: 0, y: contentInset.top) : .zero
}
//register.
func registerCell<T: CellNibable>(cell: T.Type) {
register(cell.nib, forCellReuseIdentifier: cell.identifier)
}
func registerHeaderFooterView<T: ReusableViewNibable>(headerFooterView: T.Type) {
register(headerFooterView.nib, forHeaderFooterViewReuseIdentifier: headerFooterView.identifier)
}
//dequeue.
func dequeueReusableCellWithIdentifier<T>(identifier: String) -> T {
return dequeueReusableCell(withIdentifier: identifier) as! T
}
func dequeueReusableCellWithIdentifier<T>(identifier: String, forIndexPath indexPath: IndexPath) -> T {
return dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! T
}
func dequeueReusableCell<T: CellNibable>(type: T.Type) -> T {
return dequeueReusableCell(withIdentifier: type.identifier) as! T
}
func dequeueReusableCell<T: CellNibable>(type: T.Type, forIndexPath indexPath: IndexPath) -> T {
return dequeueReusableCell(withIdentifier: type.identifier, for: indexPath) as! T
}
func dequeueReusableHeaderFooterViewWithIdentifier<T>(identifier: String) -> T {
return dequeueReusableHeaderFooterView(withIdentifier: identifier) as! T
}
func dequeueReusableHeaderFooterView<T: ReusableViewNibable>(type: T.Type) -> T {
return dequeueReusableHeaderFooterViewWithIdentifier(identifier: type.identifier)
}
}
extension UITableView {
func cellsForRowAtIndexPathRow<T>(row: Int) -> [T] {
guard let indexPaths = indexPathsForVisibleRows else {
return []
}
let cells = indexPaths.filter { $0.row == row }.map { cellForRow(at: $0) }
return cells.flatMap { $0 as? T }
}
}
| 34.419355 | 107 | 0.687441 |
e03a5e0bb80085e24f7614dd9d893130bea92069
| 2,148 |
//
// AppDelegate.swift
// IOS8SwiftPrototypeCellsTutorial
//
// Created by Arthur Knopper on 10/08/14.
// Copyright (c) 2014 Arthur Knopper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.695652 | 281 | 0.765829 |
d7f71e6243f63013585db61a44d99007bd85c337
| 993 |
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "GeometryHelpers",
platforms: [
.iOS(.v11),
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "GeometryHelpers",
targets: ["GeometryHelpers"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "GeometryHelpers",
dependencies: [],
path: "Sources"),
]
)
| 33.1 | 117 | 0.634441 |
fecc623f470a38ad70ba0cee9648e2d4822ccea8
| 231 |
//
// TestAppApp.swift
// TestApp
//
// Created by Tahsin Jahin Khalid on 17/12/21.
//
import SwiftUI
@main
struct TestAppApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.833333 | 47 | 0.562771 |
b9aa8744c81115097d2345a1efaf82532f046cb9
| 1,224 |
/*:
## Breaking It Down
Each verse of the nursery rhyme follows a pattern:
- The first two lines are the same each verse.
- The next two lines change each verse.
- You take a breath between verses.
When programmers are faced with a long list of tasks, like printing the original nursery rhyme, they often break the single long list down into multiple smaller lists. This is called _decomposition_. When you're choosing how to break apart your list, it's helpful to find the smallest pieces of work that are still meaningful. For example, to split a single verse into multiple meaningful functions, you could do this:
*/
func rowTheBoat() {
print("Row, row, row your boat")
print("Gently down the stream")
}
func merrilyDream() {
print("Merrily, merrily, merrily, merrily")
print("Life is but a dream")
}
func breatheBetweenVerses() {
print("crocodileScream")
}
//: Now you can use these functions to print the first verse and the start of the second verse like this:
rowTheBoat()
merrilyDream()
breatheBetweenVerses()
rowTheBoat()
//: Next, learn about making larger groups of tasks.
//:
//: [Previous](@previous) | page 5 of 12 | [Next: Functions Within Functions](@next)
| 26.608696 | 419 | 0.72549 |
7237174f2d2376370d85e4b5510affe2be9e75c6
| 1,473 |
//
// IRNumberKeyboardImage.swift
// IRNumberKeyboard
//
// Created by Dirk van Oosterbosch on 26/11/2019.
// Copyright © 2019 IR Labs. All rights reserved.
//
import UIKit
/**
Helper struct make the Special Key Keyboard Images publicly available.
Usage:
let img = IRNumberKeyboardImage.delete.image()
*/
public enum IRNumberKeyboardImage: CustomStringConvertible {
/// The backspace button image
case delete
/// An image of a keyboard with a down arrow to indicate the dismising of the keyboard
case dismiss
/// A special arithmetic symbol to invert the sign of the number.
case plusMinusSign
public var description: String {
switch self {
case .delete:
return "delete"
case .dismiss:
return "dismiss"
case .plusMinusSign:
return "plusMinusSign"
}
}
/**
Returns the image of this key.
To be used in the configuration of the special key.
*/
public func image() -> UIImage {
if let img = IRNumberKeyboardImageGetter.keyboardImage(named: self.description) {
return img.withRenderingMode(.alwaysTemplate)
}
return UIImage()
}
}
fileprivate class IRNumberKeyboardImageGetter {
class func keyboardImage(named: String) -> UIImage? {
let bundle = Bundle(for: self)
return UIImage.init(named: named, in: bundle, compatibleWith: nil)
}
}
| 25.396552 | 90 | 0.640869 |
9c8a1271d24ad904eaf853b995675639f4b5099d
| 1,820 |
// The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
struct SPDeviceOrientation {
static func isPortraitOrienation() -> Bool {
var isPortraitOrientation = true
if UIDevice.current.orientation.isValidInterfaceOrientation {
if UIDevice.current.orientation.isPortrait {
isPortraitOrientation = true
} else {
isPortraitOrientation = false
}
} else {
if UIScreen.main.bounds.width < UIScreen.main.bounds.height {
isPortraitOrientation = true
} else {
isPortraitOrientation = false
}
}
return isPortraitOrientation
}
}
| 41.363636 | 81 | 0.695055 |
11ec11adcac0d4e08a5ef5b8a9e4d823da69d430
| 2,452 |
//
// AppDelegate.swift
// TMPasscodeLockDemo
//
// Created by Travis Morgan on 1/16/17.
// Copyright © 2017 Travis Morgan. All rights reserved.
//
import UIKit
import TMPasscodeLock
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
if TMPasscodeLock.isPasscodeSet {
let passcodeLockViewController = TMPasscodeLockController(style: .basic, state: .enter)
passcodeLockViewController.presentIn(window: window!, animated: false)
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.264151 | 285 | 0.748369 |
3915928abe9e4da9cd67393b6ddf2326477589ec
| 1,112 |
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// the type of "library" is inferred to be [MediaItem]
// ------
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
print("Media library contains \(movieCount) movies and \(songCount) songs")
// Prints "Media library contains 2 movies and 3 songs"
| 23.166667 | 75 | 0.620504 |
6aed5087ee586910d5de47c68e9658cf0c9473b4
| 422 |
import Foundation
import KleinKit
public protocol AppActionAsync: ActionAsync where StateType == AppState {
}
final public class Store: StoreBase<AppState, EntryPointReducer> {
public static let shared: Store = {
let global = Store()
return global
}()
private init() {
super.init(initialState: AppState(), reducer: EntryPointReducer())
}
}
extension Store: ActionDispatcher { }
| 22.210526 | 74 | 0.691943 |
69ea6fda18223c3a6b0fcbf142823c9c6748d4ff
| 3,005 |
//: # カスタムデコード/カスタムデコード
//: [Codable の基本的な実装のサンプルへ](@previous)
import Foundation
let data1: Data = """
{
"user_name": "山田二郎",
"scores": [
{ "score": 65 },
{ "score": 24 }
]
}
""".data(using: .utf8)!
//: ---
// JSONに対応する構造体
struct Person: Codable {
let name: String
let scores: [Int]
// トップレベルの属性に対応するCodingKeys
enum CodingKeys: String, CodingKey {
case name = "user_name"
case scores
}
// ネストしたJSONの属性に対応するCodingKeys
enum ScoresCodingKeys: String, CodingKey {
case score
}
}
//: ---
// カスタムデコード用のイニシャライザを追加
extension Person {
init(from decoder: Decoder) throws {
// CodingKeysを指定し、JSON直下の属性("user_name"と"scores"にあたる部分)に対するコンテナを取得
let rootContainer = try decoder.container(keyedBy: CodingKeys.self)
// JSONのキー"user_name"にあたる部分の値を取得
let name = try rootContainer.decode(String.self, forKey: .name)
// ネストしたオブジェクト(キー"scores")の配列部分(配列なので中身の各要素にはキーがない)のコンテナを取得
var arrayContainer = try rootContainer.nestedUnkeyedContainer(forKey: .scores)
var scores: [Int] = []
// 配列の要素の最後になるまで繰り返し
while !arrayContainer.isAtEnd {
// ネストした部分のCodingKeys(ここではScoresCodingKeys)を指定し配列内のオブジェクト部分のコンテナを取得
let scoreContainer = try arrayContainer.nestedContainer(keyedBy: ScoresCodingKeys.self)
// JSONのキー"score"にあたる部分の値を取得
let score = try scoreContainer.decode(Int.self, forKey: .score)
// 取得した値を配列に追加
scores.append(score)
}
// 取得した値をメンバワイズイニシャライザに渡して初期化
self.init(name: name, scores: scores)
}
}
//: ---
// カスタムエンコード用のメソッドを追加
extension Person {
// カスタムでエンコードするためのメソッド
func encode(to encoder: Encoder) throws {
// CodingKeysを指定し、JSON直下の属性("user_name"と"scores"にあたる部分)に対するコンテナを取得
var container = encoder.container(keyedBy: CodingKeys.self)
// JSONのキー"name"にあたる部分をエンコード
try container.encode(self.name, forKey: .name)
// ネストしたオブジェクト(キー"scores")の配列部分(配列なので中身の各要素にはキーがない)のコンテナを取得
var scoresContainer = container.nestedUnkeyedContainer(forKey: .scores)
// scores配列をループし、各要素をエンコード
for score in scores {
// ネストした部分のCodingKeys(ここではScoresCodingKeys)を指定し配列内のオブジェクト部分のコンテナを取得
var arrayContainer = scoresContainer.nestedContainer(keyedBy: ScoresCodingKeys.self)
// JSONのキー"score"にあたる部分をエンコード
try arrayContainer.encode(score, forKey: .score)
}
}
}
//: ---
let decoder = JSONDecoder()
let yamada = try decoder.decode(Person.self, from: data1)
print(yamada.name)
yamada.scores.forEach { score in
print(score)
}
print("------------------------------")
//: ---
let kawada = Person(name: "川田吾郎", scores: [60, 80])
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data2 = try encoder.encode(kawada)
print(String(data: data2, encoding: .utf8)!)
| 29.174757 | 99 | 0.635275 |
0905fa269cff0150fe25256bc49f41ea37875fa5
| 1,138 |
//
// ViewController.swift
// SwiftTimerTutorial
//
// Created by Keri Clowes on 3/15/16.
// Copyright © 2016 Keri Clowes. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var countingLabel: UILabel!
@IBAction func startButton(sender: AnyObject) {
SwiftTimer = NSTimer.scheduledTimerWithTimeInterval(
1,
target:self,
selector: Selector("updateCounter"),
userInfo: nil,
repeats: true
)
}
@IBAction func pauseButton(sender: AnyObject) {
SwiftTimer.invalidate()
}
@IBAction func clearButton(sender: AnyObject) {
SwiftTimer.invalidate()
SwiftCounter = 0
countingLabel.text = String(SwiftCounter)
}
var SwiftTimer = NSTimer()
var SwiftCounter = 0
override func viewDidLoad() {
super.viewDidLoad()
countingLabel.text = String(SwiftCounter)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func updateCounter() {
countingLabel.text = String(SwiftCounter++)
}
}
| 21.471698 | 60 | 0.629174 |
ded9fed8020718b60388f64ab48a00279e101f5b
| 600 |
//
// ViewController+Options.swift
// SheeeeeeeeetExample
//
// Created by Daniel Saidi on 2019-02-10.
// Copyright © 2019 Daniel Saidi. All rights reserved.
//
import Foundation
import Sheeeeeeeeet
extension ViewController {
/**
Get the appearance option at a certain index, if any.
*/
func appearance(at indexPath: IndexPath) -> ActionSheetAppearance? {
switch menuOption(at: indexPath) {
case .openSheet, .separator: return nil
case .applyAppearance(.demo): return .demo
case .applyAppearance(.colors): return .colors
}
}
}
| 24 | 72 | 0.663333 |
87c8fafb3cb3a0da414bc7e67b33685dde3afdda
| 877 |
//
// Level36.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level36: Level {
let levelNumber = 36
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| 25.057143 | 89 | 0.573546 |
f5075f95f8cd0098fe58aae476f1cea2657340cd
| 679 |
//
// AppDelegate.swift
// MusicAlbum
//
// Created by Pedro Trujillo on 1/6/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}
| 24.25 | 179 | 0.75405 |
de2f106af53d7cfc1f7b3a9bd522ce3e84aa2921
| 1,130 |
//
// ContentView.swift
// LoadingViewExample
//
// Created by Juraj Macák on 03/12/2021.
//
import SwiftUI
import LoadingButton
struct ContentView: View {
@State private var name: String = ""
@State private var isLoading: Bool = false
@FocusState private var isFocus: Bool
private var style: LoadingButtonStyle {
return .init(width: 200, height: 40, cornerRadius: 20, backgroundColor: .blue, loadingColor: .blue, strokeWidth: 1, strokeColor: .white)
}
var body: some View {
VStack {
TextField("Enter your name", text: $name)
.textContentType(.name)
.focused($isFocus)
LoadingButton(action: {
isFocus = false
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {self.isLoading = false
}
}, isLoading: $isLoading, style: style) {
Text("Log in")
}
.foregroundColor(.white)
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 24.042553 | 144 | 0.578761 |
1c14aa7bc26dd75e309eb690beaa07209e9bedf5
| 503 |
//
// ViewController.swift
// PipeProcessor
//
// Created by Tulipa on 01/17/2017.
// Copyright (c) 2017 Tulipa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.12 | 80 | 0.66998 |
1460482de7a29b4d814a1ee308e6672ef74dd7a8
| 2,724 |
//
// MainViewController.swift
// AVCameraDemo
//
// Created by KuanWei on 2018/4/16.
// Copyright © 2018年 Kuan-Wei. All rights reserved.
//
import UIKit
import Photos
class MainViewController: UIViewController {
@IBOutlet weak var captureButton: UIButton!
@IBOutlet weak var capturePreviewView: UIView!
@IBOutlet weak var photoModeButton: UIButton!
@IBOutlet weak var toggleCameraButton: UIButton!
@IBOutlet weak var toggleFlashButton: UIButton!
@IBOutlet weak var videoModeButton: UIButton!
let cameraController = CameraController()
override var prefersStatusBarHidden: Bool { return true }
override func viewDidLoad() {
super.viewDidLoad()
func styleCaptureButton() {
captureButton.layer.borderColor = UIColor.black.cgColor
captureButton.layer.borderWidth = 2
captureButton.layer.cornerRadius = min(captureButton.frame.width, captureButton.frame.height) / 2
}
styleCaptureButton()
configureCameraController()
}
func configureCameraController() {
cameraController.prepare {(error) in
if let error = error {
print(error)
}
try? self.cameraController.displayPreview(on: self.capturePreviewView)
}
}
@IBAction func toggleFlash(_ sender: UIButton) {
if cameraController.flashMode == .on {
cameraController.flashMode = .off
toggleFlashButton.setImage(#imageLiteral(resourceName: "Flash Off Icon"), for: .normal)
}
else {
cameraController.flashMode = .on
toggleFlashButton.setImage(#imageLiteral(resourceName: "Flash On Icon"), for: .normal)
}
}
@IBAction func switchCameras(_ sender: UIButton) {
do {
try cameraController.switchCameras()
}
catch {
print(error)
}
switch cameraController.currentCameraPosition {
case .some(.front):
toggleCameraButton.setImage(#imageLiteral(resourceName: "Front Camera Icon"), for: .normal)
case .some(.rear):
toggleCameraButton.setImage(#imageLiteral(resourceName: "Rear Camera Icon"), for: .normal)
case .none:
return
}
}
@IBAction func captureImage(_ sender: UIButton) {
cameraController.captureImage {(image, error) in
guard let image = image else {
print(error ?? "Image capture error")
return
}
try? PHPhotoLibrary.shared().performChangesAndWait {
PHAssetChangeRequest.creationRequestForAsset(from: image)
}
}
}
}
| 26.705882 | 109 | 0.622247 |
5dc9105153702fb57b7f1a7c5a5af6df37a33fd3
| 313 |
//
// GetSkuConfig.swift
// Syte
//
// Created by Artur Tarasenko on 25.08.2021.
//
import Foundation
public class GetSkuConfig: Codable, ReflectedStringConvertible {
public var skuProvidersOrder: [String]?
public var shouldReportMissingSkus: Bool?
public var functionConfig: String?
}
| 18.411765 | 64 | 0.71246 |
7a7ddda0b97821e22a553cc2d0b1ad426607f224
| 1,777 |
/**
* (C) Copyright IBM Corp. 2020.
*
* 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
/**
An object describing the role played by a system entity that is specifies the beginning or end of a range recognized in
the user input. This property is included only if the new system entities are enabled for the skill.
*/
public struct RuntimeEntityRole: Codable, Equatable {
/**
The relationship of the entity to the range.
*/
public enum TypeEnum: String {
case dateFrom = "date_from"
case dateTo = "date_to"
case numberFrom = "number_from"
case numberTo = "number_to"
case timeFrom = "time_from"
case timeTo = "time_to"
}
/**
The relationship of the entity to the range.
*/
public var type: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case type = "type"
}
/**
Initialize a `RuntimeEntityRole` with member variables.
- parameter type: The relationship of the entity to the range.
- returns: An initialized `RuntimeEntityRole`.
*/
public init(
type: String? = nil
)
{
self.type = type
}
}
| 28.66129 | 120 | 0.670231 |
299f0ebd8911ea07af691c41c149ca057b273d66
| 1,662 |
import UIKit
// Arrays
let john = "John Lennon"
let paul = "Paul McCartney"
let george = "George Harrison"
let ringo = "Ringo Starr"
let beatles = [john, paul, george, ringo]
beatles[1]
// Sets
let colors = Set(["red", "green", "blue"])
let colors2 = Set(["red", "green", "blue", "red", "blue"])
// Tuples
var name = (first: "Taylor", last: "Swift")
name.0
name.first
// Arrays vs sets vs tuples
let address = (house: 555, street: "Taylor Swift Avenue", city: "Nashville")
let set = Set(["aardvark", "astronaut", "azalea"])
let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"]
// Dictionaries
let heights = [
"Taylor Swift": 1.78,
"Ed Sheeran": 1.73
]
heights["Taylor Swift"]
// Dictionary default values
let favoriteIceCream = [
"Paul": "Chocolate",
"Sophie": "Vanilla"
]
favoriteIceCream["Paul"]
favoriteIceCream["Charlotte"]
favoriteIceCream["Charlotte", default: "Unknown"]
// Creating empty collections
var teams = [String: String]()
teams["Paul"] = "Red"
var results = [Int]()
var words = Set<String>()
var numbers = Set<Int>()
var scores = Dictionary<String, Int>()
var results2 = Array<Int>()
// Enumerations
let result = "failure"
let result2 = "failed"
let result3 = "fail"
enum Result {
case success
case failure
}
let result4 = Result.failure
// Enum associated values
enum Activity {
case bored
case running(destination: String)
case talking(topic: String)
case singing(volume: Int)
}
let talking = Activity.talking(topic: "football")
// Enum raw values
enum Planet: Int {
case mercury = 1
case venus
case earth
case mars
}
let earth = Planet(rawValue: 2)
| 19.103448 | 76 | 0.663057 |
6a5764489536c75b2195217f83dfb39d3e950acf
| 1,025 |
// swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "keccak256",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "keccak256",
targets: ["keccak256"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "keccak256",
dependencies: []),
.testTarget(
name: "keccak256Tests",
dependencies: ["keccak256"]),
]
)
| 35.344828 | 122 | 0.620488 |
4a3a3fb5aa3f15b5359e46b124b8705b048890ea
| 501 |
//
// MRKeychainProviderError.swift
// MRFoundation
//
// Created by Roman Mogutnov on 24.02.2022.
// Copyright © 2022 Roman Mogutnov. All rights reserved.
//
import Foundation
public enum MRKeychainProviderErrorCode: Int, MRErrorCode {
case unknown = 0
case string2DataConversion = 1
case data2StringConversion = 2
}
public final class MRKeychainProviderError: MRError<MRKeychainProviderErrorCode> {
public override func domainShortName() -> String {
"MR_KP"
}
}
| 20.875 | 82 | 0.724551 |
8f5290eae7f7bf5bf8cacff78ea56c25b2308a9b
| 660 |
//
// PhotoViewModel.swift
// iOS_Labs
//
// Created by Daniil Oleshchuk on 02.12.2021.
//
import Foundation
class PhotosViewModel: ObservableObject {
@Published var photos = [PhotoModel]()
@Published var likedPhotos = [PhotoModel]()
func loadPhotos() {
PhotoManager.photos(action: {fetchedPhotos in
if let photos = fetchedPhotos {
self.photos = photos
} else {
self.photos = []
}
})
}
func loadLikedPhotos() {
if let likedPhotos = LikedPhotosService.shared.getAll() {
self.likedPhotos = likedPhotos
}
}
}
| 20.625 | 65 | 0.563636 |
483e80b0c18d9a0d023e631189613107ea4d010f
| 3,096 |
//
// AppDelegate.swift
// FileExplorerExampleApp
//
// Created by Rafal Augustyniak on 27/11/2016.
// Copyright (c) 2016 Rafal Augustyniak
//
// 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 FileExplorer
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let directoryURL = URL.documentDirectory
let audioURL = Bundle.main.url(forResource: "audio", withExtension: "mp3")!
let videoURL = Bundle.main.url(forResource: "video", withExtension: "mp4")!
let pdfURL = Bundle.main.url(forResource: "pdf", withExtension: "pdf")!
let image = UIImage(named: "image.jpg")!
let imageData = image.pngData()!
let firstDirectoryURL = directoryURL.appendingPathComponent("Directory")
try? FileManager.default.createDirectory(at: firstDirectoryURL, withIntermediateDirectories: true, attributes: [FileAttributeKey: Any]())
let items = [
(audioURL, "audio.mp3"),
(videoURL, "video.mp4"),
(pdfURL, "pdf.pdf")
]
for (url, filename) in items {
let destinationURL = firstDirectoryURL.appendingPathComponent(filename)
try? FileManager.default.copyItem(at: url, to: destinationURL)
}
let imageURL = firstDirectoryURL.appendingPathComponent("image.png")
try? imageData.write(to: imageURL)
let subdirectoryURL = firstDirectoryURL.appendingPathComponent("Empty Directory")
try? FileManager.default.createDirectory(at: subdirectoryURL, withIntermediateDirectories: true, attributes: [FileAttributeKey: Any]())
let secondDirectoryURL = directoryURL.appendingPathComponent("Empty Directory")
try? FileManager.default.createDirectory(at: secondDirectoryURL, withIntermediateDirectories: true, attributes: [FileAttributeKey: Any]())
return true
}
}
| 45.529412 | 146 | 0.722868 |
f5efa41fe240633f7ccd846a8a10c47e7c3a9278
| 1,383 |
//
// AuthenticationView.swift
// Oak
//
// Created by Alex Catchpole on 02/02/2021.
//
import Foundation
import SwiftUI
import Resolver
struct AuthenticationView: View {
@Environment(\.scenePhase) var scenePhase
@StateObject private var viewModel: AuthenticationViewModel = Resolver.resolve()
@Binding var activeSheet: RootView
var body: some View {
NavigationView {
List {
Section(header: Text("Enter your password to unlock oak")) {
SecureField("Password", text: $viewModel.password)
.accessibilityIdentifier("EnterPasswordSecureField")
}
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("Authentication")
.navigationBarItems(trailing: Button("Unlock", action: {
if viewModel.authenticatePassword() {
activeSheet = .accounts
}
}).accessibility(identifier: "UnlockButton"))
}
.alert(isPresented: $viewModel.authFailed) {
Alert(title: Text("Incorrect Password"), message: Text("Please double check your password and try again."), dismissButton: .cancel())
}
.onAppear {
viewModel.rootViewBinding = $activeSheet
viewModel.attemptBiometrics(for: scenePhase)
}
}
}
| 32.928571 | 145 | 0.600868 |
ac693ab7ee7d6a963cf29961ab05f5ad6627080d
| 889 |
//
// TextExportDocument.swift
// cos(x) Tab
//
// Created by Jeff Terry on 1/23/21.
//
// Based upon code from https://github.com/acwright/ImportExport
//
import Foundation
import SwiftUI
import UniformTypeIdentifiers
struct TextExportDocument: FileDocument {
static var readableContentTypes: [UTType] { [.plainText] }
var message: String
init(message: String) {
self.message = message
}
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let string = String(data: data, encoding: .utf8)
else {
throw CocoaError(.fileReadCorruptFile)
}
message = string
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
return FileWrapper(regularFileWithContents: message.data(using: .utf8)!)
}
}
| 23.394737 | 80 | 0.664792 |
bf6bfbd3c537e35b5de412e98968195dd9c146ef
| 2,283 |
//
// ConfigurationServiceTests.swift
// Data
//
// Created by Ryne Cheow on 17/4/17.
// Copyright © 2017 Pointwelve. All rights reserved.
//
@testable import Data
import Domain
import RxSwift
import XCTest
private enum ReadError: Error {
case fail
}
private class ReadConfigurationTestSuccessRepository: Readable {
typealias Value = Configuration
typealias Key = Void
func read() -> Observable<Configuration> {
return Observable.just(Configuration(apiHost: "test",
functionsHost: "www.func.com",
socketHost: "testhost",
sslCertificateData: Data(),
companyName: "testName",
apiKey: "apiKey",
termsAndConditions: "foobar"))
}
}
private class ReadConfigurationTestFailureRepository: Readable {
typealias Value = Configuration
typealias Key = Void
func read() -> Observable<Configuration> {
return Observable.error(ReadError.fail)
}
}
class ConfigurationUseCaseTests: XCTestCase {
func testReadConfigurationReturnsObject() {
let disposeBag = DisposeBag()
let repository = ReadConfigurationTestSuccessRepository()
let service = ReadConfigurationUseCaseType(repository: repository, schedulerExecutor: ImmediateSchedulerExecutor())
let expect = expectation(description: "executed")
service.read().subscribe(onNext: { _ in
expect.fulfill()
}).disposed(by: disposeBag)
waitForExpectations(timeout: 1) { error in
XCTAssertNil(error)
}
}
func testReadConfigurationResultsInError() {
let disposeBag = DisposeBag()
let repository = ReadConfigurationTestFailureRepository()
let service = ReadConfigurationUseCaseType(repository: repository, schedulerExecutor: ImmediateSchedulerExecutor())
let expect = expectation(description: "executed")
service.read().subscribe(onError: { _ in
expect.fulfill()
}).disposed(by: disposeBag)
waitForExpectations(timeout: 1) { error in
XCTAssertNil(error)
}
}
}
| 30.851351 | 121 | 0.621551 |
e24acf541305e5360382b9c871962acecf7134c2
| 5,280 |
//
// BusinessesViewController.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class BusinessesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, FiltersViewControllerDelegate, UISearchBarDelegate {
var searchBar: UISearchBar!
var businesses: [Business]!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
searchBar = UISearchBar()
searchBar.sizeToFit()
searchBar.delegate = self
navigationItem.titleView = searchBar
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
self.automaticallyAdjustsScrollViewInsets = false
navigationController?.navigationBar.barTintColor = UIColor.red
Business.searchWithTerm(term: "Thai", completion: { (businesses: [Business]?, error: Error?) -> Void in
self.businesses = businesses
self.tableView.reloadData()
if let businesses = businesses {
for business in businesses {
print(business.name!)
print(business.address!)
}
}
}
)
/* Example of Yelp search with more search options specified
Business.searchWithTerm("Restaurants", sort: .Distance, categories: ["asianfusion", "burgers"], deals: true) { (businesses: [Business]!, error: NSError!) -> Void in
self.businesses = businesses
for business in businesses {
print(business.name!)
print(business.address!)
}
}
*/
}
func showSearchBarCancelButton(show: Bool, searchBar : UISearchBar) {
searchBar.setShowsCancelButton(show, animated: true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("searching for " + searchText)
Business.searchWithTerm(term: searchText) { (businesses :[Business]?, error:Error?) in
self.businesses = businesses
self.tableView.reloadData()
}
// Business.searchWithTerm(term: searchText, sort: nil, categories: ni;;, deals: nil) { (businesses:[Business]?, error:Error?) in
// self.businesses = businesses
// self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if businesses != nil {
return businesses.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell
cell.business = businesses[indexPath.row]
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// let navigationController = segue.destination as? UINavigationController
// let filtersViewController = navigationController?.viewControllers[0] as! FiltersViewController
// filtersViewController.delegate = self;
// }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navigationController = segue.destination as? UINavigationController
let filtersViewController = navigationController?.viewControllers[0] as! FiltersViewController
filtersViewController.delegate = self;
}
func filtersViewController(filtersViewController: FiltersViewController, didUpdateFilters filters: [String : AnyObject]) {
//Business.searchWithTerm(term: "Restaurants", completion: <#T##([Business]?, Error?) -> Void#>)
let sortModes = [YelpSortMode.bestMatched, YelpSortMode.distance, YelpSortMode.highestRated]
let categories = filters["categories"] as? [String]
let deals = filters["deals"] as? Bool
let distance = filters["distance"] as? String
let sortString = filters["sort"] as? String
let sort = sortModes[Int(sortString!)!] as! YelpSortMode
Business.searchWithTerm(term: "restaurants", sort: sort, categories: categories, deals: deals) { (businesses:[Business]?, error:Error?) in
self.businesses = businesses
self.tableView.reloadData()
}
// Business.searchWithTerm(term: "Restaurents", sort: nil, categories: categories, deals: nil) { (businesses: [Business]!, error:Error!) in
// self.businesses = businesses
// self.tableView.reloadData()
// }
}
}
| 36.164384 | 173 | 0.624621 |
7558364a378d7798ae10d4d09960be9894227841
| 595 |
//
// Timing.swift
// StatsdClient
//
// Created by Khoi Lai on 10/7/17.
// Copyright © 2017 StatsdClient. All rights reserved.
//
import Foundation
public struct Timing: Metric, Codable {
let name: String
let value: Int
let sample: Float?
public init(name: String, value: Int, sample: Float? = nil) {
self.name = name
self.value = value
self.sample = sample
}
public var metricData: String {
if let sample = sample {
return "\(name):\(value)|ms|@\(sample.clean)"
}
return "\(name):\(value)|ms"
}
}
| 20.517241 | 65 | 0.578151 |
f9c63a5fbd8f97d737fb2d8e05397ad577282818
| 2,234 |
import UIKit
public class UAFlowView: UIControl {
@IBInspectable public var interitemSpacing: CGFloat = 8 { didSet { setNeedsLayout() }}
@IBInspectable public var lineSpacing: CGFloat = 8 { didSet { setNeedsLayout() }}
@IBInspectable public var alignment: NSTextAlignment = .left { didSet { setNeedsLayout() }}
public override var intrinsicContentSize: CGSize { get {
if let lastSubView = self.subviews.last {
return CGSize(width: bounds.size.width, height: lastSubView.frame.maxY)
} else {
return CGSize(width: bounds.size.width, height: 44)
}
}}
public override func layoutSubviews() {
var lines: [[UIView]] = [[]]
var lastOrigin: CGPoint = .zero
subviews.forEach { subview in
subview.transform = .identity
let intrinsicContentSize = subview.intrinsicContentSize
let availableWidth = (self.frame.maxX - self.frame.minX)
let size = CGSize(width: min(intrinsicContentSize.width, availableWidth),
height: intrinsicContentSize.height)
var frame = CGRect(origin: lastOrigin, size: size)
if frame.maxX > bounds.size.width {
lastOrigin = CGPoint(x: 0, y: lines.last!.enclosingRect.maxY + lineSpacing)
frame = CGRect(origin: lastOrigin, size: size)
lines.append([])
}
var last = lines.removeLast()
last.append(subview)
lines.append(last)
subview.frame = frame
lastOrigin = CGPoint(x: frame.maxX + interitemSpacing, y: frame.minY)
}
if alignment == .right || alignment == .center {
lines.forEach { line in
let enclosing = line.enclosingRect
let Δ = (bounds.width - enclosing.width) / (alignment == .center ? 2 : 1)
line.forEach({ view in
view.transform = CGAffineTransform(translationX: Δ, y: 0)
})
}
}
self.invalidateIntrinsicContentSize()
}
}
| 37.233333 | 95 | 0.551477 |
1182f0cc5acb7d2a30fac07b7b6fd7bc1ae6391d
| 795 |
//
// Instaceable.swift
// SwiftConceptMVP
//
// Created by Thiago Magalhães on 27/11/2017.
// Copyright © 2017 Thiago Magalhães. All rights reserved.
//
import UIKit
protocol Instanceable {
static var storyboardName: String { get }
static var viewControllerIdentifier: String { get }
func preparePresenter()
}
extension Instanceable where Self : PresentableViewController {
static func createInstance() throws -> Self {
let identifier = viewControllerIdentifier
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
guard let view = storyboard.instantiateViewController(withIdentifier: identifier) as? Self else {
throw ViewControllerTypeNotMatching()
}
view.preparePresenter()
return view
}
}
| 26.5 | 105 | 0.701887 |
0199dea51ec5bbdfa698830e5676fc9f71d53653
| 846 |
//
// Copyright 2021 New Vector Ltd
//
// 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
class LocationOutgoingWithPaginationTitleBubbleCell: LocationOutgoingWithoutSenderInfoBubbleCell {
override func setupViews() {
super.setupViews()
roomCellContentView?.showPaginationTitle = true
}
}
| 32.538462 | 98 | 0.743499 |
2feb644a0ca5a958049c2ae595a3e228af12e28c
| 2,743 |
//
// Date+custom.swift
// My Pass UAE
//
// Created by Pantera Engineering on 25/01/2017.
// Copyright © 2017 Incubasys IT Solutions. All rights reserved.
//
import Foundation
import UIKit
public extension Date{
public static func date(fromString dateString: String, format: String = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone(identifier: "UTC")
guard let date = dateFormatter.date(from: dateString) else {
return nil
}
return date
}
public func string(format:String="yyyy-MM-dd'T'HH:mm:ss.SSSZ") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale.init(identifier: "en_GB")
return dateFormatter.string(from: self)
}
public func offsetFrom(date: Date) -> String {
let unitFlags:Set<Calendar.Component> = [.year,.month ,.day, .hour, .minute, .second]
let difference = Calendar.current.dateComponents(unitFlags, from: self,to:date)
let minutes = "\(difference.minute!)m" + " "
let hours = "\(difference.hour!)h" + " " + minutes
let days = "\(difference.day!)d" + " " + hours
let month = "\(difference.month!)M" + " " + days
if difference.month! > 0 { return month}
if difference.day! > 0 { return days }
if difference.hour! > 0 { return hours }
if difference.minute! > 0 { return minutes }
return ""
}
public func offsetBy(unit: Calendar.Component, fromDate:Date) -> Int{
let unitFlags:Set<Calendar.Component> = [unit]
let difference = Calendar.current.dateComponents(unitFlags, from: fromDate, to: self)
var result:Int!
switch unit {
case .year:
result = difference.year ?? 0
case .month:
result = difference.month ?? 0
case .day:
result = difference.day ?? 0
case .hour:
result = difference.hour ?? 0
case .minute:
result = difference.minute ?? 0
case .second:
result = difference.second ?? 0
case .nanosecond:
result = difference.second ?? 0
default:
result = 0
}
return result
}
var utcValue: String {
let dateFormater = DateFormatter()
dateFormater.calendar = Calendar.current
dateFormater.timeZone = TimeZone(abbreviation: "UTC")
let currentTimeString = dateFormater.string(from: self)
return currentTimeString
}
static public var timeStamp: String {
let date = Date().timeIntervalSince1970
return "\(date)"
}
}
| 31.170455 | 116 | 0.609916 |
5606ff1951b52ea7ac1023039dc96091f101ceae
| 756 |
//
// TransactionCategory.swift
// personal-planner
//
// Created by Calvin De Aquino on 2020-02-21.
// Copyright © 2020 Calvin Aquino. All rights reserved.
//
import CoreData
import Foundation
class TransactionCategory : NSManagedObject, Identifiable {
@NSManaged var name: String
@NSManaged var budget: Double
@NSManaged var transactionItems: [TransactionItem]?
convenience init() {
self.init(context: Store.context)
}
static func allFetchRequest() -> NSFetchRequest<TransactionCategory> {
let request : NSFetchRequest<TransactionCategory> = TransactionCategory.fetchRequest() as! NSFetchRequest<TransactionCategory>
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
return request
}
}
| 27 | 130 | 0.746032 |
d5ada19887fb7caab145fd5bc97acb8e4da33381
| 2,450 |
//
// KeyboardObserver.swift
// TweetleDumb
//
// Created by Ian Keen on 2017-06-14.
// Copyright © 2017 Mustard. All rights reserved.
//
import UIKit
final class KeyboardObserver {
// MARK: - Private Properties
private let container: UIView
private var observers: [Any] = []
private let originalHeight: CGFloat
init(container: UIView) {
self.container = container
originalHeight = container.frame.height
}
deinit { stop() }
// MARK: - Public Functions
func start() {
let notifications: [Notification.Name] = [UIResponder.keyboardWillShowNotification, UIResponder.keyboardWillHideNotification]
observers = notifications.map(subscribe(to:))
}
func stop() {
observers.forEach(NotificationCenter.default.removeObserver)
}
// MARK: - Private Functions
private func subscribe(to notification: Notification.Name) -> Any {
return NotificationCenter.default.addObserver(forName: notification, object: nil, queue: .main) { [weak self] obj in
guard let this = self else { return }
let offset = this.offset(from: obj)
let duration = this.duration(from: obj)
UIView.animate(withDuration: duration, delay: 0.0, options: .layoutSubviews, animations: {
this.container.frame = CGRect(
x: this.container.frame.origin.x,
y: this.container.frame.origin.y,
width: this.container.frame.size.width,
height: (notification == UIResponder.keyboardWillHideNotification) ? this.originalHeight : this.container.frame.size.height + offset
)
})
}
}
private func offset(from notification: Notification) -> CGFloat {
guard
let userInfo = notification.userInfo,
let begin = userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue,
let end = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
else { return .leastNormalMagnitude }
return end.cgRectValue.minY - begin.cgRectValue.minY
}
private func duration(from notification: Notification) -> TimeInterval {
guard
let userInfo = notification.userInfo,
let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval
else { return 0 }
return duration
}
}
| 36.029412 | 152 | 0.643265 |
67f2ea5325f124fcfe835b701f58c5182a5fce15
| 206 |
final class AppCoordinator: Coordinator {
weak var navigator: NavigatorProtocol?
init(navigator: NavigatorProtocol?) {
self.navigator = navigator
}
func start() {
}
}
| 17.166667 | 42 | 0.626214 |
8a213238196e9613eb34d934f7020c451dcc987a
| 1,305 |
//
// HashFunction.swift
// CryptoKit
//
// Created by Chris Amanse on 06/09/2016.
//
//
import Foundation
/// A `HashFunction` contains a `HashAlgorithm.Type`, which is then used for calculating the hash of a message.
public struct HashFunction {
/// The type of hash alorithm to use for calculating the hash of a message.
public var algorithm: HashAlgorithm.Type
/// Calculates the hash/digest of a message.
/// - parameters:
/// - message: The message to be hashed.
/// - returns: The hash of a message.
public func digest(_ message: Data) -> Data {
return algorithm.digest(message)
}
/// Creates a hash function with an algorithm specified by the `HashAlgorithm.Type`
/// - parameters:
/// - algorithm: The algorithm to be used for calculating the hash of a message.
public init(_ algorithm: HashAlgorithm.Type) {
self.algorithm = algorithm
}
}
extension HashFunction: Equatable {
public static func ==(lhs: HashFunction, rhs: HashFunction) -> Bool {
return lhs.algorithm == rhs.algorithm
}
}
public extension HashAlgorithm {
/// Creates a hash function instance using `self` as its hash algorithm.
public static var hashFunction: HashFunction {
return HashFunction(self)
}
}
| 29.659091 | 111 | 0.671264 |
677fba5c3ec4627d1aca0759a39323a13ed8f5bf
| 551 |
// Generated using Sourcery 0.13.1 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import Foundation
extension CardServiceResponse.Loyalty.LoyaltyApprovalCode {
func toXML(_ name: String, encoder: XMLEncoderProtocol) -> XMLElement {
let xml = XMLElement(name: name)
xml.valueString = encoder.encodeValue(value)
xml.attributes["LoyaltyAcquirerID"] = encoder.encodeValue(loyaltyAcquirerID)
xml.attributes["LoyaltyAcquirerBatch"] = encoder.encodeValue(loyaltyAcquirerBatch)
return xml
}
}
| 36.733333 | 90 | 0.735027 |
dbf6451fc261694b9be05d5c1ec9f29a67ae3bf3
| 9,950 |
//
// LFScreenAdaptor.swift
// SwiftData
//
// Created by LeonDeng on 2019/9/2.
// Copyright © 2019 tcl. All rights reserved.
//
import UIKit
enum ScreenType {
case Unknown /// DeviceScreenTypeUnknown: Unknown screenType, maybe a new iPhone or simulator
case Type3_5 /// DeviceScreenType3_5: 1, 3G, 3Gs, 4, 4s
case Type4_0 /// DeviceScreenType4_0: 5, 5s, 5c, se, iPod Touch 5, iPod Touch 6
case Type4_7 /// DeviceScreenType4_7: 6, 6s, 7, 8
case Type5_5 /// DeviceScreenType5_5: 6Plus, 6sPlus, 7Plus, 8Plus
case Type5_8 /// DeviceScreenType5_8: X, Xs
case Type6_1 /// DeviceScreenType6_1: XR
case Type6_5 /// DeviceScreenType6_5: Xs Max
case Type9_7 /// DeviceScreenType9_7: iPad Pro, iPad Air, iPad Air 2, iPad 4, iPad 3
case Type10_5 /// DeviceScreenType10_5: iPad Pro
case Type11 /// DeviceScreenType11: iPad Pro
case Type12_9 /// DeviceScreenType12_9: iPad Pro
}
extension ScreenType {
var statusBarHeight: CGFloat {
switch self {
case .Type5_8, .Type6_1, .Type6_5:
return 44
default:
return 20
}
}
var navigationBarHeight: CGFloat {
switch self {
case .Type5_8, .Type6_1, .Type6_5:
return 88
default:
return 64
}
}
var buttonIndicatorHeight: CGFloat {
switch self {
case .Type5_8, .Type6_1, .Type6_5:
return 34
default:
return 0
}
}
var screenWidth: CGFloat {
switch self {
case .Type3_5:
return 320
case .Type4_0:
return 320
case .Type4_7:
return 375
case .Type5_5:
return 414
case .Type5_8:
return 375
case .Type6_5, .Type6_1:
return 414
default:
return 0
}
}
var screenHeight: CGFloat {
switch self {
case .Type3_5:
return 480
case .Type4_0:
return 568
case .Type4_7:
return 667
case .Type5_5:
return 736
case .Type5_8:
return 812
case .Type6_5, .Type6_1:
return 896
default:
return 0
}
}
}
enum DeviceType: Int {
case Unknown = 0 /// Unknown: unknown type, maybe new iphone or simulator
case Simulator = 1 /// Simulator: simulator, not supported for most functions of this frameWork
case IPhone_1G = 2 /// IPhone_1G: Not supported
case IPhone_3G = 3 /// IPhone_3G: Not supported
case IPhone_3GS = 4 /// IPhone_3GS: Not supported
case IPhone_4 = 5 /// IPhone_4: supported
case IPhone_4S = 6 /// IPhone_4S: supported
case IPhone_5 = 7 /// IPhone_5: supported
case IPhone_5C = 8 /// IPhone_5C: supported
case IPhone_5S = 9 /// IPhone_5S: supported
case IPhone_SE = 10 /// IPhone_SE: supported
case IPhone_6 = 11 /// IPhone_6: supported
case IPhone_6P = 12 /// IPhone_6P: supported
case IPhone_6S = 13 /// IPhone_6S: supported
case IPhone_6S_P = 14 /// IPhone_6S_P: supported
case IPhone_7 = 15 /// IPhone_7: supported
case IPhone_7P = 16 /// IPhone_7P: supported
case IPhone_8 = 17 /// IPhone_8: supported
case IPhone_8P = 18 /// IPhone_8P: supported
case IPhone_X = 19 /// IPhone_X: supported
case IPhone_XS = 20 /// IPhone_XS: supported
case IPhone_XSMax = 21 /// IPhone_XSMax: supported
case IPhone_XR = 22 /// IPhone_XR: supported
}
extension DeviceType {
var screenType: ScreenType {
switch self {
case .Unknown:
return .Unknown
case .IPhone_1G, .IPhone_3G, .IPhone_3GS:
return .Type3_5
case .IPhone_4, .IPhone_4S:
return .Type3_5
case .IPhone_5, .IPhone_5C, .IPhone_5S, .IPhone_SE:
return .Type4_0
case .IPhone_6, .IPhone_6S, .IPhone_7, .IPhone_8:
return .Type4_7
case .IPhone_6P, .IPhone_7P, .IPhone_8P:
return .Type5_5
case .IPhone_X, .IPhone_XS:
return .Type5_8
case .IPhone_XR:
return .Type6_1
case .IPhone_XSMax:
return .Type6_5
default:
return .Unknown
}
}
var name: String {
switch self {
case .Unknown:
return "Unknown"
case .IPhone_1G:
return "iPhone_1G"
case .IPhone_3G:
return "iPhone_3G"
case .IPhone_3GS:
return "iPhone_3GS"
case .IPhone_4:
return "iPhone_4"
case .IPhone_4S:
return "iPhone_4S"
case .IPhone_5:
return "iPhone_5"
case .IPhone_5C:
return "iPhone_5C"
case .IPhone_5S:
return "iPhone_5S"
case .IPhone_6:
return "iPhone_6"
case .IPhone_6P:
return "iPhone_6Plus"
case .IPhone_6S:
return "iPhone_6S"
case .IPhone_6S_P:
return "iPhone_6SPlus"
case .IPhone_7:
return "iPHone_7"
case .IPhone_7P:
return "iPhone_7Plus"
case .IPhone_8:
return "iPhone_8"
case .IPhone_8P:
return "iPhone_8Plus"
case .IPhone_X:
return "iPhone_X"
case .IPhone_XS:
return "iPhone_XS"
case .IPhone_XSMax:
return "iPhone_XSMax"
case .IPhone_XR:
return "iPhone_XR"
default:
return "Unknown"
}
}
}
class LFScreenAdaptor {
static let sharedAdaptor: LFScreenAdaptor = LFScreenAdaptor(designScreenType: DeviceType.IPhone_6.screenType)
var designScreen: ScreenType
let currentDevice: DeviceType = {
var systemInfo: utsname = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
// let identifier = machineMirror.children.reduce("") { identifier, elementin
//
// guardletvalue = element.valueas?Int8wherevalue !=0else{returnidentifier }
//
// returnidentifier +String(UnicodeScalar(UInt8(value)))
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
// if ([platform isEqualToString:@"iPhone1,1"]) return IPhone_1G;
// if ([platform isEqualToString:@"iPhone1,2"]) return IPhone_3G;
// if ([platform isEqualToString:@"iPhone2,1"]) return IPhone_3GS;
case "iPhone1,1": return .IPhone_1G
case "iPhone1,2": return .IPhone_3G
case "iPhone2,1": return .IPhone_3GS
case "iPhone3,1": return .IPhone_4
case "iPhone4,1": return .IPhone_4S
case "iPhone5,1", "iPhone5,2": return .IPhone_5
case "iPhone5,3", "iPhone5,4": return .IPhone_5C
case "iPhone6,1", "iPhone6,2": return .IPhone_5S
case "iPhone7,2": return .IPhone_6
case "iPhone7,1": return .IPhone_6P
case "iPhone8,1": return .IPhone_6S
case "iPhone8,2": return .IPhone_6S_P
case "iPhone8,4": return .IPhone_SE
case "iPhone9,1": return .IPhone_7
case "iPhone9,2": return .IPhone_7P
// case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
// case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
// case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
// case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
// case "iPad5,3", "iPad5,4": return "iPad Air 2"
// case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
// case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
// case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
// case "iPad5,1", "iPad5,2": return "iPad Mini 4"
// case "iPad6,7", "iPad6,8": return "iPad Pro"
// case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return .Simulator
default: return .Unknown
}
}()
var currentScreen: ScreenType {
return self.currentDevice.screenType
}
public func adaptedHeight(height: CGFloat) -> CGFloat {
let deviceHeight = self.currentScreen.screenHeight
let standardHeight = self.designScreen.screenHeight
return standardHeight * (deviceHeight / standardHeight)
}
public func adaptedWidth(width: CGFloat) -> CGFloat {
let deviceWidth = self.currentScreen.screenWidth
let standardWidth = self.designScreen.screenWidth
return standardWidth * (deviceWidth / standardWidth)
}
init(designScreenType: ScreenType) {
designScreen = designScreenType
}
}
| 32.94702 | 113 | 0.523618 |
293e4e1e7676745ee87e8d6a2153d09bc4af15cf
| 452 |
//
// DateFormatter+Utils.swift
// DribbbleAPI
//
// Created by Eduard Panasiuk on 9/5/16.
// Copyright © 2016 somedev. All rights reserved.
//
import Foundation
extension DateFormatter {
@nonobjc public static var dbFormatter: DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
| 23.789474 | 61 | 0.674779 |
566fbb3382bc292f8dc8ba8b8959c96b7a1068da
| 1,218 |
//
// 31NextPermutation.swift
// Algorithm
//
// Created by vchan on 2021/1/20.
// Copyright © 2021 vhuichen. All rights reserved.
//
import Foundation
extension Solution {
func nextPermutation(_ nums: inout [Int]) {
var left = nums.count - 1
var right = left
while left > 0 && nums[left - 1] >= nums[left] {
left -= 1
}
if left > 0 {
let exchangeIndex = left - 1
let exchangeValue = nums[exchangeIndex]
//二分查找
var tempLeft = left
var tempRight = right
while tempLeft < tempRight {
let middle = (tempRight + tempLeft + 1) / 2
if (exchangeValue < nums[middle]) {
tempLeft = middle
} else {
tempRight = middle - 1
}
}
nums[exchangeIndex] = nums[tempRight]
nums[tempRight] = exchangeValue
}
while left < right {
let temp = nums[left]
nums[left] = nums[right]
nums[right] = temp
left += 1
right -= 1
}
}
}
| 24.36 | 59 | 0.45156 |
b9cef1a1122e666b723339d59437dc3523d3e892
| 1,540 |
//
// ContentView.swift
// BCard
//
// Created by Kostadin Samardzhiev on 30.12.21.
//
import SwiftUI
import CoreData
struct ContentView: View {
init(){
for family in UIFont.familyNames.sorted() {
let names = UIFont.fontNames(forFamilyName: family)
print("Family: \(family) Font names: \(names)")
}
}
var body: some View {
ZStack {
Color(red: 0.29, green: 0.48, blue: 0.93)
.edgesIgnoringSafeArea(.all)
VStack {
Image("ksamardzhiev")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 150.0, height: 150.0)
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 5))
Text("Kostadin Samardzhiev")
.font(Font.custom("Lobster-Regular", size: 40))
.bold()
.foregroundColor(.white)
Text("iOS Developer")
.font(.system(size: 25))
.foregroundColor(.white)
Divider()
InfoView(text: "+359 123 456 7", imageName: "phone.fill", imageColor: .green)
InfoView(text: "[email protected]", imageName: "envelope.fill", imageColor: .blue)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 29.056604 | 104 | 0.494156 |
fb6f1e340a0360210dff1f3edd73e0535638bd4c
| 5,320 |
//
// PlistValue.swift
// SwiftyLibPlist
//
// Created by Kazuki Yamamoto on 2019/11/30.
// Copyright © 2019 Kazuki Yamamoto. All rights reserved.
//
import Foundation
import libplist
public extension Plist {
init(string: String) {
self.rawValue = plist_new_string(string)
}
init(bool: Bool) {
self.rawValue = plist_new_bool(bool ? 1 : 0)
}
init(uint: UInt64) {
self.rawValue = plist_new_uint(uint)
}
init(uid: UInt64) {
self.rawValue = plist_new_uid(uid)
}
init(real: Double) {
self.rawValue = plist_new_real(real)
}
init(data: Data) {
let count = data.count
self.rawValue = data.withUnsafeBytes { (data) -> plist_t? in
let value = data.baseAddress?.assumingMemoryBound(to: Int8.self)
return plist_new_data(value, UInt64(count))
}
}
init(date: Date) {
let timeInterval = date.timeIntervalSinceReferenceDate
var sec = 0.0
let usec = modf(timeInterval, &sec)
self.rawValue = plist_new_date(Int32(sec), Int32(round(usec * 1000000)))
}
var key: String? {
get {
guard nodeType == .key else {
return nil
}
var pkey: UnsafeMutablePointer<Int8>? = nil
plist_get_key_val(rawValue, &pkey)
guard let key = pkey else {
return nil
}
defer { key.deallocate() }
return String(cString: key)
}
set {
guard let key = newValue else {
return
}
plist_set_key_val(rawValue, key)
}
}
var string: String? {
get {
guard nodeType == .string else {
return nil
}
var pkey: UnsafeMutablePointer<Int8>? = nil
plist_get_string_val(rawValue, &pkey)
guard let key = pkey else {
return nil
}
defer { key.deallocate() }
return String(cString: key)
}
set {
guard let string = newValue else {
return
}
plist_set_string_val(rawValue, string)
}
}
var bool: Bool? {
get {
guard nodeType == .boolean else {
return nil
}
var bool: UInt8 = 0
plist_get_bool_val(rawValue, &bool)
return bool > 0
}
set {
guard let bool = newValue else {
return
}
plist_set_bool_val(rawValue, bool ? 1 : 0)
}
}
var real: Double? {
get {
guard nodeType == .real else {
return nil
}
var double: Double = 0
plist_get_real_val(rawValue, &double)
return double
}
set {
guard let real = newValue else {
return
}
plist_set_real_val(rawValue, real)
}
}
var data: Data? {
get {
guard nodeType == .data else {
return nil
}
var pvalue: UnsafeMutablePointer<Int8>? = nil
var length: UInt64 = 0
plist_get_data_val(rawValue, &pvalue, &length)
guard let value = pvalue else {
return nil
}
defer { value.deallocate() }
return Data(bytes: UnsafeRawPointer(value), count: Int(length))
}
set {
newValue?.withUnsafeBytes { (data: UnsafeRawBufferPointer) -> Void in
plist_set_data_val(rawValue, data.bindMemory(to: Int8.self).baseAddress, UInt64(data.count))
}
}
}
var date: Date? {
get {
guard nodeType == .date else {
return nil
}
var sec: Int32 = 0
var usec: Int32 = 0
plist_get_date_val(rawValue, &sec, &usec)
return Date(timeIntervalSinceReferenceDate: Double(sec) + Double(usec) / 1000000)
}
set {
guard nodeType == .date, let date = newValue?.timeIntervalSinceReferenceDate else {
return
}
var sec: Double = 0
let usec = modf(date, &sec)
plist_set_date_val(rawValue, Int32(sec), Int32(usec * 1000000))
}
}
var uid: UInt64? {
get {
guard nodeType == .uid else {
return nil
}
var uid: UInt64 = 0
plist_get_uid_val(rawValue, &uid)
return uid
}
set {
guard let uid = newValue else {
return
}
plist_set_uid_val(rawValue, uid)
}
}
var uint: UInt64? {
get {
guard nodeType == .uint else {
return nil
}
var uint: UInt64 = 0
plist_get_uint_val(rawValue, &uint)
return uint
}
set {
guard let uint = newValue else {
return
}
plist_set_uint_val(rawValue, uint)
}
}
}
| 26.078431 | 108 | 0.474436 |
8acef412c8395c468729a4c2bf3f2b0d6362cc4f
| 992 |
//
// EventAnalyticsFacade.swift
// AmazonChimeSDK
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
/// `EventAnalyticsFacade` exposes event analytics related function to builders
@objc public protocol EventAnalyticsFacade {
/// Subscribes to meeting event related data with an observer
/// - Parameter observer: An observer to add to start receiving meeting events
func addEventAnalyticsObserver(observer: EventAnalyticsObserver)
/// Unsubscribes from meeting event by removing the specified observer
/// - Parameter observer: An observer to remove to stop receiving meeting events
func removeEventAnalyticsObserver(observer: EventAnalyticsObserver)
/// Retrieve meeting history.
func getMeetingHistory() -> [MeetingHistoryEvent]
/// Retrieve common attributes, including deviceName, osName, and more.
func getCommonEventAttributes() -> [AnyHashable: Any]
}
| 36.740741 | 84 | 0.759073 |
0ece109b8df637a37893295bfb87bb04fdd36d4e
| 745 |
//
// CurrencyManager.swift
// CurrencyManager
//
// Created by Jon Manning on 4/02/2015.
// Copyright (c) 2015 Secret Lab. All rights reserved.
//
import UIKit
// BEGIN currency
class CurrencyManager {
var gold : Int = 0
var gems : Int {
set(value) {
// Set the updated count of gems in the user defaults system
UserDefaults.standard.set(value, forKey: "gems")
}
get {
// Ask the user defaults system for the current number of gems
return UserDefaults.standard.integer(forKey: "gems")
}
}
func endGame() {
// When the game is over, reset gold but leave gems alone
gold = 0
}
}
// END currency
| 20.694444 | 74 | 0.571812 |
4be22ced796685a8e0b8df56d8cc7c858de7dd4a
| 610 |
//
// InitialInteractor.swift
// Parcel
//
// Created by Skibin Alexander on 04/11/2020.
// Copyright © 2020 ParcelApp. All rights reserved.
//
import Foundation
final class InitialInteractor: InitialInteractorProtocol {
// MARK: - Public Properties
weak var presenter: InitialPresenterFromInteractorProtocol!
var service: ExampleServiceProtocol!
// MARK: - Interactor Implementation
func initialization() {
presenter.didLoad(
namesString:
service
.fetchExample()
.joined(separator: " ")
)
}
}
| 21.034483 | 60 | 0.62623 |
cc9b4e733ddcfa59756d2a46e15ac799c99d421d
| 10,448 |
//
// PollingAwaitComponentTests.swift
// AdyenTests
//
// Created by Mohamed Eldoheiri on 8/12/20.
// Copyright © 2020 Adyen. All rights reserved.
//
@testable import Adyen
@testable import AdyenActions
import XCTest
class PollingAwaitComponentTests: XCTestCase {
func testRetryWhenResultIsReceived() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
delegate.onDidFail = { _, _ in
XCTFail()
}
let onDidProvideExpectation = expectation(description: "ActionComponentDelegate.didProvide must be called.")
delegate.onDidProvide = { data, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(data.paymentData, "data")
XCTAssertNotNil(data.details as? AwaitActionDetails)
let details = data.details as! AwaitActionDetails
XCTAssertEqual(details.payload, "pay load")
onDidProvideExpectation.fulfill()
}
sut.delegate = delegate
let result = MockedResult.success(PaymentStatusResponse(payload: "pay load", resultCode: .received))
apiClient.mockedResults = [result, result, result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 3)
}
func testRetryWhenResultIsPending() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
delegate.onDidFail = { _, _ in
XCTFail()
}
let onDidProvideExpectation = expectation(description: "ActionComponentDelegate.didProvide must be called.")
onDidProvideExpectation.assertForOverFulfill = true
delegate.onDidProvide = { data, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(data.paymentData, "data")
XCTAssertNotNil(data.details as? AwaitActionDetails)
let details = data.details as! AwaitActionDetails
XCTAssertEqual(details.payload, "pay load")
onDidProvideExpectation.fulfill()
}
sut.delegate = delegate
let result = MockedResult.success(PaymentStatusResponse(payload: "pay load", resultCode: .pending))
apiClient.mockedResults = [result, result, result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 3)
}
func testNotRetryWhenRequestFails() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
let onDidFailExpectation = expectation(description: "ActionComponentDelegate.didFail must be called.")
delegate.onDidFail = { error, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(error as? Dummy, Dummy.dummyError)
onDidFailExpectation.fulfill()
}
delegate.onDidProvide = { _, _ in
XCTFail()
}
sut.delegate = delegate
let result = MockedResult.failure(Dummy.dummyError)
apiClient.mockedResults = [result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 1)
}
func testNotRetryWhenResultIsRefused() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
delegate.onDidFail = { _, _ in
XCTFail()
}
let onDidProvideExpectation = expectation(description: "ActionComponentDelegate.didProvide must be called.")
onDidProvideExpectation.assertForOverFulfill = true
delegate.onDidProvide = { data, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(data.paymentData, "data")
XCTAssertNotNil(data.details as? AwaitActionDetails)
let details = data.details as! AwaitActionDetails
XCTAssertEqual(details.payload, "pay load")
onDidProvideExpectation.fulfill()
}
sut.delegate = delegate
let result = MockedResult.success(PaymentStatusResponse(payload: "pay load", resultCode: .refused))
apiClient.mockedResults = [result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 1)
}
func testNotRetryWhenResultIsCancelled() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
delegate.onDidFail = { _, _ in
XCTFail()
}
let onDidProvideExpectation = expectation(description: "ActionComponentDelegate.didProvide must be called.")
onDidProvideExpectation.assertForOverFulfill = true
delegate.onDidProvide = { data, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(data.paymentData, "data")
XCTAssertNotNil(data.details as? AwaitActionDetails)
let details = data.details as! AwaitActionDetails
XCTAssertEqual(details.payload, "pay load")
onDidProvideExpectation.fulfill()
}
sut.delegate = delegate
let result = MockedResult.success(PaymentStatusResponse(payload: "pay load", resultCode: .cancelled))
apiClient.mockedResults = [result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 1)
}
func testNotRetryWhenResultIsError() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
delegate.onDidFail = { _, _ in
XCTFail()
}
let onDidProvideExpectation = expectation(description: "ActionComponentDelegate.didProvide must be called.")
onDidProvideExpectation.assertForOverFulfill = true
delegate.onDidProvide = { data, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(data.paymentData, "data")
XCTAssertNotNil(data.details as? AwaitActionDetails)
let details = data.details as! AwaitActionDetails
XCTAssertEqual(details.payload, "pay load")
onDidProvideExpectation.fulfill()
}
sut.delegate = delegate
let result = MockedResult.success(PaymentStatusResponse(payload: "pay load", resultCode: .error))
apiClient.mockedResults = [result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 1)
}
func testNotRetryWhenResultIsAuthorized() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
delegate.onDidFail = { _, _ in
XCTFail()
}
let onDidProvideExpectation = expectation(description: "ActionComponentDelegate.didProvide must be called.")
onDidProvideExpectation.assertForOverFulfill = true
delegate.onDidProvide = { data, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(data.paymentData, "data")
XCTAssertNotNil(data.details as? AwaitActionDetails)
let details = data.details as! AwaitActionDetails
XCTAssertEqual(details.payload, "pay load")
onDidProvideExpectation.fulfill()
}
sut.delegate = delegate
let result = MockedResult.success(PaymentStatusResponse(payload: "pay load", resultCode: .authorised))
apiClient.mockedResults = [result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 1)
}
func testStopRetryingWhenUserCancels() {
let apiClient = APIClientMock()
let retryApiClient = RetryAPIClient(apiClient: apiClient, scheduler: SimpleScheduler(maximumCount: 3))
let sut = PollingAwaitComponent(apiClient: retryApiClient)
let delegate = ActionComponentDelegateMock()
let onDidFailExpectation = expectation(description: "ActionComponentDelegate.didFail must be called.")
delegate.onDidFail = { error, component in
XCTAssertTrue(component === sut)
XCTAssertEqual(error as? ComponentError, ComponentError.cancelled)
onDidFailExpectation.fulfill()
}
delegate.onDidProvide = { _, _ in
XCTFail()
}
sut.delegate = delegate
let result = MockedResult.success(PaymentStatusResponse(payload: "pay load", resultCode: .pending))
apiClient.mockedResults = [result, result, result]
sut.handle(AwaitAction(paymentData: "data", paymentMethodType: .mbway))
sut.didCancel()
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(apiClient.counter, 1)
}
}
| 33.703226 | 116 | 0.673813 |
acde4063c79df1a17cd93e84caf780bb1209900e
| 373 |
import SwiftUI
struct Unwrap<Value, Content: View>: View {
private let value: Value?
private let contentProvider: (Value) -> Content
init(_ value: Value?,
@ViewBuilder content: @escaping (Value) -> Content)
{
self.value = value
contentProvider = content
}
var body: some View {
value.map(contentProvider)
}
}
| 20.722222 | 60 | 0.613941 |
16a6fde1d2c3b185572130623816486a10091d00
| 3,533 |
/// Copyright (c) 2019 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
import RxSwift
import Then
import Alamofire
import RxRealmDataSources
class ListTimelineViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var messageView: UIView!
private let bag = DisposeBag()
fileprivate var viewModel: ListTimelineViewModel!
fileprivate var navigator: Navigator!
static func createWith(navigator: Navigator, storyboard: UIStoryboard, viewModel: ListTimelineViewModel) -> ListTimelineViewController {
return storyboard.instantiateViewController(ofType: ListTimelineViewController.self).then { vc in
vc.navigator = navigator
vc.viewModel = viewModel
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 90
tableView.rowHeight = UITableView.automaticDimension
title = "@\(viewModel.list.username)/\(viewModel.list.slug)"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: nil, action: nil)
bindUI()
}
func bindUI() {
// Bind button to the people view controller
navigationItem.rightBarButtonItem!.rx.tap
.throttle(0.5, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] _ in
guard let self = self else { return }
self.navigator.show(segue: .listPeople(self.viewModel.account, self.viewModel.list), sender: self)
})
.disposed(by: bag)
// Show tweets in table view
let dataSource = RxTableViewRealmDataSource<Tweet>(cellIdentifier:
"TweetCellView", cellType: TweetCellView.self) { cell, _, tweet in
cell.update(with: tweet)
}
viewModel.tweets
.bind(to: tableView.rx.realmChanges(dataSource))
.disposed(by: bag)
// Show message when no account available
viewModel.loggedIn
.drive(messageView.rx.isHidden)
.disposed(by: bag)
}
}
| 40.147727 | 138 | 0.739881 |
29f5f5561ae903c8b676b17b7193860e53fc59f7
| 764 |
//
// SplashViewController.swift
// Demo
//
// Created by Ganesh Manickam on 10/04/21.
//
//
import UIKit
import RxSwift
import RxCocoa
class SplashViewController: UIViewController {
// MARK: - IBOutlets
// MARK: - Properties
let disposeBag = DisposeBag()
var viewModel: SplashViewModel!
// MARK: - Superview Methods
override func viewDidLoad() {
super.viewDidLoad()
initRxBinding()
setupUI()
}
}
// MARK: - Binding
extension SplashViewController {
/**
Function to initialize Rx binding
*/
func initRxBinding() {
}
}
// MARK: - UI Setup
extension SplashViewController {
/**
Function to setup ui elements
*/
func setupUI() {
}
}
| 15.28 | 46 | 0.596859 |
b978402022b0e1cd277385e0f5ca09eb9f3eef75
| 1,632 |
//
// InterfaceController.swift
// Menu WatchKit Extension
//
// Created by Thiago-Bernardes on 3/11/16.
// Copyright © 2016 TB. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.addMenuItemWithItemIcon(WKMenuItemIcon.Add, title: "Add", action: "addNewSong")
// Configure interface objects here.
}
@IBAction func saveFavoriteSong() {
let yesAction = { () -> Void in
print("saved")
}
let noAction = { () -> Void in
print("not saved")
}
self.presentAlertControllerWithTitle("Loteria", message: "Quer ganhar um milhão?", preferredStyle: .Alert, actions: [
WKAlertAction(title: "Não", style: .Default, handler: yesAction),
WKAlertAction(title: "Não", style: .Default, handler: noAction)
])
}
func addNewSong(){
print(__FUNCTION__)
}
@IBAction func newPlayAction() {
print(__FUNCTION__)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| 23.652174 | 125 | 0.556373 |
6211a5cf7e06502aab475261d7c5281905080dd8
| 2,840 |
//
// MultiClusterIntegrationTests.swift
//
//
// Created by Vladislav Fitc on 27/05/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
private extension SearchClient {
func remove(_ userID: UserID) throws {
while true {
do {
try removeUser(withID: userID)
break
} catch let error as HTTPError where error.statusCode == 400 || error.statusCode == 404 {
continue
} catch let error {
throw error
}
}
}
func exists(_ userID: UserID) throws -> Bool {
do {
try getUser(withID: userID)
return true
} catch let error as HTTPError where error.statusCode == 404 {
return false
} catch let error {
throw error
}
}
}
struct TestIdentifier {
let rawValue: String
init(date: Date = .init(), suffix: String? = nil) {
let language = "swift"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD-HH-mm-ss"
let dateString = dateFormatter.string(from: date)
let username = NSUserName().description
rawValue = [language, dateString, username, suffix].compactMap { $0 }.joined(separator: "-")
}
}
class MultipleClusterIntegrationTests: OnlineTestCase {
let date: Date = .init()
override var allowFailure: Bool { return true }
override var retryableTests: [() throws -> Void] {
[multiCluster]
}
func userID(_ id: String) -> UserID {
return UserID(rawValue: TestIdentifier(date: date, suffix: id).rawValue)
}
func multiCluster() throws {
let userID0 = userID("0")
let userID1 = userID("1")
let userID2 = userID("2")
let userIDs = [userID0, userID1, userID2]
let client = SearchClient(appID: TestCredentials.mcm!.applicationID, apiKey: TestCredentials.mcm!.apiKey)
let exists = client.exists
let remove = client.remove
let clusters = try client.listClusters().clusters
XCTAssertEqual(clusters.count, 2)
try client.assignUser(withID: userID0, toClusterWithName: clusters.first!.name)
try client.assignUsers(withIDs: [userID1, userID2], toClusterWithName: clusters.first!.name)
while try !(exists(userID0) && exists(userID1) && exists(userID2)) {
sleep(1)
}
for userID in userIDs {
let query = UserIDQuery().set(\.query, to: userID.rawValue)
XCTAssertEqual(try client.searchUser(with: query).hits.count, 1)
}
XCTAssertFalse(try client.listUsers().userIDs.isEmpty)
XCTAssertFalse(try client.getTopUser().topUsers.isEmpty)
try remove(userID0)
try remove(userID1)
try remove(userID2)
while try (exists(userID0) || exists(userID1) || exists(userID2)) {
sleep(1)
}
try client.hasPendingMappings(retrieveMappings: true)
}
}
| 25.132743 | 109 | 0.647183 |
29faefe755adecd4e8b380233143d9f32b87e027
| 11,057 |
//
// Signature.swift
// OntSwift
//
// Created by hsiaosiyuan on 2018/12/2.
// Copyright © 2018 hsiaosiyuan. All rights reserved.
//
import Foundation
import OpenSSL
public class Signature {
public let r: Data
public let s: Data
public let algorithm: SignatureScheme
public init(r: Data, s: Data, scheme: SignatureScheme) {
self.r = r
self.s = s
algorithm = scheme
}
public var bytes: Data {
var buf = Data()
buf.append(UInt8(algorithm.value))
if algorithm == .sm2Sm3 {
buf.append(Constant.defaultSm2Id)
buf.append(UInt8(0))
}
buf.append(r)
buf.append(s)
return buf
}
public var hexEncoded: String {
return bytes.hexEncoded
}
public static func from(raw: Data) throws -> Signature {
let buf = raw
let algo = SignatureScheme(rawValue: Int(buf[0]))!
var rs = buf.subdata(in: 1 ..< buf.count)
if algo == .sm2Sm3 {
guard let idx = rs.firstIndex(of: 0) else {
throw SignatureError.deformedSm2Sig
}
if !rs.subdata(in: 0 ..< idx).elementsEqual(Constant.defaultSm2Id) {
throw SignatureError.deformedSm2Sig
}
rs = rs.subdata(in: (idx + 1) ..< rs.count)
}
let r = rs.subdata(in: 0 ..< 32)
let s = rs.subdata(in: 32 ..< rs.count)
return Signature(r: r, s: s, scheme: algo)
}
public static func from(hex: String) throws -> Signature {
let raw = Data.from(hex: hex)!
return try from(raw: raw)
}
}
public enum SignatureError: Error {
case deformedSm2Sig
}
public final class Eddsa {
public static func pub(pri: Data) -> Data {
var pub = Data(count: 32)
pri.withUnsafeBytes { (priPtr: UnsafePointer<UInt8>) -> Void in
pub.withUnsafeMutableBytes { (pubPtr: UnsafeMutablePointer<UInt8>) -> Void in
ED25519_public_from_private(pubPtr, priPtr)
}
}
return pub
}
public static func sign(msg: Data, pub: Data, pri: Data) -> Signature {
var sig = Data(count: 64)
msg.withUnsafeBytes { (msgPtr: UnsafePointer<UInt8>) -> Void in
pub.withUnsafeBytes { (pubPtr: UnsafePointer<UInt8>) -> Void in
pri.withUnsafeBytes { (priPtr: UnsafePointer<UInt8>) -> Void in
sig.withUnsafeMutableBytes { (sigPtr: UnsafeMutablePointer<UInt8>) -> Void in
ED25519_sign(sigPtr, msgPtr, msg.count, pubPtr, priPtr)
}
}
}
}
let r = sig.subdata(in: 0 ..< 32)
let s = sig.subdata(in: 32 ..< sig.count)
return Signature(r: r, s: s, scheme: SignatureScheme.eddsaSha512)
}
public static func verify(msg: Data, sig: Signature, pub: Data) -> Bool {
var ok: Int32 = 0
var sr = Data()
sr.append(sig.r)
sr.append(sig.s)
msg.withUnsafeBytes { (msgPtr: UnsafePointer<UInt8>) -> Void in
sr.withUnsafeBytes { (sigPtr: UnsafePointer<UInt8>) -> Void in
pub.withUnsafeBytes { (pubPtr: UnsafePointer<UInt8>) -> Void in
ok = ED25519_verify(msgPtr, msg.count, sigPtr, pubPtr)
}
}
}
return ok == 1
}
}
/// Wrapper of BIGNUM*
public final class BN: Equatable, Comparable {
public fileprivate(set) var raw: OpaquePointer?
public init(raw: OpaquePointer?) {
self.raw = raw
}
public static func cmp(_ a: BN, _ b: BN) -> Int {
return Int(BN_cmp(a.raw, b.raw))
}
public static func == (_ a: BN, _ b: BN) -> Bool {
return BN.cmp(a, b) == 0 ? true : false
}
public static func < (_ a: BN, _ b: BN) -> Bool {
return BN.cmp(a, b) < 0 ? true : false
}
}
/// Wrapper of EVP_PKEY*
public final class PKey {
public fileprivate(set) var raw: OpaquePointer?
public static let sm2id = "1234567812345678".data(using: .utf8)!
public init(raw: OpaquePointer?) {
self.raw = raw
}
deinit {
if let ptr = raw {
EVP_PKEY_free(ptr)
raw = nil
}
}
public enum PubMode {
case uncompress, compress, mix
}
public func pub(mode: PubMode) -> Data {
let eckey = EVP_PKEY_get0_EC_KEY(raw)
let pubpnt = EC_KEY_get0_public_key(eckey)
var form: point_conversion_form_t
switch mode {
case .uncompress: form = POINT_CONVERSION_UNCOMPRESSED
case .compress: form = POINT_CONVERSION_COMPRESSED
case .mix: form = POINT_CONVERSION_HYBRID
}
var group = EC_GROUP_dup(EC_KEY_get0_group(eckey))
defer {
EC_GROUP_free(group)
}
var pbuf: UnsafeMutablePointer<UInt8>?
let len = EC_POINT_point2buf(group, pubpnt, form, &pbuf, nil)
return Data(bytesNoCopy: pbuf!, count: len, deallocator: .free)
}
public var pubxy: (x: BN, y: BN) {
let eckey = EVP_PKEY_get0_EC_KEY(raw)
let pubpnt = EC_KEY_get0_public_key(eckey)
let group = EC_GROUP_dup(EC_KEY_get0_group(eckey))
let x = BN_new()
let y = BN_new()
EC_POINT_get_affine_coordinates_GFp(group, pubpnt, x, y, nil)
return (BN(raw: x), BN(raw: y))
}
public func pri() -> Data {
let eckey = EVP_PKEY_get0_EC_KEY(raw)
let k = EC_KEY_get0_private_key(eckey)
let len = (BN_num_bits(k) + 7) / 8
let ret = NSMutableData()
ret.length = Int(len)
BN_bn2bin(k, ret.mutableBytes.assumingMemoryBound(to: UInt8.self))
return ret as Data
}
public func sign(msg: Data, scheme: SignatureScheme) throws -> Signature {
let msg = msg as NSData
var mdctx = EVP_MD_CTX_new()
defer {
EVP_MD_CTX_free(mdctx)
}
let isSm2 = scheme == .sm2Sm3
var pkctx: OpaquePointer?
defer {
if let ptr = pkctx {
EVP_PKEY_CTX_free(ptr)
}
}
if isSm2 {
EVP_PKEY_set_alias_type(raw, EVP_PKEY_SM2)
pkctx = EVP_PKEY_CTX_new(raw, nil)
PKey.sm2id.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
EVP_PKEY_CTX_ctrl(pkctx, -1, -1, EVP_PKEY_CTRL_SET1_ID, Int32(PKey.sm2id.count), UnsafeMutableRawPointer(mutating: ptr))
}
EVP_MD_CTX_set_pkey_ctx(mdctx, pkctx)
}
if 1 != EVP_DigestSignInit(mdctx, nil, scheme.hashAlgo, nil, raw) {
throw PKeyError.signInit
}
if 1 != EVP_DigestUpdate(mdctx, msg.bytes, msg.length) {
throw PKeyError.signUpdate
}
var sigbuf = NSMutableData()
sigbuf.length = Int(EVP_PKEY_size(raw))
var siglen = sigbuf.length
if 1 != EVP_DigestSignFinal(mdctx, sigbuf.mutableBytes.assumingMemoryBound(to: UInt8.self), &siglen) {
throw PKeyError.signFinal
}
var sigbufptr: UnsafePointer<UInt8>? = sigbuf.bytes.assumingMemoryBound(to: UInt8.self)
var sig = d2i_ECDSA_SIG(nil, &sigbufptr, Int(siglen))
defer {
ECDSA_SIG_free(sig)
}
let r = ECDSA_SIG_get0_r(sig)
let s = ECDSA_SIG_get0_s(sig)
let rlen = (BN_num_bits(r) + 7) / 8
let slen = (BN_num_bits(s) + 7) / 8
var rbuf = Data(count: Int(rlen))
rbuf.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Void in
BN_bn2bin(r, ptr)
}
var sbuf = Data(count: Int(slen))
sbuf.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Void in
BN_bn2bin(s, ptr)
}
return Signature(r: rbuf, s: sbuf, scheme: scheme)
}
public func verify(msg: Data, sig: Signature) throws -> Bool {
let msg = msg as NSData
var r = sig.r.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> OpaquePointer in
return BN_bin2bn(ptr, Int32(sig.r.count), nil)
}
var s = sig.s.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> OpaquePointer in
return BN_bin2bn(ptr, Int32(sig.s.count), nil)
}
var si = ECDSA_SIG_new()
defer {
ECDSA_SIG_free(si)
}
ECDSA_SIG_set0(si, r, s)
var sigdlen = EVP_PKEY_size(raw)
var sigd = malloc(Int(sigdlen))
defer {
free(sigd)
}
var sigdptr = sigd?.assumingMemoryBound(to: UInt8.self)
sigdlen = i2d_ECDSA_SIG(si, &sigdptr)
var mdctx = EVP_MD_CTX_new()
defer {
EVP_MD_CTX_free(mdctx)
}
let isSm2 = sig.algorithm == .sm2Sm3
var pkctx: OpaquePointer?
defer {
if let ptr = pkctx {
EVP_PKEY_CTX_free(ptr)
}
}
if isSm2 {
EVP_PKEY_set_alias_type(raw, EVP_PKEY_SM2)
pkctx = EVP_PKEY_CTX_new(raw, nil)
PKey.sm2id.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
EVP_PKEY_CTX_ctrl(pkctx, -1, -1, EVP_PKEY_CTRL_SET1_ID, Int32(PKey.sm2id.count), UnsafeMutableRawPointer(mutating: ptr))
}
EVP_MD_CTX_set_pkey_ctx(mdctx, pkctx)
}
if 1 != EVP_DigestVerifyInit(mdctx, nil, sig.algorithm.hashAlgo, nil, raw) {
throw PKeyError.verifyInit
}
if 1 != EVP_DigestUpdate(mdctx, msg.bytes, msg.length) {
throw PKeyError.verifyUpdate
}
return EVP_DigestVerifyFinal(mdctx, sigd?.assumingMemoryBound(to: UInt8.self), Int(sigdlen)) == 1
}
}
public enum PKeyError: Error {
case signInit, signUpdate, signFinal, verifyInit, verifyUpdate, verifyFinal
}
public final class Ecdsa {
/// Creates EVP_PKEY from raw private key
///
/// - Parameter data: raw private key
/// - Returns: PKey
public static func pkey(pri: Data, curve: Int32) -> PKey {
var ok = false
var ret = PKey(raw: nil)
var eckey = EC_KEY_new_by_curve_name(curve)
defer {
if !ok {
EC_KEY_free(eckey)
}
}
let group = EC_KEY_get0_group(eckey)
EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE)
var pribn = pri.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> OpaquePointer in
return BN_bin2bn(ptr, Int32(pri.count), nil)
}
defer {
BN_free(pribn)
}
if 1 != EC_KEY_set_private_key(eckey, pribn) {
return ret
}
var pubpnt = EC_POINT_new(group)
defer {
EC_POINT_free(pubpnt)
}
if 1 != EC_POINT_mul(group, pubpnt, pribn, nil, nil, nil) {
return ret
}
if 1 != EC_KEY_set_public_key(eckey, pubpnt) {
return ret
}
var pkey = EVP_PKEY_new()
defer {
if !ok {
EVP_PKEY_free(pkey)
}
}
if 1 != EC_KEY_check_key(eckey) || 1 != EVP_PKEY_assign(pkey, EVP_PKEY_EC, UnsafeMutableRawPointer(eckey)) {
return ret
}
ok = true
ret.raw = pkey
return ret
}
/// Creates EVP_PKEY from raw public key
///
/// - Parameter data: raw public key
/// - Returns: PKey
public static func pkey(pub: Data, curve: Int32) -> PKey {
var ok = false
var ret = PKey(raw: nil)
var eckey = EC_KEY_new_by_curve_name(curve)
defer {
if !ok {
EC_KEY_free(eckey)
}
}
let group = EC_KEY_get0_group(eckey)
EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE)
var pubpnt = EC_POINT_new(group)
pub.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
EC_POINT_oct2point(group, pubpnt, ptr, pub.count, nil)
}
defer {
EC_POINT_free(pubpnt)
}
if 1 != EC_KEY_set_public_key(eckey, pubpnt) {
return ret
}
var pkey = EVP_PKEY_new()
defer {
if !ok {
EVP_PKEY_free(pkey)
}
}
if 1 != EC_KEY_check_key(eckey) || 1 != EVP_PKEY_assign(pkey, EVP_PKEY_EC, UnsafeMutableRawPointer(eckey)) {
return ret
}
ok = true
ret.raw = pkey
return ret
}
}
| 25.535797 | 128 | 0.635073 |
894ea5a93e6f83914667324a3c243bcb75cfa84d
| 455 |
/*
*/
import Foundation
struct SourceResponse : Codable {
let status : String?
let sources : [Sources]?
enum CodingKeys: String, CodingKey {
case status = "status"
case sources = "sources"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
status = try values.decodeIfPresent(String.self, forKey: .status)
sources = try values.decodeIfPresent([Sources].self, forKey: .sources)
}
}
| 18.2 | 72 | 0.707692 |
8a47c84056ba651e165ae97c0e1c65d1a4e66b30
| 8,171 |
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Original Source
// "The Oxford-IIIT Pet Dataset"
// Omkar M Parkhi, Andrea Vedaldi, Andrew Zisserman and C. V. Jawahar
// https://www.robots.ox.ac.uk/~vgg/data/pets/
import Foundation
import ModelSupport
import TensorFlow
public struct OxfordIIITPets<Entropy: RandomNumberGenerator> {
/// Type of the collection of non-collated batches.
public typealias Batches = Slices<Sampling<[(file: URL, annotation: URL)], ArraySlice<Int>>>
/// The type of the training data, represented as a sequence of epochs, which
/// are collection of batches.
public typealias Training = LazyMapSequence<
TrainingEpochs<[(file: URL, annotation: URL)], Entropy>,
LazyMapSequence<Batches, SegmentedImage>
>
/// The type of the validation data, represented as a collection of batches.
public typealias Validation = LazyMapSequence<
Slices<[(file: URL, annotation: URL)]>, LabeledImage
>
/// The training epochs.
public let training: Training
/// The validation batches.
public let validation: Validation
/// Creates an instance with `batchSize`.
///
/// - Parameters:
/// - batchSize: Number of images provided per batch.
/// - entropy: A source of randomness used to shuffle sample
/// ordering. It will be stored in `self`, so if it is only pseudorandom
/// and has value semantics, the sequence of epochs is deterministic and not
/// dependent on other operations.
/// - device: The Device on which resulting Tensors from this dataset will be placed, as well
/// as where the latter stages of any conversion calculations will be performed.
public init(batchSize: Int, entropy: Entropy, device: Device) {
self.init(
batchSize: batchSize, entropy: entropy, device: device, imageSize: 224)
}
/// Creates an instance with `batchSize` on `device` using `remoteBinaryArchiveLocation`.
///
/// - Parameters:
/// - batchSize: Number of images provided per batch.
/// - entropy: A source of randomness used to shuffle sample ordering. It
/// will be stored in `self`, so if it is only pseudorandom and has value
/// semantics, the sequence of epochs is deterministic and not dependent
/// on other operations.
/// - device: The Device on which resulting Tensors from this dataset will be placed, as well
/// as where the latter stages of any conversion calculations will be performed.
/// - imageSize: The square width and height of the images returned from this dataset.
/// - localStorageDirectory: Where to place the downloaded and unarchived dataset.
public init(
batchSize: Int, entropy: Entropy, device: Device, imageSize: Int,
localStorageDirectory: URL = DatasetUtilities.defaultDirectory
.appendingPathComponent("OxfordIIITPets", isDirectory: true)
) {
do {
let trainingSamples = try loadOxfordIITPetsTraining(
localStorageDirectory: localStorageDirectory)
training = TrainingEpochs(samples: trainingSamples, batchSize: batchSize, entropy: entropy)
.lazy.map { (batches: Batches) -> LazyMapSequence<Batches, LabeledImage> in
return batches.lazy.map {
makeBatch(samples: $0, imageSize: imageSize, device: device)
}
}
let validationSamples = try loadOxfordIITPetsTraining(
localStorageDirectory: localStorageDirectory)
validation = validationSamples.inBatches(of: batchSize).lazy.map {
makeBatch(samples: $0, imageSize: imageSize, device: device)
}
} catch {
fatalError("Could not load the Oxford IIIT Pets dataset: \(error)")
}
}
}
extension OxfordIIITPets: ImageSegmentationData where Entropy == SystemRandomNumberGenerator {
/// Creates an instance with `batchSize`, using the SystemRandomNumberGenerator.
public init(batchSize: Int, on device: Device = Device.default) {
self.init(batchSize: batchSize, entropy: SystemRandomNumberGenerator(), device: device)
}
/// Creates an instance with `batchSize`, `inputSize`, and `outputSize`, using the
/// SystemRandomNumberGenerator.
public init(batchSize: Int, imageSize: Int, on device: Device = Device.default) {
self.init(
batchSize: batchSize, entropy: SystemRandomNumberGenerator(), device: device,
imageSize: imageSize)
}
}
func downloadOxfordIIITPetsIfNotPresent(to directory: URL) {
let downloadPath = directory.appendingPathComponent("images", isDirectory: true).path
let directoryExists = FileManager.default.fileExists(atPath: downloadPath)
let contentsOfDir = try? FileManager.default.contentsOfDirectory(atPath: downloadPath)
let directoryEmpty = (contentsOfDir == nil) || (contentsOfDir!.isEmpty)
guard !directoryExists || directoryEmpty else { return }
let remoteRoot = URL(string: "https://www.robots.ox.ac.uk/~vgg/data/pets/data/")!
let _ = DatasetUtilities.downloadResource(
filename: "images", fileExtension: "tar.gz",
remoteRoot: remoteRoot, localStorageDirectory: directory
)
let _ = DatasetUtilities.downloadResource(
filename: "annotations", fileExtension: "tar.gz",
remoteRoot: remoteRoot, localStorageDirectory: directory
)
}
func loadOxfordIIITPets(filename: String, in directory: URL) throws -> [(
file: URL, annotation: URL
)] {
downloadOxfordIIITPetsIfNotPresent(to: directory)
let imageURLs = getImageURLs(filename: filename, directory: directory)
return imageURLs.lazy.map { (imageURL: URL) -> (file: URL, annotation: URL) in
(file: imageURL, annotation: makeAnnotationURL(imageURL: imageURL, directory: directory))
}
}
func makeAnnotationURL(imageURL: URL, directory: URL) -> URL {
let filename = imageURL.deletingPathExtension().lastPathComponent
return directory.appendingPathComponent("annotations/trimaps/\(filename).png")
}
func getImageURLs(filename: String, directory: URL) -> [URL] {
let filePath = directory.appendingPathComponent("annotations/\(filename)")
let imagesRootDirectory = directory.appendingPathComponent("images", isDirectory: true)
let fileContents = try? String(contentsOf: filePath)
let imageDetails = fileContents!.split(separator: "\n")
return imageDetails.map {
let imagename = String($0[..<$0.firstIndex(of: " ")!])
return imagesRootDirectory.appendingPathComponent("\(imagename).jpg")
}
}
func loadOxfordIITPetsTraining(localStorageDirectory: URL) throws -> [(file: URL, annotation: URL)]
{
return try loadOxfordIIITPets(
filename: "trainval.txt", in: localStorageDirectory)
}
func loadOxfordIIITPetsValidation(localStorageDirectory: URL) throws -> [(
file: URL, annotation: URL
)] {
return try loadOxfordIIITPets(
filename: "test.txt", in: localStorageDirectory)
}
fileprivate func makeBatch<BatchSamples: Collection>(
samples: BatchSamples, imageSize: Int, device: Device
) -> SegmentedImage where BatchSamples.Element == (file: URL, annotation: URL) {
let images = samples.map(\.file).map { url -> Tensor<Float> in
Image(contentsOf: url).resized(to: (imageSize, imageSize)).tensor[0..., 0..., 0..<3]
}
var imageTensor = Tensor(stacking: images)
imageTensor = Tensor(copying: imageTensor, to: device)
imageTensor /= 255.0
let annotations = samples.map(\.annotation).map { url -> Tensor<Int32> in
Tensor<Int32>(
Image(contentsOf: url).resized(to: (imageSize, imageSize)).tensor[0..., 0..., 0...0] - 1)
}
var annotationTensor = Tensor(stacking: annotations)
annotationTensor = Tensor(copying: annotationTensor, to: device)
return SegmentedImage(data: imageTensor, label: annotationTensor)
}
| 42.557292 | 99 | 0.725003 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.