blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
0c9494b667f1d4b69efd2d80a7041b091e88f012
|
Swift
|
DeveloperZhang/Swift_Demo
|
/20180718HttpToolDemo/VZHttpSwiftTool/VZHttpSwiftTool/ViewController.swift
|
UTF-8
| 2,214
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// VZHttpSwiftTool
//
// Created by Vicent on 2018/7/17.
// Copyright © 2018年 VicentZ. All rights reserved.
//
import UIKit
enum RequestType {
case Get
case Post
}
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var array: Array<Any>?
var requestType: RequestType?
override func viewDidLoad() {
super.viewDidLoad()
self.array = ["get请求","post请求"];
let cellIdentify: String = "MyTableViewCell";
tableView.register(UINib.init(nibName: cellIdentify, bundle: nil), forCellReuseIdentifier: cellIdentify)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.array?.count)!;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentify: String = "MyTableViewCell";
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentify)!;
cell.textLabel?.text = self.array?[indexPath.row] as? String;
return cell;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 88;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
self.requestType = RequestType.Get;
break
default:
self.requestType = RequestType.Post;
break;
}
switch self.requestType {
case .Get?:
VZHttpTool.get(url: "http://test.imhuasheng.com//app/v2/appVersion/version", urlParamDic: ["id":"1"], successBlock: { (httpResponse) in
print(httpResponse as Any)
}, failedBlock: { (httpError) in
print(httpError as Any)
})
break
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
57c3cd95c5ee8aed89b1860bb9e7ac2f2d7f46d8
|
Swift
|
SonVH013/JuicyBreaker-
|
/Juicy Breakout/Scenes/GameMenuScene.swift
|
UTF-8
| 2,283
| 2.75
| 3
|
[] |
no_license
|
//
// GameMenu.swift
// Juicy Breakout
//
// Created by SonVu on 10/2/16.
// Copyright © 2016 Hoang Doan. All rights reserved.
//
import SpriteKit
class GameMenuScene: SKScene {
override func didMove(to view: SKView) {
addBackGround()
addButton()
}
func addBackGround() {
let backGround = SKSpriteNode(color: UIColor(red:0.97, green:0.95, blue:0.70, alpha:1.0), size: self.frame.size)
backGround.anchorPoint = CGPoint.zero
addChild(backGround)
}
func addButton() {
let named = SKLabelNode(text: "Juicy Breaker")
named.position.x = self.frame.size.width / 2
named.position.y = self.frame.size.height / 2 + 50
named.fontSize = 30
named.fontColor = UIColor(red:0.38, green:0.74, blue:0.52, alpha:1.0)
named.fontName = "Zapfino"
addChild(named)
let backgroundText = SKSpriteNode(color: UIColor(red:0.81, green:0.22, blue:0.27, alpha:1.0), size: CGSize(width: 500, height: 70))
backgroundText.position.x = self.frame.size.width / 2
backgroundText.position.y = self.frame.size.height / 2 - 150
// backgroundText.anchorPoint = CGPoint.zero
backgroundText.name = "Play"
addChild(backgroundText)
let cheat = SKLabelNode(text: "Tab to play")
cheat.fontSize = 32
cheat.fontColor = UIColor.white
cheat.position.x = self.frame.size.width / 2
cheat.position.y = self.frame.size.height / 2 - 160
cheat.name = "Play"
addChild(cheat)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let touchNodes = self.nodes(at: location)
for node in touchNodes {
if(node.name == "Play") {
//1 creat secent
let gameScene = GameScene(size: (self.view?.frame.size)!)
//2 transport
self.view?.presentScene(gameScene, transition: SKTransition.fade(with: UIColor.black, duration: 0.5))
GameScene.score = 0
}
}
}
}
}
| true
|
40237a0624442031b9affe6668e1d0371a7eef8c
|
Swift
|
wpd550/Animation
|
/EcornAnimationDemo/EcornAnimationDemo/keyAnimationController/KeyAnimationController.swift
|
UTF-8
| 2,937
| 3.078125
| 3
|
[] |
no_license
|
//
// KeyAnimationController.swift
// EcornAnimationDemo
//
// Created by dong on 2021/9/26.
//
import UIKit
enum KeyFrameAnimationType: Int {
case keyFrame = 0 //关键帧
case path //路径
case shake //抖动
}
class KeyAnimationController: BaseViewController {
fileprivate var type:KeyFrameAnimationType!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func removeFromParent() {
super.removeFromParent()
}
convenience init(enterType:Int) {
self.init()
switch enterType {
case 0:
type = .keyFrame
case 1:
type = .path
case 2:
type = .shake
default:
break
}
}
}
extension KeyAnimationController{
override func playBtnClick(btn: UIButton) {
switch type.rawValue {
case 0:
keyFrameAnimation()
case 1:
pathAnimation()
case 2:
shakeAnimation()
default:
break
}
}
}
extension KeyAnimationController{
func keyFrameAnimation(){
let animation = CAKeyframeAnimation.init(keyPath: "position")
let value_0 = CGPoint.init(x: margin_ViewMidPosition, y: kScreenH / 2 - margin_ViewWidthHeight)
let value_1 = CGPoint.init(x: kScreenW / 3, y: kScreenH / 2 - margin_ViewWidthHeight)
let value_2 = CGPoint.init(x: kScreenW / 3, y: kScreenH / 2 + margin_ViewMidPosition)
let value_3 = CGPoint.init(x: kScreenW * 2 / 3, y: kScreenH / 2 + margin_ViewMidPosition)
let value_4 = CGPoint.init(x: kScreenW * 2 / 3, y: kScreenH / 2 - margin_ViewWidthHeight)
let value_5 = CGPoint.init(x: kScreenW - margin_ViewMidPosition, y: kScreenH / 2 - margin_ViewWidthHeight)
animation.values = [value_0, value_1, value_2, value_3, value_4, value_5]
animation.duration = 2.0
view_Body.layer.add(animation, forKey: "keyFrameAnimation")
}
// 只对涂层又有
func pathAnimation(){
let animation = CAKeyframeAnimation.init(keyPath: "position")
let path = UIBezierPath.init(arcCenter: CGPoint.init(x: kScreenW/2, y: kScreenH/2), radius: 60, startAngle: 0.0, endAngle: .pi * 2, clockwise: true)
animation.path = path.cgPath
animation.duration = 2.0
view_Body.layer.add(animation, forKey: "pathAnimation")
}
func shakeAnimation(){
let animation = CAKeyframeAnimation.init(keyPath: "transform.rotation")
let value_0 = NSNumber.init(value: -Double.pi / 180 * 16)
let value_1 = NSNumber.init(value: Double.pi / 180 * 16)
animation.values = [value_0, value_1, value_0]
animation.duration = 0.1
animation.repeatCount = 2
view_Body.layer.add(animation, forKey: "shakeAnimation")
}
}
| true
|
a9bd2b6787974135f0d9b2bbd0b07efa806faddd
|
Swift
|
alxarsnk/RealmHWProject
|
/TestRealm/TestUser.swift
|
UTF-8
| 620
| 2.625
| 3
|
[] |
no_license
|
//
// TestUser.swift
// TestRealm
//
// Created by Ильдар Залялов on 25/02/2019.
// Copyright © 2019 Ильдар Залялов. All rights reserved.
//
import UIKit
@objcMembers
class TestUser: NSObject {
dynamic var name = String()
dynamic var age: Int = 0
override var description: String {
return "\nName - \(name), Age - \(age)"
}
override class func automaticallyNotifiesObservers(forKey key: String) -> Bool {
if key == "name" {
return false
}
else {
return super.automaticallyNotifiesObservers(forKey: key)
}
}
}
| true
|
d81519916465223776969e57b6d8e3e75ba8aae9
|
Swift
|
q195945056/ShareEducation
|
/ShareEducation/Classes/Common/View/SplashView.swift
|
UTF-8
| 1,321
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// SplashView.swift
// ShareEducation
//
// Created by 严明俊 on 2019/11/26.
// Copyright © 2019 严明俊. All rights reserved.
//
import UIKit
class SplashView: UIView {
static var canShowSplash: Bool {
let shareData = ShareData.shared
let resource = shareData.splashResources?.first
if let _ = resource {
return true
} else {
return false
}
}
lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: self.bounds)
let resource = (ShareData.shared.splashResources?.first)!
imageView.kf.setImage(with: URL(string: resource.img.fullURLString))
return imageView
}()
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func show(in view: UIView) {
view.addSubview(self)
// DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
// self.removeFromSuperview()
// }
}
}
| true
|
68f84564e9917eea26eff83abceeebb5f899e0e7
|
Swift
|
RuslanMavlyutov/Currencies
|
/Currencies/ExchangeRate/ConvertModel/ConvertModel.swift
|
UTF-8
| 2,246
| 3.265625
| 3
|
[] |
no_license
|
import Foundation
struct TextFieldModel {
var character: String
var firstCurrencyValue: Float
var secondCurrencyValue: Float
var firstTextFieldText: String
var secondTextFieldText: String
var isFirstTextFieldFilled: Bool
}
struct KeyStringsProperties {
static let format = "yyyy-MM-dd HH:mm:ss"
static let text = "..."
static let keyEUR = "EUR"
static let keyRUB = "RUB"
static let descriptRUB = "Российский рубль"
static let characters = "0123456789."
static let keyDot = "."
static let keyDotNull = ".0"
static let keyNullDot = "0."
}
final class ConvertModel {
func convert(textFieldModel: TextFieldModel) -> String {
var numberStr = String()
var ratio = Float()
if textFieldModel.isFirstTextFieldFilled {
numberStr = textFieldModel.firstTextFieldText + textFieldModel.character
ratio = textFieldModel.firstCurrencyValue / textFieldModel.secondCurrencyValue
} else {
numberStr = textFieldModel.secondTextFieldText + textFieldModel.character
ratio = textFieldModel.secondCurrencyValue / textFieldModel.firstCurrencyValue
}
if textFieldModel.character.isEmpty {
numberStr.removeLast()
}
if numberStr == KeyStringsProperties.keyDot {
numberStr = KeyStringsProperties.keyNullDot
}
if !numberStr.isEmpty {
var textValue = "\(Float(numberStr)! * ratio)"
if textValue.count > 2, String(textValue.suffix(2)) == KeyStringsProperties.keyDotNull {
textValue = String(textValue.dropLast(2))
}
return textValue
} else {
return String()
}
}
func changeCurrecncy(_ textFieldModel: TextFieldModel) -> String {
var numberStr = textFieldModel.firstTextFieldText
let ratio = textFieldModel.firstCurrencyValue / textFieldModel.secondCurrencyValue
if numberStr == KeyStringsProperties.keyDot {
numberStr = KeyStringsProperties.keyDotNull
}
if !numberStr.isEmpty {
return "\(Float(numberStr)! * ratio)"
} else {
return String()
}
}
}
| true
|
01198ef5bdb6c4cb58bbd9642c1bb546a16d1622
|
Swift
|
kuojed/PokemonPvP
|
/PokemonPvP/PokemonList.swift
|
UTF-8
| 1,312
| 2.75
| 3
|
[] |
no_license
|
//
// GreatDetail.swift
// PokemonPvP
//
// Created by 郭冠杰 on 2020/3/22.
// Copyright © 2020 郭冠杰. All rights reserved.
//
import SwiftUI
struct PokemonList: View {
let pokemons: [Pokemon]
let leagueName: String
var body: some View {
// ZStack{
// Rectangle()
// .fill(Color(red: 254/255, green: 250/255, blue: 212/255))
// .edgesIgnoringSafeArea(.all)
List(pokemons.indices) { item in
NavigationLink(destination: PokemonDetail(pokemon: self.pokemons[item])) {
PokemonRow(pokemon: self.pokemons[item])
}
}
// VStack{
//
// ForEach(pokemons.indices) { item in
//
//
// NavigationLink(destination: PokemonDetail(pokemon: self.pokemons[item])) {
// PokemonRow(pokemon: self.pokemons[item])
// }
// }
// }
.navigationBarTitle(leagueName)
// }
}
}
struct PokemonList_Previews: PreviewProvider {
static var previews: some View {
NavigationView{
PokemonList(pokemons: greatPokemons, leagueName: "超級聯盟")
}
}
}
| true
|
77e15ae1a4c58f94d9f727588d79eaf8813ce635
|
Swift
|
azmisahin/azmisahin-software-mobile-ios-Automation
|
/web/Library/Logger/Logger.swift
|
UTF-8
| 2,480
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
//
// Logger.swift
// web
//
// Created by Azmi SAHIN on 28/08/2017.
// Copyright © 2017 Azmi SAHIN. All rights reserved.
//
// MARK: - Requared
import Foundation
/// Log Level
///
/// var logLevel : LogLevel.All
///
public enum LogLevel: Int {
// MARK: - Property
case
/// All
///
/// 0
All = 0
/// Verbose
///
/// 1
, Verbose = 1
/// Debug
///
/// 2
, Debug = 2
/// Info
///
/// 0
, Info = 3
/// All
///
/// 4
, Warning = 4
/// Error
///
/// 5
, Error = 5
/// Off
///
/// 6
, Off = 6
}
/// Logger
///
/// var log : Logger()
///
/// log.info("Logger Success", .Info)
///
public struct Logger {
/// All
public func all(_ value: String)
{
write(value: value, level: .Debug)
}
/// Verbose
public func verbose(_ value: String)
{
write(value: value, level: .Debug)
}
/// Debug
public func debug(_ value: String)
{
write(value: value, level: .Debug)
}
/// Info
public func info(_ value: String)
{
write(value: value, level: .Info)
}
/// Warning
public func warning(_ value: String)
{
write(value: value, level: .Warning)
}
/// Error
public func error(_ value: String)
{
write(value: value, level: .Error)
}
/// Off
public func off(_ value: String)
{
write(value: value, level: .Off)
}
/// Write
private func write(value: String, level : LogLevel)
{
// Termianal
let terminalAll = ">"
let terminalDebug = ">"
let terminalError = ">"
let terminalInfo = ">"
let terminalOff = ">"
let terminalVerbose = ">"
// Console
var console = ""
// Proc
switch level
{
case LogLevel.All: console = terminalAll + value
case LogLevel.Debug: console = terminalDebug + value
case LogLevel.Error: console = terminalError + value
case LogLevel.Info: console = terminalInfo + value
case LogLevel.Off: console = terminalOff + value
case LogLevel.Verbose: console = terminalVerbose
default: console = terminalAll + value
}
// Print
print(console)
}
}
/// Logger
var log = Logger()
| true
|
5c4a5161e2e9aca2eff737958b9cf6f7c861279f
|
Swift
|
califrench/Swifton
|
/Sources/Swifton/CustomMiddleware.swift
|
UTF-8
| 124
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import S4
public protocol CustomMiddleware {
func call(request: Request, _ closure: Request -> Response) -> Response
}
| true
|
34736d4aeb55477ff70e491f1aa9c301d87b0fc0
|
Swift
|
apple/swift
|
/test/Concurrency/Runtime/async_sequence.swift
|
UTF-8
| 28,039
| 2.53125
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library)
// REQUIRES: executable_test
// REQUIRES: concurrency
// rdar://76038845
// REQUIRES: concurrency_runtime
// TODO: This crashes on linux for some strange reason
// REQUIRES: OS=macosx
import StdlibUnittest
// Utility functions for closure based operators to force them into throwing
// and async and throwing async contexts.
@available(SwiftStdlib 5.1, *)
func throwing<T>(_ value: T) throws -> T {
return value
}
@available(SwiftStdlib 5.1, *)
func asynchronous<T>(_ value: T) async -> T {
return value
}
@available(SwiftStdlib 5.1, *)
func asynchronousThrowing<T>(_ value: T) async throws -> T {
return value
}
@available(SwiftStdlib 5.1, *)
struct Failure: Error, Equatable {
var value = 1
}
@available(SwiftStdlib 5.1, *)
func failable<T, E: Error>(
_ results: [Result<T, E>]
) -> AsyncThrowingMapSequence<AsyncLazySequence<[Result<T, E>]>, T> {
return results.async.map { try $0.get() }
}
@available(SwiftStdlib 5.1, *)
extension Sequence {
@inlinable
public var async: AsyncLazySequence<Self> {
get {
return AsyncLazySequence(self)
}
}
}
@available(SwiftStdlib 5.1, *)
public struct AsyncLazySequence<S: Sequence>: AsyncSequence {
public typealias Element = S.Element
public typealias AsyncIterator = Iterator
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var iterator: S.Iterator
@usableFromInline
init(_ iterator: S.Iterator) {
self.iterator = iterator
}
@inlinable
public mutating func next() async -> S.Element? {
return iterator.next()
}
}
public let sequence: S
@usableFromInline
init(_ sequence: S) {
self.sequence = sequence
}
@inlinable
public func makeAsyncIterator() -> Iterator {
return Iterator(sequence.makeIterator())
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
@inlinable
public func collect() async rethrows -> [Element] {
var items = [Element]()
var it = makeAsyncIterator()
while let e = try await it.next() {
items.append(e)
}
return items
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence where Element: Equatable {
func `throw`(_ error: Error, on element: Element) -> AsyncThrowingMapSequence<Self, Element> {
return map { (value: Element) throws -> Element in
if value == element { throw error }
return value
}
}
}
@main struct Main {
static func main() async {
if #available(SwiftStdlib 5.1, *) {
var AsyncLazySequenceTests = TestSuite("AsyncLazySequence")
AsyncLazySequenceTests.test("iteration past first nil") {
let seq = [1, 2, 3]
let async_seq = seq.async
var iter = async_seq.makeAsyncIterator()
let a = await iter.next()
expectEqual(a, 1)
let b = await iter.next()
expectEqual(b, 2)
let c = await iter.next()
expectEqual(c, 3)
let d = await iter.next()
expectNil(d)
let e = await iter.next()
expectNil(e)
}
AsyncLazySequenceTests.test("iterate twice with iterators before usage") {
let s = [1, 2, 3].async
var iter1 = s.makeAsyncIterator()
var iter2 = s.makeAsyncIterator()
var iter1Results = [Int?]()
var iter2Results = [Int?]()
for _ in 1...4 {
do {
let value = await iter1.next()
iter1Results.append(value)
}
do {
let value = await iter2.next()
iter2Results.append(value)
}
}
expectEqual(iter1Results, iter2Results)
expectEqual(iter1Results, [1, 2, 3, nil])
}
var AsyncSequenceTests = TestSuite("AsyncSequence")
AsyncSequenceTests.test("reduce") {
let result = await [1, 2, 3].async.reduce(0) { partial, element in
return partial + element
}
expectEqual(result, 1 + 2 + 3)
}
AsyncSequenceTests.test("reduce throws in closure") {
do {
_ = try await [1, 2, 3].async.reduce(0) { partial, element in
if element == 2 { throw Failure(value: 42) }
return partial + element
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("reduce throws upstream") {
do {
let _ = try await [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.reduce(0) { partial, element in
return partial + element
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("reduce into") {
let result = await [1, 2, 3].async.reduce(into: 0) { partial, element in
partial += element
}
expectEqual(result, 1 + 2 + 3)
}
AsyncSequenceTests.test("reduce into throws in closure") {
do {
_ = try await [1, 2, 3].async.reduce(into: 0) { partial, element in
if element == 2 { throw Failure(value: 42) }
partial += element
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("reduce into throws upstream") {
do {
_ = try await [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.reduce(into: 0) { partial, element in
partial += element
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("contains predicate true") {
let result = await [1, 2, 3].async.contains { $0 == 2 }
expectTrue(result)
}
AsyncSequenceTests.test("contains predicate false") {
let result = await [1, 2, 3].async.contains { $0 == 4 }
expectFalse(result)
}
AsyncSequenceTests.test("contains predicate empty") {
let result = await [Int]().async.contains { $0 == 4 }
expectFalse(result)
}
AsyncSequenceTests.test("contains throws in closure") {
do {
_ = try await [1, 2, 3].async
.contains {
if $0 == 2 { throw Failure(value: 42) }
return $0 == 3
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("contains throws upstream") {
do {
_ = try await [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.contains {
return $0 == 3
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("all satisfy true") {
let result = await [1, 2, 3].async.allSatisfy { $0 < 10 }
expectTrue(result)
}
AsyncSequenceTests.test("all satisfy throws in closure") {
do {
_ = try await [1, 2, 3].async
.allSatisfy {
if $0 == 2 { throw Failure(value: 42) }
return $0 < 10
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("all satisfy throws upstream") {
do {
_ = try await [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.allSatisfy {
return $0 < 10
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("all satisfy false") {
let result = await [1, 2, 3].async.allSatisfy { $0 > 10 }
expectFalse(result)
}
AsyncSequenceTests.test("all satisfy empty") {
let result = await [Int]().async.allSatisfy { $0 > 10 }
expectTrue(result)
}
AsyncSequenceTests.test("contains true") {
let result = await [1, 2, 3].async.contains(2)
expectTrue(result)
}
AsyncSequenceTests.test("contains false") {
let result = await [1, 2, 3].async.contains(4)
expectFalse(result)
}
AsyncSequenceTests.test("contains throws upstream") {
do {
_ = try await [1, 2, 3].async.throw(Failure(value: 42), on: 2).contains(4)
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("contains empty") {
let result = await [Int]().async.contains(4)
expectFalse(result)
}
AsyncSequenceTests.test("first found") {
let result = await [1, 2, 3].async.first { $0 > 1 }
expectEqual(result, 2)
}
AsyncSequenceTests.test("first throws in closure") {
do {
_ = try await [1, 2, 3].async
.first {
if $0 == 2 { throw Failure(value: 42) }
return $0 > 2
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("first throws upstream") {
do {
_ = try await [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.first {
return $0 > 2
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("first empty") {
let result = await [Int]().async.first { $0 > 1 }
expectEqual(result, nil)
}
AsyncSequenceTests.test("min by found") {
let result = await [1, 2, 3].async.min { $0 < $1 }
expectEqual(result, 1)
}
AsyncSequenceTests.test("min by throws in closure") {
do {
_ = try await [1, 2, 3].async
.min {
if $0 == 2 { throw Failure(value: 42) }
return $0 < $1
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("min by throws upstream") {
do {
_ = try await [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.min {
return $0 < $1
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("min by empty") {
let result = await [Int]().async.min { $0 < $1 }
expectEqual(result, nil)
}
AsyncSequenceTests.test("max by found") {
let result = await [1, 2, 3].async.max { $0 < $1 }
expectEqual(result, 3)
}
AsyncSequenceTests.test("max by throws in closure") {
do {
_ = try await [1, 2, 3].async
.max {
if $0 == 2 { throw Failure(value: 42) }
return $0 < $1
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("max by throws upstream") {
do {
_ = try await [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.max {
return $0 < $1
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("max by empty") {
let result = await [Int]().async.max { $0 < $1 }
expectEqual(result, nil)
}
AsyncSequenceTests.test("min found") {
let result = await [1, 2, 3].async.min()
expectEqual(result, 1)
}
AsyncSequenceTests.test("min empty") {
let result = await [Int]().async.min()
expectEqual(result, nil)
}
AsyncSequenceTests.test("max found") {
let result = await [1, 2, 3].async.max()
expectEqual(result, 3)
}
AsyncSequenceTests.test("max empty") {
let result = await [Int]().async.max()
expectEqual(result, nil)
}
AsyncSequenceTests.test("collect") {
let result = await [1, 2, 3].async.collect()
expectEqual(result, [1, 2, 3])
}
AsyncSequenceTests.test("collect throws upstream") {
do {
_ = try await [1, 2, 3].async.throw(Failure(value: 42), on: 2).collect()
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
}
AsyncSequenceTests.test("collect empty") {
let result = await [Int]().async.collect()
expectEqual(result, [])
}
var AsyncCompactMapTests = TestSuite("AsyncCompactMap")
AsyncCompactMapTests.test("non nil values") {
let result = await [1, 2, 3].async.compactMap { $0 }.collect()
expectEqual(result, [1, 2, 3])
}
AsyncCompactMapTests.test("nil values") {
let result = await [1, nil, 2, nil, 3, nil].async
.compactMap { $0 }.collect()
expectEqual(result, [1, 2, 3])
}
AsyncCompactMapTests.test("non nil values async") {
let result = await [1, 2, 3].async
.compactMap { await asynchronous($0) }.collect()
expectEqual(result, [1, 2, 3])
}
AsyncCompactMapTests.test("nil values async") {
let result = await [1, nil, 2, nil, 3, nil].async
.compactMap { await asynchronous($0) }.collect()
expectEqual(result, [1, 2, 3])
}
AsyncCompactMapTests.test("non nil values with throw") {
do {
let result = try await [1, 2, 3].async
.compactMap { try throwing($0) }.collect()
expectEqual(result, [1, 2, 3])
} catch {
expectUnreachable()
}
}
AsyncCompactMapTests.test("nil values with throw") {
do {
let result = try await [1, nil, 2, nil, 3, nil].async
.compactMap { try throwing($0) }.collect()
expectEqual(result, [1, 2, 3])
} catch {
expectUnreachable()
}
}
AsyncCompactMapTests.test("non nil values with async throw") {
do {
let result = try await [1, 2, 3].async
.compactMap { try await asynchronousThrowing($0) }.collect()
expectEqual(result, [1, 2, 3])
} catch {
expectUnreachable()
}
}
AsyncCompactMapTests.test("nil values with async throw") {
do {
let result = try await [1, nil, 2, nil, 3, nil].async
.compactMap { try await asynchronousThrowing($0) }.collect()
expectEqual(result, [1, 2, 3])
} catch {
expectUnreachable()
}
}
AsyncCompactMapTests.test("throwing in closure") {
let seq = [1, nil, 2, nil, 3, nil].async
.compactMap { value throws -> Int? in
if value == 2 {
throw Failure(value: 42)
}
return value
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncCompactMapTests.test("throwing upstream") {
let seq = [1, nil, 2, nil, 3, nil].async
.throw(Failure(value: 42), on: 2)
.compactMap { value throws -> Int? in
return value
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
var AsyncMapSequenceTests = TestSuite("AsyncMapSequence")
AsyncMapSequenceTests.test("map values") {
let results = await [1, 2, 3].async.map { "\($0)" }.collect()
expectEqual(results, ["1", "2", "3"])
}
AsyncMapSequenceTests.test("map empty") {
let results = await [Int]().async.map { "\($0)" }.collect()
expectEqual(results, [])
}
AsyncMapSequenceTests.test("map throwing in closure") {
let seq = [1, 2, 3].async
.map { value throws -> String in
if value == 2 {
throw Failure(value: 42)
}
return "\(value)"
}
var it = seq.makeAsyncIterator()
var results = [String]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, ["1"])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncMapSequenceTests.test("map throwing upstream") {
let seq = [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.map { value throws -> String in
return "\(value)"
}
var it = seq.makeAsyncIterator()
var results = [String]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, ["1"])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
var AsyncFilterSequenceTests = TestSuite("AsyncFilterSequence")
AsyncFilterSequenceTests.test("filter out one item") {
let results = await [1, 2, 3].async.filter { $0 % 2 != 0 } .collect()
expectEqual(results, [1, 3])
}
AsyncFilterSequenceTests.test("filter out one item throwing") {
do {
let results = try await [1, 2, 3].async
.filter { try throwing($0 % 2 != 0) }
.collect()
expectEqual(results, [1, 3])
} catch {
expectUnreachable()
}
}
AsyncFilterSequenceTests.test("filter out one item throwing async") {
do {
let results = try await [1, 2, 3].async
.filter { try await asynchronousThrowing($0 % 2 != 0) }
.collect()
expectEqual(results, [1, 3])
} catch {
expectUnreachable()
}
}
AsyncFilterSequenceTests.test("filter out two items") {
let results = await [1, 2, 3].async.filter { $0 % 2 == 0 } .collect()
expectEqual(results, [2])
}
AsyncFilterSequenceTests.test("filter out all items") {
let results = await [1, 2, 3].async.filter { _ in return false } .collect()
expectEqual(results, [Int]())
}
AsyncFilterSequenceTests.test("filter out no items") {
let results = await [1, 2, 3].async.filter { _ in return true } .collect()
expectEqual(results, [1, 2, 3])
}
AsyncFilterSequenceTests.test("filter throwing in closure") {
let seq = [1, 2, 3].async
.filter {
if $0 == 2 { throw Failure(value: 42) }
return $0 % 2 != 0
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncFilterSequenceTests.test("filter throwing upstream") {
let seq = [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.filter {
return $0 % 2 != 0
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
var AsyncDropWhileSequenceTests = TestSuite("AsyncDropWhileSequence")
AsyncDropWhileSequenceTests.test("drop one") {
let results = await [1, 2, 3].async.drop { value -> Bool in
return value == 1
}.collect()
expectEqual(results, [2, 3])
}
AsyncDropWhileSequenceTests.test("drop throwing in closure") {
let seq = [1, 2, 3].async
.drop {
if $0 == 2 { throw Failure(value: 42) }
return $0 == 1
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncDropWhileSequenceTests.test("drop throwing upstream") {
let seq = [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.drop {
return $0 == 1
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncDropWhileSequenceTests.test("drop one async") {
let results = await [1, 2, 3].async.drop { value async -> Bool in
return await asynchronous(value == 1)
}.collect()
expectEqual(results, [2, 3])
}
AsyncDropWhileSequenceTests.test("drop one throws") {
do {
let results = try await [1, 2, 3].async.drop { value throws -> Bool in
return try throwing(value == 1)
}.collect()
expectEqual(results, [2, 3])
} catch {
expectUnreachable()
}
}
AsyncDropWhileSequenceTests.test("drop one throws async") {
do {
let results = try await [1, 2, 3].async.drop { value async throws -> Bool in
return try await asynchronousThrowing(value == 1)
}.collect()
expectEqual(results, [2, 3])
} catch {
expectUnreachable()
}
}
AsyncDropWhileSequenceTests.test("drop none") {
let results = await [1, 2, 3].async.drop { _ in return false }.collect()
expectEqual(results, [1, 2, 3])
}
AsyncDropWhileSequenceTests.test("drop all") {
let results = await [1, 2, 3].async.drop { _ in return true }.collect()
expectEqual(results, [])
}
AsyncDropWhileSequenceTests.test("drop stops") {
let results = await [1, 2, 3].async.drop { value in
return value == 1 || value == 3
}.collect()
expectEqual(results, [2, 3])
}
var AsyncDropFirstSequenceTests = TestSuite("AsyncDropFirstSequence")
AsyncDropFirstSequenceTests.test("drop 1") {
let results = await [1, 2, 3].async.dropFirst().collect()
expectEqual(results, [2, 3])
}
AsyncDropFirstSequenceTests.test("drop 2") {
let results = await [1, 2, 3].async.dropFirst(2).collect()
expectEqual(results, [3])
}
AsyncDropFirstSequenceTests.test("drop 0") {
let results = await [1, 2, 3].async.dropFirst(0).collect()
expectEqual(results, [1, 2, 3])
}
var AsyncPrefixSequenceTests = TestSuite("AsyncPrefixSequence")
AsyncPrefixSequenceTests.test("prefix satisfied") {
let results = await [1, 2, 3].async.prefix(2).collect()
expectEqual(results, [1, 2])
}
AsyncPrefixSequenceTests.test("prefix partial satisfied") {
let results = await [1, 2, 3].async.prefix(4).collect()
expectEqual(results, [1, 2, 3])
}
AsyncPrefixSequenceTests.test("prefix 0") {
let results = await [1, 2, 3].async.prefix(0).collect()
expectEqual(results, [])
}
var AsyncPrefixWhileSequenceTests = TestSuite("AsyncPrefixWhileSequence")
/* DISABLED: this deadlocks for some unknown reason
AsyncPrefixWhileSequenceTests.test("prefix while") {
let results = await [1, 2, 3].async
.prefix { $0 < 3 }
.collect()
expectEqual(results, [1, 2])
}
*/
var AsyncFlatMapSequenceTests = TestSuite("AsyncFlatMapSequence")
AsyncFlatMapSequenceTests.test("flat map") {
let results = await [1, 2, 3].async.flatMap { ($0..<4).async }.collect()
let expected = [1, 2, 3].flatMap { $0..<4 }
expectEqual(results, expected)
}
AsyncFlatMapSequenceTests.test("flat map throwing in closure") {
let seq = [1, 2, 3].async
.flatMap { (value: Int) throws -> AsyncLazySequence<Range<Int>> in
if value == 2 { throw Failure(value: 42) }
return (value..<4).async
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1, 2, 3])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncFlatMapSequenceTests.test("flat map throwing upstream") {
let seq = [1, 2, 3].async
.throw(Failure(value: 42), on: 2)
.flatMap {
return ($0..<4).async
}
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1, 2, 3])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncFlatMapSequenceTests.test("flat map throwing inner") {
@Sendable func buildSubSequence(
_ start: Int
) -> AsyncThrowingMapSequence<AsyncLazySequence<Range<Int>>, Int> {
return (start..<4).async.map { (value: Int) throws -> Int in
if value == 2 { throw Failure(value: 42) }
return value
}
}
let seq = [1, 2, 3].async
.flatMap(buildSubSequence)
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
AsyncFlatMapSequenceTests.test("flat map throwing inner on throwing outer") {
@Sendable func buildSubSequence(
_ start: Int
) throws -> AsyncThrowingMapSequence<AsyncLazySequence<Range<Int>>, Int> {
return (start..<4).async.map { (value: Int) throws -> Int in
if value == 2 { throw Failure(value: 42) }
return value
}
}
let seq = [1, 2, 3].async
.flatMap(buildSubSequence)
var it = seq.makeAsyncIterator()
var results = [Int]()
do {
while let value = try await it.next() {
results.append(value)
}
expectUnreachable()
} catch {
expectEqual(error as? Failure, Failure(value: 42))
}
expectEqual(results, [1])
do {
let result = try await it.next()
expectNil(result)
} catch {
expectUnreachable()
}
}
}
await runAllTestsAsync()
}
}
| true
|
3ad3bde8ab1920aab1df4b8010c08b81f695301d
|
Swift
|
shainedl/Freeze
|
/Freeze/ViewController.swift
|
UTF-8
| 1,246
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// freeze
//
// Created by Anmol Seth on 3/12/19.
// Copyright © 2019 freeze. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
@IBOutlet var phoneNumberField: UITextField!
//@IBOutlet var messageField: UITextField!
@IBAction func sendData(sender: AnyObject) {
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters: Parameters = [
"To": phoneNumberField.text ?? "",
//"Body": messageField.text ?? ""
"Body": "Shaine Leibowitz is in danger! You can give her a call and find her location. https://goo.gl/maps/9e8ZmsDLW9hUjw619"
]
Alamofire.request("http://localhost:5000/sms", method: .post, parameters: parameters, headers: headers).response { response in
print(response)
}
}
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.
}
}
| true
|
9f7c2dcaead78591258e4ccec5b6798abb230564
|
Swift
|
ahartwel/PersistentSwift
|
/PersistentSwift/Classes/Background.swift
|
UTF-8
| 1,338
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// Background.swift
// PersistentSwift
//
// Created by Alex Hartwell on 9/6/16.
// Copyright © 2016 SWARM. All rights reserved.
//
import Foundation
class Background {
static func runInBackground(_ inBackground: @escaping (() -> ())) {
let priority = DispatchQueue.GlobalQueuePriority.background;
DispatchQueue.global(priority: priority).async {
inBackground()
}
}
static func runInBackgroundAndCallback(_ inBackground: @escaping (() -> ()), callback: @escaping (() -> ())) {
let priority = DispatchQueue.GlobalQueuePriority.background;
DispatchQueue.global(priority: priority).async {
inBackground()
DispatchQueue.main.async {
callback()
}
}
}
static func runInBackgroundAsyncAndCallback(_ inBackground: @escaping (( (() -> ()) ) -> ()), callback: @escaping (() -> ())) {
let priority = DispatchQueue.GlobalQueuePriority.background;
DispatchQueue.global(priority: priority).async {
inBackground({
DispatchQueue.main.async {
callback();
}
})
}
}
static func runInMainThread(_ closure: @escaping (() -> ())) {
DispatchQueue.main.async(execute: closure);
}
}
| true
|
c26496936b048c6c0cf5f8a4bd07abd579c25fb9
|
Swift
|
ryanplitt/DungeonMessenger
|
/DungeonMessenger/Message.swift
|
UTF-8
| 1,637
| 2.65625
| 3
|
[] |
no_license
|
//
// Message.swift
// DungeonMessenger
//
// Created by Ryan Plitt on 8/9/16.
// Copyright © 2016 Ryan Plitt. All rights reserved.
//
import Foundation
import CloudKit
class Message {
static let typeKey = "Message"
static let textKey = "Text"
static let timestampKey = "Timestamp"
static let senderKey = "SenderKey"
static let conversationKey = "Conversation"
var ckRecord: CKRecord {
let record = CKRecord(recordType: Message.typeKey)
record.setValue(text, forKey: Message.textKey)
record.setValue(timestamp, forKey: Message.timestampKey)
record.setValue(sender, forKey: Message.senderKey)
record.setValue(conversation, forKey: Message.conversationKey)
return record
}
let text: String
let timestamp: NSDate
let sender: CKReference
let conversation: CKReference
init(text: String, timestamp: NSDate = NSDate(), sender: CKReference, conversation: CKReference){
self.text = text
self.timestamp = timestamp
self.sender = sender
self.conversation = conversation
}
convenience init?(ckRecord: CKRecord) {
guard ckRecord.recordType == Message.typeKey else {return nil}
guard let text = ckRecord[Message.textKey] as? String,
let timestamp = ckRecord[Message.timestampKey] as? NSDate,
let sender = ckRecord[Message.senderKey] as? CKReference,
let conversation = ckRecord[Message.conversationKey] as? CKReference else {return nil}
self.init(text: text, timestamp: timestamp, sender: sender, conversation: conversation)
}
}
| true
|
cac60a814020ef57202bd15768fee4c4a9a48dcf
|
Swift
|
seirifat/RealmDbRelationship
|
/RealmDbRelationship/Models/Product.swift
|
UTF-8
| 1,857
| 3.15625
| 3
|
[] |
no_license
|
//
// Product.swift
// Model Generated using http://www.jsoncafe.com/
// Created on January 25, 2019
import Foundation
import SwiftyJSON
import RealmSwift
class Product: Object {
@objc dynamic var id: String?
@objc dynamic var name: String?
@objc dynamic var type: String?
var vehiclesList: List<Vehicle> = List<Vehicle>()
var originalsList: List<Original> = List<Original>()
override public static func primaryKey() -> String? {
return "id"
}
public static func with(realm: Realm, json: JSON) -> Product? {
let identifier = json["id"].stringValue
if identifier == "" {
return nil
}
var obj = realm.object(ofType: Product.self, forPrimaryKey: identifier)
if obj == nil {
obj = Product()
obj?.id = identifier
} else {
obj = Product(value: obj!)
}
if json["name"].exists() {
obj?.name = json["name"].string
}
if json["type"].exists() {
obj?.type = json["type"].string
}
if json["vehicles"].exists() {
obj?.vehiclesList.removeAll()
for itemJson in json["vehicles"].arrayValue {
if let item = Vehicle.with(json: itemJson) {
obj?.vehiclesList.append(item)
}
}
}
if json["originals"].exists() {
obj?.originalsList.removeAll()
for itemJson in json["originals"].arrayValue {
if let item = Original.with(json: itemJson) {
obj?.originalsList.append(item)
}
}
}
return obj
}
public static func with(json: JSON) -> Product? {
return with(realm: try! Realm(), json: json)
}
}
| true
|
61c08ffb8d6da658198d01bc33f623ea288aa25c
|
Swift
|
binbin0915/BanTang
|
/BanTang/BanTang/Classes/Account/Controller/BTSettingController.swift
|
UTF-8
| 2,371
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// BTSettingController.swift
// BanTang
//
// Created by 张灿 on 16/5/30.
// Copyright © 2016年 张灿. All rights reserved.
//
import UIKit
class BTSettingController: UITableViewController {
//清理缓存
@IBOutlet weak var cleanLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//背景色即分割线颜色
tableView.backgroundColor = UIColor(red: 244 / 255.0, green: 244 / 255.0, blue: 244 / 255.0, alpha: 1.0)
tableView.sectionFooterHeight = 1
cleanLabel.text = sizeString()
}
//夜间模式
@IBAction func nightClick(sender: UISwitch) {
debugPrint("夜间模式")
}
}
extension BTSettingController {
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(indexPath.section,indexPath.row)
if indexPath.section == 1 && indexPath.row == 2 {
clean()
cleanLabel.text = sizeString()
}
}
}
//清理缓存业务逻辑
extension BTSettingController {
//拼接缓存大小
func sizeString() -> String {
//获取cache文件夹路径
let cachePath: String = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
//获取缓存大小
let size: NSInteger = ZCFileManager.getSizeOfDirectoryPath(cachePath)
var str: String = "0.00K"
//判断尺寸大小,拼接不同显示方式
if size > 1000 * 1000 {
let sizeMB: CGFloat = CGFloat(size) / 1000.0 / 1000.0
str = "\(String(format: "%.1f", sizeMB))MB"
} else if size > 1000 {
let sizeKB: CGFloat = CGFloat(size) / 1000.0
str = "\(String(format: "%.1f", sizeKB))KB"
} else if size > 0 {
str = "\(size)dB"
}
return str
}
//清理缓存
func clean() {
//获取cachelujing
let cachePath: String = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
//清空缓存
ZCFileManager.removeDirectoryPath(cachePath)
}
}
| true
|
bef94c11355bf08caf547335d9050e9eb43c8d3d
|
Swift
|
akolov/GoldenTiler
|
/GoldenSpiralFilter/GoldenSpiralFilter/GoldenSpiralFilter.swift
|
UTF-8
| 3,475
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// GoldenSpiralFilter.swift
// GoldenTiler
//
// Created by Alexander Kolov on 10/5/15.
// Copyright © 2015 Alexander Kolov. All rights reserved.
//
import Foundation
import ImageIO
import UIKit
let φ: CGFloat = (1 + sqrt(5.0)) / 2.0
public protocol GoldenSpiralFilter: NSObjectProtocol {
init()
var inputImage: UIImage? { get set }
var colorSpace: CGColorSpaceRef? { get }
var outputImage: UIImage? { get }
var outputImageSize: CGSize { get }
var canProcessImage: Bool { get }
var context: CIContext { get }
func tiles() -> AnyGenerator<CGRect>
func imageCropRect(image sourceImage: CIImage, toDimension dimension: CGFloat) -> CGRect
}
public extension GoldenSpiralFilter {
public func tiles() -> AnyGenerator<CGRect> {
let dimension = min(outputImageSize.width, outputImageSize.height)
let portrait = outputImageSize.height > outputImageSize.width
var transform = CGAffineTransformIdentity
// Transformations needed because context origin is (bottom, left)
if portrait {
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
transform = CGAffineTransformTranslate(transform, -outputImageSize.height, 0)
}
else {
transform = CGAffineTransformTranslate(transform, 0, outputImageSize.height)
transform = CGAffineTransformScale(transform, 1, -1)
}
var x: CGFloat = 0, y: CGFloat = 0, counter = 0
return anyGenerator {
let a = round(CGFloat(dimension) / pow(φ, CGFloat(counter)))
let b = round(CGFloat(dimension) / pow(φ, CGFloat(counter) + 1))
// Bail out when significant part is less than 2 pixels
if a < 2 {
return .None
}
var origin: CGPoint!
switch counter % 4 {
case 0:
origin = CGPoint(x: x, y: y)
x += round(a + b)
case 1:
origin = CGPoint(x: x - a, y: y)
y += round(a + b)
case 2:
origin = CGPoint(x: x - a, y: y - a)
x -= round(a + b)
case 3:
origin = CGPoint(x: x, y: y - a)
y -= round(a + b)
default:
break
}
counter++
let rect = CGRect(origin: origin, size: CGSize(width: a, height: a))
return CGRectApplyAffineTransform(rect, transform)
}
}
func imageCropRect(image sourceImage: CIImage, toDimension dimension: CGFloat) -> CGRect {
let detector = CIDetector(ofType: CIDetectorTypeFace, context: context, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
let orientation: AnyObject = sourceImage.properties[String(kCGImagePropertyOrientation)] ?? 1
let features = detector.featuresInImage(sourceImage, options: [CIDetectorImageOrientation: orientation])
let cropRect: CGRect
if features.count == 0 {
cropRect = CGRect(x: (sourceImage.extent.width - dimension) / 2.0, y: (sourceImage.extent.height - dimension) / 2.0, width: dimension, height: dimension)
}
else {
// We've detected some faces, set crop rect to center around faces
var facesRect = features.map { $0.bounds }.reduce(features.first!.bounds, combine: CGRectUnion)
facesRect.insetInPlace(dx: (dimension - facesRect.width) / -2.0, dy: (dimension - facesRect.height) / -2.0)
facesRect.offsetInPlace(dx: facesRect.minX < 0 ? -facesRect.minX : 0, dy: facesRect.minY < 0 ? -facesRect.minY : 0)
facesRect.offsetInPlace(dx: dimension - facesRect.maxX, dy: dimension - facesRect.maxY)
cropRect = facesRect
}
return cropRect
}
}
| true
|
35cae727358675700c656968abe8f21abd36d075
|
Swift
|
MartonioJunior/JurassicRun-Public
|
/JurrasicRun Shared/Extensions/Swift/CGRect+Operations.swift
|
UTF-8
| 359
| 2.546875
| 3
|
[] |
no_license
|
//
// CGRect+Operations.swift
// JurrasicRun iOS
//
// Created by Martônio Júnior on 18/12/19.
// Copyright © 2019 martonio. All rights reserved.
//
import CoreGraphics
extension CGRect {
func min() -> CGPoint {
return CGPoint(x: self.minX, y: self.minY)
}
func max() -> CGPoint {
return CGPoint(x: self.maxX, y: self.maxY)
}
}
| true
|
e905ea2090b2449c8809ede75735b122000d4a79
|
Swift
|
GlebRadchenko/LivePhotoExtractor
|
/Photo Cropper/Extensions/UIImage+Watermark.swift
|
UTF-8
| 2,095
| 2.78125
| 3
|
[] |
no_license
|
//
// UIImage+Watermark.swift
// Photo Cropper
//
// Created by Anton Poltoratskyi on 09.01.17.
// Copyright © 2017 Gleb Radchenko. All rights reserved.
//
import UIKit
extension UIImage {
func addingWatermark(text: String, font: UIFont, color: UIColor) -> UIImage {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .right
let attributes = [NSFontAttributeName: font,
NSForegroundColorAttributeName: color,
NSParagraphStyleAttributeName: paragraphStyle]
// Calculate needed text bounds
let horizontalOffset: CGFloat = 16.0
let verticalOffset: CGFloat = 16.0
let maxSize = CGSize(width: self.size.width - horizontalOffset * 2, height: self.size.height)
let contentBounds = (text as NSString).boundingRect(with: maxSize,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attributes,
context: nil)
//Drawing
let watermarkRect = CGRect(x: horizontalOffset,
y: self.size.height - contentBounds.size.height - verticalOffset,
width: self.size.width - horizontalOffset * 2,
height: self.size.height - verticalOffset * 2)
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
(text as NSString).draw(with: watermarkRect,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attributes, context: nil)
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage ?? self
}
}
| true
|
c56c2e5c308eb0755f40924211f721da248ecc29
|
Swift
|
carlneto/Indexer
|
/Sources/Indexer/CharIndex.swift
|
UTF-8
| 10,497
| 2.96875
| 3
|
[] |
no_license
|
import Foundation
public class CharIndex {
public enum ResourceType: Int { case file = 1, dict }
public typealias Resource = (type: CharIndex.ResourceType, name: String)
typealias Resources = [CharIndex.Resource]
public typealias Reference = (excerpt: String, location: Int, resource: CharIndex.Resource)
public typealias References = [CharIndex.Reference]
typealias Entry = (word: String, references: CharIndex.References)
typealias Entries = [CharIndex.Entry]
static let nullChar = Character("\0")
static let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz0123456789-'")
static let notAllowed = CharIndex.allowed.inverted
static let referenceSize = 30
let insertions = Atomic(0)
private lazy var operationQueue: OperationQueue = {
let operation = OperationQueue()
operation.name = "CharIndex.operationQueue"
operation.maxConcurrentOperationCount = 1
return operation
}()
private(set) var char = CharIndex.nullChar
var usage = 0
var references = CharIndex.References()
var sibling: CharIndex?
var child: CharIndex?
init() {}
init(char: Character) {
self.char = char
}
init(aCharIndex: CharIndex) {
self.char = aCharIndex.char
self.usage = aCharIndex.usage
self.references = aCharIndex.references
self.sibling = aCharIndex.sibling
self.child = aCharIndex.child
}
func insert(text: String, nIndex: Set<String>, resource: CharIndex.Resource, master: IndexController?) -> Int {
let group = text.words(simplify: true, referenceSize: CharIndex.referenceSize)
var sum = 0
for item in group {
guard item.token.count > 1 else { continue }
var location = 0
for word in item.token.components(separatedBy: CharIndex.notAllowed) {
let loc = location + item.location
location += word.count + 1
guard word.count > 1, !nIndex.contains(word) else {
continue
}
self.insert(word: word, reference: (excerpt: item.excerpt, location: loc, resource: resource), master: master)
sum += 1
}
}
return sum
}
private func insert(word: String, reference: CharIndex.Reference, master: IndexController?) {
self.insertions.increase()
self.operationQueue.addOperation {
self.insert(word: word, reference: reference, parent: nil)
if self.insertions.decreased == 0 {
master?.didInsert()
}
}
}
private func insert(word: String, reference: CharIndex.Reference, parent: CharIndex?) {
var letters = word
let chr = letters.removeFirst()
var actual = self
if actual.char == chr {
actual.usage += 1
} else if actual.char == CharIndex.nullChar {
actual.char = chr
actual.usage += 1
} else {
var siblingCharIndex = actual.sibling
var previous = [CharIndex]()
while let aCharIndex = siblingCharIndex {
previous.append(actual)
actual = aCharIndex
if actual.char == chr {
break
}
siblingCharIndex = siblingCharIndex?.sibling
}
if siblingCharIndex == nil {
actual.sibling = CharIndex(char: chr)
previous.append(actual)
actual = actual.sibling!
}
actual.usage += 1
if let last = previous.last, last.usage < actual.usage {
var penultCharIndex: CharIndex?
for priorCharIndex in previous {
if priorCharIndex.usage < actual.usage {
last.sibling = actual.sibling
actual.sibling = priorCharIndex
if penultCharIndex == nil {
if parent != nil {
parent?.child = actual
} else {
actual = self.head(actual)
}
} else {
penultCharIndex?.sibling = actual
}
break
}
penultCharIndex = priorCharIndex
}
}
}
guard let aChar = letters.first else {
actual.references.append(reference)
return
}
if actual.child == nil {
actual.child = CharIndex(char: aChar)
}
actual.child?.insert(word: letters, reference: reference, parent: actual)
}
private func head(_ head: CharIndex) -> CharIndex {
let selfCopy = CharIndex(aCharIndex: self)
self.char = head.char
self.usage = head.usage
self.references = head.references
self.sibling = selfCopy
self.child = head.child
return self
}
func remove(resource: CharIndex.Resource, master: IndexController?) {
guard !resource.name.isEmpty else { return }
self.operationQueue.addOperation {
let removed = self.remove(resource: resource)
print("removed: \(removed) resource: \(resource.name)")
self.balance()
master?.didInsert()
}
}
private func remove(resource: CharIndex.Resource) -> Int {
var usages = self.child?.remove(resource: resource) ?? 0
var toRemove = [Int]()
for (i, selfReference) in self.references.enumerated() {
if selfReference.resource.name == resource.name {
toRemove.append(i)
}
}
usages += toRemove.count
for i in toRemove.reversed() {
self.references.remove(at: i)
}
self.usage -= usages
return usages + (self.sibling?.remove(resource: resource) ?? 0)
}
func balance(master: IndexController?) {
self.operationQueue.addOperation {
self.balance()
master?.didInsert()
}
}
private func balance() {
let selfCopy = CharIndex(aCharIndex: self)
let head = selfCopy.balanced()
if self.char != head.char {
self.char = head.char
self.usage = head.usage
self.references = head.references
self.sibling = head.sibling
self.child = head.child
}
}
private func balanced() -> CharIndex {
var root = self
guard root.sibling != nil else {
root.child = root.child?.balanced()
return root
}
var siblings = [root]
var actual = root.sibling
var siblingUsage = root.usage
var needSort = false
while let sibling = actual {
if !needSort, siblingUsage < sibling.usage {
needSort = true
}
siblingUsage = sibling.usage
siblings.append(sibling)
actual = actual?.sibling
}
if needSort {
siblings.sort(by: { $0.usage > $1.usage } )
for (i, aSibling) in siblings.enumerated() {
aSibling.sibling = siblings[at: i + 1]
}
root = siblings.first ?? root
}
actual = root
while let charIndex = actual {
charIndex.child = charIndex.child?.balanced()
actual = actual?.sibling
}
return root
}
func find(word: String, suffixes: Bool) -> CharIndex.Entry {
let letters = word.simple
guard !letters.isEmpty else {
return (word: "", references: [])
}
return (word: letters, references: self.find(chars: letters, enlarged: suffixes))
}
private func find(chars: String, enlarged: Bool) -> CharIndex.References {
var letters = chars
let chr = letters.removeFirst()
var actual: CharIndex? = self
while actual != nil {
if actual?.char == chr {
if letters.isEmpty {
var refs = actual?.references ?? []
if enlarged {
for entry in actual?.child?.inserted().entries ?? [] {
refs += entry.references
}
}
return refs
} else {
return actual?.child?.find(chars: letters, enlarged: enlarged) ?? []
}
}
actual = actual?.sibling
}
return []
}
func letters(until level: Int) -> Set<String> {
var lettersArr = Set<String>()
self.letters(chars: "", level: level, lettersArr: &lettersArr)
return lettersArr
}
private func letters(chars: String, level: Int, lettersArr: inout Set<String>) {
let str = "\(chars)\(self.char)"
lettersArr.insert(str)
self.sibling?.letters(chars: chars, level: level, lettersArr: &lettersArr)
guard level > 1 else { return }
self.child?.letters(chars: str, level: level - 1, lettersArr: &lettersArr)
}
func inserted() -> (entries: CharIndex.Entries, total: Int, biggestWord: String) {
var wordsCount = 0
var wordsIndexed = CharIndex.Entries()
var biggestWord = ""
self.inserted(chars: "", wordsCount: &wordsCount, wordsIndexed: &wordsIndexed, biggestWord: &biggestWord)
return (wordsIndexed, wordsCount, biggestWord)
}
private func inserted(chars: String, wordsCount: inout Int, wordsIndexed: inout CharIndex.Entries, biggestWord: inout String) {
let str = "\(chars)\(self.char)"
let wordCount = self.references.count
if wordCount > 0 {
wordsCount += wordCount
wordsIndexed.append(CharIndex.Entry(word: str, references: self.references))
if str.count > biggestWord.count {
biggestWord = str
}
}
self.sibling?.inserted(chars: chars, wordsCount: &wordsCount, wordsIndexed: &wordsIndexed, biggestWord: &biggestWord)
self.child?.inserted(chars: str, wordsCount: &wordsCount, wordsIndexed: &wordsIndexed, biggestWord: &biggestWord)
}
}
| true
|
e319c01b3213f1b74df8b5995484ecc7af6c509d
|
Swift
|
pavankovurru/BullsEye
|
/BullsEye/Models/Constants.swift
|
UTF-8
| 667
| 2.546875
| 3
|
[] |
no_license
|
//
// Models.swift
// BullsEye
//
// Created by Pavan Kovurru on 2/21/21.
//
import Foundation
import UIKit
enum Constants {
enum General {
public static let strokeWidth = CGFloat(2.0)
public static let roundedViewLength = CGFloat(56.0)
public static let roundedRectViewWidth = CGFloat(68.0)
public static let roundedRectViewHeight = CGFloat(56.0)
public static let roundedRectCornerRadius = CGFloat(21.0)
}
enum LeaderBoard{
public static let scoreColumnWidth = CGFloat(50.0)
public static let dateColumnWidth = CGFloat(170.0)
public static let maxRowWidth = CGFloat(480.0)
}
}
| true
|
3e8293130e4a9e4d91c9825905b16a7a7c7356c8
|
Swift
|
uias/Tabman
|
/Sources/Tabman/TabmanViewController.swift
|
UTF-8
| 13,860
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// TabmanViewController.swift
// Tabman
//
// Created by Merrick Sapsford on 17/02/2017.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
import Pageboy
/// A view controller which embeds a `PageboyViewController` and provides the ability to add bars which
/// can directly manipulate, control and display the status of the page view controller. It also handles
/// automatic insetting of child view controller contents.
open class TabmanViewController: PageboyViewController, PageboyViewControllerDelegate, TMBarDelegate {
// MARK: Types
/// Location of the bar in the view controller.
///
/// - top: Pin to the top of the safe area.
/// - bottom: Pin to the bottom of the safe area.
/// - navigationItem: Set as a `UINavigationItem.titleView`.
/// - custom: Add the view to a custom view and provide custom layout.
/// If no layout is provided, all edge anchors will be constrained
/// to the superview.
public enum BarLocation {
case top
case bottom
case navigationItem(item: UINavigationItem)
case custom(view: UIView, layout: ((UIView) -> Void)?)
}
// MARK: Views
internal let topBarContainer = UIStackView()
internal let bottomBarContainer = UIStackView()
/// All bars that have been added to the view controller.
public private(set) var bars = [TMBar]()
// MARK: Layout
private var requiredInsets: Insets?
private let insetter = AutoInsetter()
/// Whether to automatically adjust child view controller content insets with bar geometry.
///
/// This must be set before `viewDidLoad`, setting it after this point will result in no change.
/// Default is `true`.
public var automaticallyAdjustsChildInsets: Bool = true
@available(*, unavailable)
open override var automaticallyAdjustsScrollViewInsets: Bool {
didSet {}
}
/// The insets that are required to safely layout content between the bars
/// that have been added.
///
/// This will only take account of bars that are added to the `.top` or `.bottom`
/// locations - bars that are added to custom locations are responsible for handling
/// their own insets.
public var barInsets: UIEdgeInsets {
return requiredInsets?.barInsets ?? .zero
}
/// The layout guide representing the portion of the view controller's view that is not
/// obstructed by bars.
public let barLayoutGuide: UILayoutGuide = {
let guide = UILayoutGuide()
guide.identifier = "barLayoutGuide"
return guide
}()
private var barLayoutGuideTop: NSLayoutConstraint?
private var barLayoutGuideBottom: NSLayoutConstraint?
@available(*, unavailable)
open override var delegate: PageboyViewControllerDelegate? {
didSet {}
}
// MARK: Init
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
super.delegate = self
}
// MARK: Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
if automaticallyAdjustsChildInsets {
insetter.enable(for: self)
}
configureBarLayoutGuide(barLayoutGuide)
layoutContainers(in: view)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setNeedsInsetsUpdate()
}
/// A method for calculating insets that are required to layout content between the bars
/// that have been added.
///
/// One can override this method with their own implementation for custom bar inset calculation, to
/// take advantage of automatic insets updates for all Tabman's pages during its lifecycle.
///
/// - Returns: information about required insets for current state.
open func calculateRequiredInsets() -> Insets {
return Insets.for(self)
}
// MARK: Pageboy
/// :nodoc:
open override func insertPage(at index: PageboyViewController.PageIndex,
then updateBehavior: PageboyViewController.PageUpdateBehavior) {
bars.forEach({ $0.reloadData(at: index...index, context: .insertion) })
super.insertPage(at: index, then: updateBehavior)
}
/// :nodoc:
open override func deletePage(at index: PageboyViewController.PageIndex,
then updateBehavior: PageboyViewController.PageUpdateBehavior) {
bars.forEach({ $0.reloadData(at: index...index, context: .deletion) })
super.deletePage(at: index, then: updateBehavior)
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
willScrollToPageAt index: PageIndex,
direction: NavigationDirection,
animated: Bool) {
let viewController = dataSource?.viewController(for: self, at: index)
setNeedsInsetsUpdate(to: viewController)
if animated {
updateActiveBars(to: CGFloat(index),
direction: direction,
animated: true)
}
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollTo position: CGPoint,
direction: NavigationDirection,
animated: Bool) {
if !animated {
updateActiveBars(to: relativeCurrentPosition,
direction: direction,
animated: false)
}
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didScrollToPageAt index: PageIndex,
direction: NavigationDirection,
animated: Bool) {
updateActiveBars(to: CGFloat(index),
direction: direction,
animated: false)
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didCancelScrollToPageAt index: PageboyViewController.PageIndex,
returnToPageAt previousIndex: PageboyViewController.PageIndex) {
}
/// :nodoc:
open func pageboyViewController(_ pageboyViewController: PageboyViewController,
didReloadWith currentViewController: UIViewController,
currentPageIndex: PageIndex) {
setNeedsInsetsUpdate(to: currentViewController)
guard let pageCount = pageboyViewController.pageCount else {
return
}
bars.forEach({ $0.reloadData(at: 0...pageCount - 1, context: .full) })
}
// MARK: TMBarDelegate
/// :nodoc:
open func bar(_ bar: TMBar,
didRequestScrollTo index: PageboyViewController.PageIndex) {
scrollToPage(.at(index: index), animated: true, completion: nil)
}
}
// MARK: - Bar Layout
extension TabmanViewController {
/// Add a new `TMBar` to the view controller.
///
/// - Parameters:
/// - bar: Bar to add.
/// - dataSource: Data source for the bar.
/// - location: Location of the bar.
public func addBar(_ bar: TMBar,
dataSource: TMBarDataSource,
at location: BarLocation) {
bar.dataSource = dataSource
bar.delegate = self
if bars.contains(where: { $0 === bar }) == false {
bars.append(bar)
}
layoutView(bar, at: location)
updateBar(bar, to: relativeCurrentPosition, animated: false)
if let pageCount = self.pageCount, pageCount > 0 {
bar.reloadData(at: 0...pageCount - 1, context: .full)
}
}
/// Remove a `TMBar` from the view controller.
///
/// - Parameter bar: Bar to remove.
public func removeBar(_ bar: TMBar) {
guard let index = bars.firstIndex(where: { $0 === bar }) else {
return
}
bars.remove(at: index)
bar.removeFromSuperview()
}
private func layoutContainers(in view: UIView) {
topBarContainer.axis = .vertical
view.addSubview(topBarContainer)
topBarContainer.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
topBarContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
topBarContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
topBarContainer.topAnchor.constraint(equalTo: view.safeAreaTopAnchor)
])
bottomBarContainer.axis = .vertical
view.addSubview(bottomBarContainer)
bottomBarContainer.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bottomBarContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
bottomBarContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
bottomBarContainer.bottomAnchor.constraint(equalTo: view.safeAreaBottomAnchor)
])
}
private func layoutView(_ view: UIView,
at location: BarLocation) {
view.removeFromSuperview()
switch location {
case .top:
topBarContainer.addArrangedSubview(view)
case .bottom:
bottomBarContainer.insertArrangedSubview(view, at: 0)
case .custom(let superview, let layout):
superview.addSubview(view)
if layout != nil {
layout?(view)
} else {
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
view.topAnchor.constraint(equalTo: superview.topAnchor),
view.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
view.bottomAnchor.constraint(equalTo: superview.bottomAnchor)
])
}
case .navigationItem(let item):
let container = ViewTitleViewContainer(for: view)
container.frame = CGRect(x: 0.0, y: 0.0, width: 300, height: 50)
container.layoutIfNeeded()
item.titleView = container
}
}
private func configureBarLayoutGuide(_ guide: UILayoutGuide) {
guard barLayoutGuide.owningView == nil else {
return
}
view.addLayoutGuide(barLayoutGuide)
let barLayoutGuideTop = barLayoutGuide.topAnchor.constraint(equalTo: view.topAnchor)
let barLayoutGuideBottom = view.bottomAnchor.constraint(equalTo: barLayoutGuide.bottomAnchor)
NSLayoutConstraint.activate([
barLayoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor),
barLayoutGuideTop,
barLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor),
barLayoutGuideBottom
])
self.barLayoutGuideTop = barLayoutGuideTop
self.barLayoutGuideBottom = barLayoutGuideBottom
}
}
// MARK: - Bar Management
private extension TabmanViewController {
func updateActiveBars(to position: CGFloat?,
direction: NavigationDirection = .neutral,
animated: Bool) {
bars.forEach({ self.updateBar($0, to: position,
direction: direction,
animated: animated) })
}
func updateBar(_ bar: TMBar,
to position: CGFloat?,
direction: NavigationDirection = .neutral,
animated: Bool) {
let position = position ?? 0.0
let capacity = self.pageCount ?? 0
let animation = TMAnimation(isEnabled: animated,
duration: transition?.duration ?? 0.25)
bar.update(for: position,
capacity: capacity,
direction: direction.barUpdateDirection,
animation: animation)
}
}
// MARK: - Insetting
internal extension TabmanViewController {
func setNeedsInsetsUpdate() {
setNeedsInsetsUpdate(to: currentViewController)
}
func setNeedsInsetsUpdate(to viewController: UIViewController?) {
guard viewIfLoaded?.window != nil else {
return
}
let insets = calculateRequiredInsets()
self.requiredInsets = insets
barLayoutGuideTop?.constant = insets.spec.allRequiredInsets.top
barLayoutGuideBottom?.constant = insets.spec.allRequiredInsets.bottom
// Don't inset TabmanViewController using AutoInsetter
if viewController is TabmanViewController {
if viewController?.additionalSafeAreaInsets != insets.spec.additionalRequiredInsets {
viewController?.additionalSafeAreaInsets = insets.spec.additionalRequiredInsets
}
} else {
insetter.inset(viewController, requiredInsetSpec: insets.spec)
}
}
}
| true
|
abe6e6e4f0599215f50783c44c15be7372585971
|
Swift
|
jfosterdavis/Charles
|
/Charles/ColorLibrary.swift
|
UTF-8
| 3,608
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ColorLibrary.swift
// Charles
//
// Created by Jacob Foster Davis on 5/26/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
struct ColorLibrary {
static let Fundamental: [UIColor] = [UIColor.black,
.white,
.red,
.green,
.blue]
static let Primary: [UIColor] = [.red,
.green,
.blue]
///easy includes primary RGB, black, white, and a single combo of R, G, B to each other
static let Easy: [UIColor] = [UIColor.black,
.red,
.yellow,
.green,
.cyan,
.white,
.white, //black and white are asy to achieve so put a few of them in here
.black,
.blue,
.magenta
]
//values for RGB can only be 1, 0, or 0.5
static let Medium: [UIColor] = [.orange,
.purple,
UIColor(red: 0, green: 0, blue: 0.5, alpha: 1),
UIColor(red: 0, green: 0.5, blue: 0.5, alpha: 1),
//UIColor(red: 0.5, green: 0, blue: 0.5, alpha: 1), //purple
UIColor(red: 0.5, green: 0, blue: 0.5, alpha: 1),
UIColor(red: 0.5, green: 0, blue: 0, alpha: 1),
UIColor(red: 0.5, green: 0.5, blue: 0, alpha: 1),
//UIColor(red: 1, green: 0.5, blue: 0, alpha: 1), //orange
UIColor(red: 1, green: 0.5, blue: 0.5, alpha: 1),
UIColor(red: 1, green: 1, blue: 0, alpha: 1),
UIColor(red: 1, green: 1, blue: 0.5, alpha: 1),
UIColor(red: 1, green: 0.5, blue: 1, alpha: 1),
UIColor(red: 0, green: 1, blue: 1, alpha: 1),
UIColor(red: 0.5, green: 1, blue: 1, alpha: 1),
UIColor(red: 0.5, green: 1, blue: 0.5, alpha: 1)
]
//returns a UIColor of any RGB combination. argument precision indicates number of decimal places beyond the tenths place
static func totallyRandomColor(precision: Int = 1) -> UIColor {
var mutablePrecision = precision
if mutablePrecision < 1 {
mutablePrecision = 1
}
let rand1 = CGFloat(Float(arc4random()) / Float(UINT32_MAX))
let rand2 = CGFloat(Float(arc4random()) / Float(UINT32_MAX))
let rand3 = CGFloat(Float(arc4random()) / Float(UINT32_MAX))
let precisionMultiplier = CGFloat(pow(10.0, Double(mutablePrecision)))
let randRed = CGFloat(round(rand1 * precisionMultiplier)/precisionMultiplier)
let randBlue = CGFloat(round(rand2 * precisionMultiplier)/precisionMultiplier)
let randGreen = CGFloat(round(rand3 * precisionMultiplier)/precisionMultiplier)
let randUIColor = UIColor(red: randRed, green: randGreen, blue: randBlue, alpha: 1)
return randUIColor
}
}
| true
|
aa756422980d2cca49fcab72fb48cd2a0072b7c4
|
Swift
|
hironytic/FireAce-iOS
|
/FireAce/RemoteConfig/RemoteConfigViewController.swift
|
UTF-8
| 2,838
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// RemoteConfigViewController.swift
// FireAce
//
// Copyright (c) 2016 Hironori Ichimiya <hiron@hironytic.com>
//
// 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 FirebaseRemoteConfig
class RemoteConfigViewController: UIViewController {
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var levelLabel: UILabel!
let remoteConfig = FIRRemoteConfig.remoteConfig()
override func viewDidLoad() {
super.viewDidLoad()
if let remoteConfigSettings = FIRRemoteConfigSettings(developerModeEnabled: true) {
remoteConfig.configSettings = remoteConfigSettings
}
remoteConfig.setDefaults([
"type": "Type-A",
"level": 1,
])
updateValues()
}
@IBAction func fetchButtonTapped(sender: AnyObject) {
remoteConfig.fetchWithExpirationDuration(10) { (status, error) in
var statusText: String
switch status {
case .NoFetchYet:
statusText = "NoFetchYet"
case .Success:
statusText = "Success"
case .Failure:
statusText = "Failure"
case .Throttled:
statusText = "Throttled"
}
print("Fetch Result: status = \(statusText), error = \(error)")
}
}
@IBAction func activateButtonTapped(sender: AnyObject) {
let result = remoteConfig.activateFetched()
print("Activate Result: \(result)")
updateValues()
}
func updateValues() {
let typeValue = remoteConfig["type"].stringValue ?? ""
typeLabel.text = typeValue
let levelValue = remoteConfig["level"].numberValue?.integerValue ?? 0
levelLabel.text = "\(levelValue)"
}
}
| true
|
a1ffebd9fc0799e9a09bfa339fac251663c23132
|
Swift
|
GregoryShields/HuliPizza
|
/HuliPizza/ListHeaderView.swift
|
UTF-8
| 996
| 3.234375
| 3
|
[] |
no_license
|
//
// ListHeaderView.swift
// HuliPizza
//
// Created by Gregory Shields on 12/24/20.
//
import SwiftUI
struct ListHeaderView: View {
var text: String
var body: some View {
HStack {
Text(text)
.padding(.leading, 5)
// [] is a "set marker",
// needed with multiple values
//.padding([.leading, .top],30)
// Specify a named color from our assets.
.foregroundColor(Color("G2"))
//.foregroundColor(.accentColor) if you needed a link
// Let's put this on the HStack instead so the entire
// line is colored instead of just the Text element.
//.background(Color("G4"))
Spacer()
}.background(Color("G4"))
}
}
struct ListHeaderView_Previews: PreviewProvider {
static var previews: some View {
ListHeaderView(text: "Menu")
}
}
| true
|
edab35f6c0e3742b47b580893394e4adcd7d05a6
|
Swift
|
nntam1407/MovieBooking
|
/SourceCode/MovieBooking/MovieBooking/Customizations/Extensions/UIColorExtension.swift
|
UTF-8
| 1,871
| 2.8125
| 3
|
[] |
no_license
|
//
// UIColorExtension.swift
// ChatApp
//
// Created by Ngoc Tam Nguyen on 12/17/14.
// Copyright (c) 2014 Ngoc Tam Nguyen. All rights reserved.
//
import UIKit
var UIColorNSCache: NSCache<AnyObject, AnyObject>?
extension UIColor {
class func colorFromHexValue(_ hexValue: Int) -> UIColor {
return UIColor(red: ((CGFloat)((hexValue & 0xFF0000) >> 16))/255.0, green: ((CGFloat)((hexValue & 0xFF00) >> 8))/255.0, blue: ((CGFloat)((hexValue & 0xFF)))/255.0, alpha: 1.0)
}
class func colorFromHexValue(_ hexValue: Int, alpha: CGFloat) -> UIColor {
return UIColor(red: ((CGFloat)((hexValue & 0xFF0000) >> 16))/255.0, green: ((CGFloat)((hexValue & 0xFF00) >> 8))/255.0, blue: ((CGFloat)((hexValue & 0xFF)))/255.0, alpha: alpha)
}
class func colorFromHexValue(_ hexValue: Int, cache: Bool) -> UIColor {
// Try to get from cache first, with hexValue is key
var color = UIColorNSCache?.object(forKey: ("\(hexValue)" as AnyObject)) as? UIColor
if (color != nil) {
} else {
color = UIColor.colorFromHexValue(hexValue)
if (cache) {
if (UIColorNSCache == nil) {
UIColorNSCache = NSCache()
UIColorNSCache!.countLimit = 100 // Only cache 100 color to reduce memory
}
UIColorNSCache!.setObject(color!, forKey: ("\(hexValue)" as AnyObject))
}
}
return color!
}
var hexString: String {
let colorRef = self.cgColor.components
let r:CGFloat = colorRef![0]
let g:CGFloat = colorRef![1]
let b:CGFloat = colorRef![2]
return NSString(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255))) as String
}
}
| true
|
c2adaa65dee389bef7255c33626be03828e69ae3
|
Swift
|
jkakeno/iOS-MovieNight
|
/MovieNight/MovieNight/Networking/JSONDecodable.swift
|
UTF-8
| 301
| 2.625
| 3
|
[] |
no_license
|
//
// JSONDecodable.swift
// MovieNight
//
// Created by Jun Kakeno on 11/5/18.
// Copyright © 2018 Jun Kakeno. All rights reserved.
//
import Foundation
protocol JSONDecodable {
//Potocole to enable models that adopt this protocole to be initialized by passing a json
init?(json: [String: Any])
}
| true
|
4f2f258a1ef9a62acfa08566d4d6161f531a4364
|
Swift
|
muvr/muvr-ios
|
/Muvr/MRSessionLabellingViewController.swift
|
UTF-8
| 5,267
| 3
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
import Foundation
import UIKit
import MuvrKit
///
/// A cell that displays a scalar value, like weight, repetitions or intensity
///
class MRSessionLabellingScalarTableViewCell : UITableViewCell {
private var increment: (MKExerciseLabel -> MKExerciseLabel)!
private var decrement: (MKExerciseLabel -> MKExerciseLabel)!
private var exerciseLabel: MKExerciseLabel!
private var scalarExerciseLabelSettable: MRScalarExerciseLabelSettable!
func setExerciseLabel(exerciseLabel: MKExerciseLabel, increment: MKExerciseLabel -> MKExerciseLabel, decrement: MKExerciseLabel -> MKExerciseLabel) {
let centreX = self.frame.width / 2
let centreY = self.frame.height / 2
let height = self.frame.height - 20
let width = ceil(height * 1.2)
let frame = CGRect(x: centreX - width / 2, y: centreY - height / 2, width: width, height: height)
let (view, scalarExerciseLabelSettable) = MRExerciseLabelViews.scalarViewForLabel(exerciseLabel, frame: frame)!
addSubview(view)
self.scalarExerciseLabelSettable = scalarExerciseLabelSettable
self.exerciseLabel = exerciseLabel
self.increment = increment
self.decrement = decrement
}
@IBAction private func incrementTouched() {
exerciseLabel = increment(exerciseLabel)
try! scalarExerciseLabelSettable.setExerciseLabel(exerciseLabel)
}
@IBAction private func decrementTouched() {
exerciseLabel = decrement(exerciseLabel)
try! scalarExerciseLabelSettable.setExerciseLabel(exerciseLabel)
}
}
///
/// Displays indicators that allow the user to select the repetitions, weight and intensity
/// To use, call ``setExercise`` supplying the predicted exercise, and a function that will
/// be called when the user changes the inputs.
///
class MRSessionLabellingViewController: UIViewController, UITableViewDataSource {
@IBOutlet private weak var tableView: UITableView!
/// A function that carries the new values: (repetitions, weight, intensity)
typealias OnLabelsUpdated = [MKExerciseLabel] -> Void
/// The function that will be called whenever a value changes
private var onLabelsUpdated: OnLabelsUpdated!
private var labels: [MKExerciseLabel] = []
private var exerciseDetail: MKExerciseDetail!
/// Makes sure the table is entirely visible
override func viewDidLayoutSubviews() {
let offset = tableView.contentSize.height - tableView.frame.height
if offset > 0 {
// not enough space
if labels.count > 0 {
tableView.rowHeight = ceil(tableView.frame.height / CGFloat(labels.count))
}
} else {
// center in available space
tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y - offset / 2, tableView.frame.width, tableView.contentSize.height)
}
}
///
/// Sets exercise detail and the labels for the users to verify.
///
/// - parameter exerciseDetail: the exercise whose values to be displayed
/// - parameter onUpdate: a function that will be called on change of values
///
func setExerciseDetail(exerciseDetail: MKExerciseDetail, predictedLabels: [MKExerciseLabel], missingLabels: [MKExerciseLabel], onLabelsUpdated: OnLabelsUpdated) {
self.onLabelsUpdated = onLabelsUpdated
self.exerciseDetail = exerciseDetail
self.labels = predictedLabels + missingLabels
tableView.reloadData()
}
/// Calls the onUpdate with the appropriate values
private func update() {
onLabelsUpdated([])
}
private func findProperty(predicate: MKExerciseProperty -> Bool) -> MKExerciseProperty? {
for property in exerciseDetail.properties {
if predicate(property) {
return property
}
}
return nil
}
private func incrementLabel(index: Int) -> (MKExerciseLabel -> MKExerciseLabel) {
return { label in
let newLabel = label.increment(self.exerciseDetail)
self.labels[index] = newLabel
self.onLabelsUpdated(self.labels)
return newLabel
}
}
private func decrementLabel(index: Int) -> (MKExerciseLabel -> MKExerciseLabel) {
return { label in
let newLabel = label.decrement(self.exerciseDetail)
self.labels[index] = newLabel
self.onLabelsUpdated(self.labels)
return newLabel
}
}
// MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return labels.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("label", forIndexPath: indexPath) as! MRSessionLabellingScalarTableViewCell
cell.setExerciseLabel(labels[indexPath.row], increment: incrementLabel(indexPath.row), decrement: decrementLabel(indexPath.row))
return cell
}
}
| true
|
ae04d672055d044978af7cd2f152a6ce75646a09
|
Swift
|
crowdin/mobile-sdk-ios
|
/Sources/CrowdinSDK/Providers/Crowdin/Operations/CrowdinDownloadOperation.swift
|
UTF-8
| 747
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// CrowdinDownloadOperation.swift
// BaseAPI
//
// Created by Serhii Londar on 05.12.2019.
//
import Foundation
protocol CrowdinDownloadOperationProtocol {
var filePath: String { get }
var contentDeliveryAPI: CrowdinContentDeliveryAPI { get }
}
class CrowdinDownloadOperation: AsyncOperation, CrowdinDownloadOperationProtocol {
var filePath: String
var contentDeliveryAPI: CrowdinContentDeliveryAPI
init(filePath: String, contentDeliveryAPI: CrowdinContentDeliveryAPI) {
self.filePath = filePath
self.contentDeliveryAPI = contentDeliveryAPI
}
override func main() {
fatalError("Please use child classes: CrowdinStringsDownloadOperation, CrowdinPluralsDownloadOperation")
}
}
| true
|
953b077cf5cb63916ed1c049862b705137fc42af
|
Swift
|
FoodPal/FoodPal
|
/FoodPal/FoodPal/Models/GroceryList.swift
|
UTF-8
| 1,258
| 3.265625
| 3
|
[] |
no_license
|
//
// GroceryList.swift
// FoodPal
//
// Created by Teodor Ivanov on 10/25/17.
// Copyright © 2017 Teodor Ivanov. All rights reserved.
//
import Foundation
class GroceryList{
//
var name: String?
var id: Int64?
var cost: Double?
var items = [GroceryItem]()
var categories = [Category]()
init(name: String, id: Int64){
self.name = name
self.id = id
}
convenience init(name: String, id: Int64, cost: Double, items: [GroceryItem], categories: [Category]){
self.init(name: name, id: id)
self.items = items
self.cost = self.calculateTotalCost(items: items)
self.categories = self.getCategories(items: items)
}
func getCategories(items: [GroceryItem]) -> [Category]{
var categories = [Category]()
for item in items {
if let itemCategory = item.category{
categories.append(itemCategory)
}
}
return categories
}
//Incase I need to calculate it.
func calculateTotalCost(items: [GroceryItem]) -> Double? {
var cost = 0.00
for item in items{
if let itemCost = item.cost{
cost += itemCost
}
}
return cost
}
}
| true
|
77a661807825d17f630d7ce36ae2a823e5c12471
|
Swift
|
XZwalk/SwiftStudy
|
/SwiftStudy/HomePageTableViewCell.swift
|
UTF-8
| 3,732
| 2.515625
| 3
|
[] |
no_license
|
//
// HomePageTableViewCell.swift
// QiuBai
//
// Created by 张祥 on 16/4/5.
// Copyright © 2016年 张祥. All rights reserved.
//
import UIKit
class HomePageTableViewCell: UITableViewCell {
//创建属性
var userPhoto:UIImageView!
var nickNameLabel:UILabel!
var contentLabel:UILabel!
var showOperationView:ShowOperationView!
//间距
let spaceWH:CGFloat = 10.0
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//调用添加子视图方法
self.addAllViews()
}
//这是我们swift中的安全机制, 我们重写父类的构造方法的时候, 需要一个构造方法参数为 aDecoder: NSCoder
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addAllViews() {
self.userPhoto = UIImageView(frame: CGRectMake(spaceWH, spaceWH, 40, 40))
self.userPhoto.backgroundColor = UIColor.orangeColor()
//打开交互, 打不打开都行
self.userPhoto.userInteractionEnabled = true
//设置圆角
self.userPhoto.layer.cornerRadius = 20
self.userPhoto.layer.masksToBounds = true
self.addSubview(self.userPhoto)
self.nickNameLabel = UILabel(frame: CGRectMake(CGRectGetMaxX(self.userPhoto.frame) + spaceWH, spaceWH, UIScreen.mainScreen().bounds.size.width - 70, 40))
//self.nickNameLabel.backgroundColor = UIColor.orangeColor()
self.addSubview(self.nickNameLabel)
self.contentLabel = UILabel(frame: CGRectMake(spaceWH, CGRectGetMaxY(self.nickNameLabel.frame) + spaceWH, UIScreen.mainScreen().bounds.size.width - 20, 80))
//self.contentLabel.backgroundColor = UIColor.yellowColor()
self.contentLabel.font = UIFont.systemFontOfSize(15)
self.contentLabel.numberOfLines = 0
self.addSubview(self.contentLabel)
self.showOperationView = ShowOperationView(frame: CGRectMake(0, CGRectGetMaxY(self.contentLabel.frame) + 10, UIScreen.mainScreen().bounds.size.width, 70))
self.addSubview(self.showOperationView)
}
//根据label的内容, 从新布局cell
//#外部参数, 在外面也能访问到
func adjustCellSubViews(use model:NetInfoModel) {
let changeRect:CGRect = model.content.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.size.width - 20, 0), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(15)], context: nil)
//先接收一下label的frame, 因为label的frame不能直接改变
var frame:CGRect = self.contentLabel.frame
//修改frame的高, 根据字体的高度
frame.size.height = changeRect.size.height
//修改label的frame
self.contentLabel.frame = frame
//更新label下面的控件的frame
self.showOperationView.frame = CGRectMake(0, CGRectGetMaxY(self.contentLabel.frame) + 10, UIScreen.mainScreen().bounds.size.width, 70)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
824afe327fa78e12cece5c3865796c36379e1701
|
Swift
|
RomanEsin/Klich
|
/Klich/Views/Chat/ChatView.swift
|
UTF-8
| 1,094
| 2.984375
| 3
|
[] |
no_license
|
//
// ChatView.swift
// Klich
//
// Created by Роман Есин on 23.05.2021.
//
import SwiftUI
struct ChatItem: View {
var body: some View {
HStack {
Image(systemName: "person.crop.circle.fill")
.font(.title)
VStack(alignment: .leading) {
Text("Имя Организации или Человека")
.font(.body.bold())
Text("Привет когда ты придешь на работу?")
.foregroundColor(.secondary)
}
Spacer()
}
}
}
struct ChatView: View {
var body: some View {
NavigationView {
List {
NavigationLink(
destination: ChatWithPersonView(),
label: {
ChatItem()
})
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("Чаты")
}
}
}
struct ChatView_Previews: PreviewProvider {
static var previews: some View {
ChatView()
}
}
| true
|
120a062071eb9d493f64350d253bf55207c12d2c
|
Swift
|
jprothwell/PopupController
|
/Example/PopupController/DemoPopupViewController1.swift
|
UTF-8
| 1,389
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// DemoPopupViewController1.swift
// PopupController
//
// Created by 佐藤 大輔 on 2/4/16.
// Copyright © 2016 Daisuke Sato. All rights reserved.
//
import UIKit
class DemoPopupViewController1: UIViewController, PopupContentViewController {
var closeHandler: (() -> Void)?
@IBOutlet weak var button: UIButton! {
didSet {
button.layer.borderColor = UIColor(red: 242/255, green: 105/255, blue: 100/255, alpha: 1.0).cgColor
button.layer.borderWidth = 1.5
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.frame.size = CGSize(width: 300,height: 300)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class func instance() -> DemoPopupViewController1 {
let storyboard = UIStoryboard(name: "DemoPopupViewController1", bundle: nil)
return storyboard.instantiateInitialViewController() as! DemoPopupViewController1
}
func sizeForPopup(_ popupController: PopupController, size: CGSize, showingKeyboard: Bool) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width,height: 300)
}
@IBAction func didTapCloseButton(_ sender: AnyObject) {
closeHandler?()
}
}
| true
|
b011fd837ce85bbb3fd9251680c082179de91fd7
|
Swift
|
iOSDevLog/raywenderlich
|
/code/264. NSOperationQueue Concurrency_02-NSOperationQueue-Resources-1/Concurrency-02-NSOperationQueue-Resources/Concurrency_002_ChallengeStarter/Decompressor.playground/Contents.swift
|
UTF-8
| 945
| 3.484375
| 3
|
[
"MIT"
] |
permissive
|
import Compressor
import UIKit
//: # Compressor Operation
//: Continuing from the challenge in the previous video, your challenge for this video is to use an `NSOperationQueue` to decompress a collection of compressed images.
//: The `ImageDecompressor` class is as before
class ImageDecompressor: NSOperation {
var inputPath: String?
var outputImage: UIImage?
override func main() {
guard let inputPath = inputPath else { return }
if let decompressedData = Compressor.loadCompressedFile(inputPath) {
outputImage = UIImage(data: decompressedData)
}
}
}
//: The following two arrays represent the input and output collections:
let compressedFilePaths = ["01", "02", "03", "04", "05"].map {
NSBundle.mainBundle().pathForResource("sample_\($0)_small", ofType: "compressed")
}
var decompressedImages = [UIImage]()
//: Create your implementation here:
//: Inspect the decompressed images
decompressedImages
| true
|
c2573a2d5c63580739563e422c93e5d09f49453f
|
Swift
|
jalp14/CalTrack
|
/CalTrack/MainViews/HomeView.swift
|
UTF-8
| 4,968
| 2.515625
| 3
|
[] |
no_license
|
//
// HomeView.swift
// CalTrack
//
// Created by Dev on 08/12/2019.
// Copyright © 2019 jdc0rp. All rights reserved.
//
import SwiftUI
import HealthKit
import Firebase
import FirebaseFirestoreSwift
//**************** Home View ****************\\
struct HomeView: View {
//**************** Variables ****************\\
@EnvironmentObject var session : SessionStore
@ObservedObject var dbManager = DBManager.shared
@State var isShowingCameraPreview = false
@State var isShowingBarcodePreview = false
@State var todayCalorie : Int = 0
@State var currentIntake = 0.0
@State var todayGoal = 0.0
@State var goalRatio = 0.0
var body: some View {
NavigationView {
VStack {
Spacer()
VStack {
DailyOverView(intake: $currentIntake, caloriesBurned: $todayCalorie, goalSetToday: $todayGoal, goalRatio : $goalRatio)
}
.frame(width: 360, height: 140)
.background(VisualBlur(blurStyle: .systemMaterial))
.clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
.shadow(color: Color(#colorLiteral(red: 0.3176470697, green: 0.07450980693, blue: 0.02745098062, alpha: 1)).opacity(0.3), radius: 20, x: 13, y: 10)
Spacer()
Button(action: {self.isShowingCameraPreview.toggle()}) {
Text("Track using ML")
.foregroundColor(.black)
.frame(minWidth: 0, maxWidth: ScreenBounds.deviceWidth - 250)
.padding(12)
.padding(.horizontal, 30)
.background(Color(#colorLiteral(red: 0.8767055458, green: 0.1087125435, blue: 0.1915467579, alpha: 1)))
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.shadow(color: Color(#colorLiteral(red: 0.8767055458, green: 0.1087125435, blue: 0.1915467579, alpha: 1)).opacity(0.2), radius: 16, x: 0, y: 20)
}.sheet(isPresented: $isShowingCameraPreview, content: {LiveCameraPreview().environmentObject(self.session)})
Spacer()
Button(action: {self.isShowingBarcodePreview.toggle()}) {
Text("Track using Barcode")
.foregroundColor(.black)
.frame(minWidth: 0, maxWidth: ScreenBounds.deviceWidth - 200)
.padding(12)
.padding(.horizontal, 30)
.background(Color(#colorLiteral(red: 0.8767055458, green: 0.1087125435, blue: 0.1915467579, alpha: 1)))
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.shadow(color: Color(#colorLiteral(red: 0.8767055458, green: 0.1087125435, blue: 0.1915467579, alpha: 1)).opacity(0.2), radius: 16, x: 0, y: 20)
}.sheet(isPresented: $isShowingBarcodePreview, content: {BarcodeScannerView().environmentObject(self.session)})
Spacer()
}.navigationBarTitle(Text("Home"))
//**************** When the view appers, update the values ****************\\
}.onAppear() {
print("On Appera Triggered!!!!")
self.loadCalories()
self.dbManager.readGoal(session: self.session)
}
//**************** When the value for intake is updated, update the UI ****************\\
.onReceive(dbManager.$currentIntake, perform: {newIntake in
print("New intake received \(newIntake)")
self.currentIntake = newIntake
// Recalculate the ratio
self.goalRatio = (self.currentIntake - Double(self.todayCalorie)) / self.todayGoal
self.goalRatio = self.goalRatio * 100
print("Goal Ration : \(self.goalRatio)")
})
//**************** When the value for the current goal is updated, update the UI ****************\\
.onReceive(dbManager.$currentGoal) { (currentGoal) in
self.todayGoal = currentGoal
}
}
// Load calories burned for today
func loadCalories() {
self.dbManager.readIntake(session: self.session)
HealthDataQuery.shared.getEnergyBurned(completion: {calories in
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.todayCalorie = Int(calories)
print(self.todayCalorie)
self.goalRatio = (self.currentIntake - Double(self.todayCalorie)) / self.todayGoal
self.goalRatio = self.goalRatio * 100
print("Goal Ratio : \(self.goalRatio)")
}
})
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
| true
|
6e1dcb0efee5d18a6dc13b24aeeeae1e4e7e8b61
|
Swift
|
klgraham/deep-learning-with-pytorch
|
/data/programming_languages/swift/enumTest.swift
|
UTF-8
| 2,052
| 3.046875
| 3
|
[] |
no_license
|
//
// enumTest.swift
// SwiftStructures
//
// Created by Wayne Bishop on 4/25/16.
// Copyright © 2016 Arbutus Software Inc. All rights reserved.
//
import XCTest
@testable import SwiftStructures
/*
notes: this test class adopts the Sortable protocol. as a result,
the isSorted function originates from the protocol extension.
*/
class enumsTest: XCTestCase, Sortable {
let list = Algorithm.Elements([8, 2, 10, 9, 7, 5])
override func setUp() {
super.setUp()
}
//model for insertion sort algorithm
func testInsertModel() {
let model = Algorithm.InsertionSort(list)
self.buildEnumModel(withModel: model)
}
//model for insertion sort (with text)
func testInsertTextModel() {
let textList = Algorithm.Elements(["Dog", "Cat", "Dinasour", "Lion", "Cheetah", "Elephant", "Aardvark"])
let model = Algorithm.InsertionSort(textList)
self.buildEnumModel(withModel: model)
}
//model for bubble sort algorithm
func testBubbleModel() {
let model = Algorithm.BubbleSort(list)
self.buildEnumModel(withModel: model)
}
//model for selection sort algorithm
func testSelectionModel() {
let model = Algorithm.SelectionSort(list)
self.buildEnumModel(withModel: model)
}
//MARK: Helper Function
//helper function - test enum model
func buildEnumModel<T: Comparable>(withModel model: Algorithm<T>) {
let enumModel = EnumModel()
let results = enumModel.evaluate(withModel: model)
XCTAssertTrue(self.isSorted(results!), "list values incorrectly sorted..")
}
}
| true
|
c472df4ea75a91fade72b680f4192cf56d99051e
|
Swift
|
caziz/OneThreeFive
|
/OneThreeFive/ArticleService.swift
|
UTF-8
| 6,078
| 2.796875
| 3
|
[] |
no_license
|
//
// ArticleService.swift
// OneThreeFive
//
// Created by Christopher Aziz on 7/24/17.
// Copyright © 2017 Christopher Aziz. All rights reserved.
//
import CoreData
import Alamofire
import SwiftyJSON
import Firebase
import FirebaseDatabase
class ArticleService {
static func getSaved(context: NSManagedObjectContext = CoreDataHelper.managedContext) -> [Article] {
let fetchRequest: NSFetchRequest<Article> = Article.fetchRequest()
do {
let results = try context.fetch(fetchRequest)
return results
} catch let error as NSError {
print("Error: Could not fetch \(error)")
}
return []
}
static func unfavoriteArticle(article: Article) {
article.isFavorited = false
// TODO: delete image
CoreDataHelper.save()
print("unfavorited")
}
static func favoriteArticle(article: Article) {
article.isFavorited = true
if let urlToImage = URL(string: article.urlToImage!),
let image = ImageService.fetchImage(url: urlToImage) {
ImageService.saveImage(path: article.uid!, image: image)
}
CoreDataHelper.save()
}
static func cache(completion: @escaping () -> Void) {
//CoreDataHelper.persistentContainer.performBackgroundTask { (context) in
let dispatchGroup = DispatchGroup()
// fetch enabled news source IDs
let enabledNewsSources = NewsSourceService.getSaved().filter{$0.isEnabled}
let cachedArticleURLs = ArticleService.getSaved().map{$0.url!}
// create firebase database reference
let ref = Database.database().reference()
Constants.Settings.timeOptions.forEach { time in
let timeRef = ref.child("time\(time)minutes")
for enabledNewsSource in enabledNewsSources {
// pull from Firebase Database
dispatchGroup.enter()
timeRef.child(enabledNewsSource.id!).observeSingleEvent(of: .value, with: { (snapshot) in
guard let articleDictsForSource = snapshot.value as? [String: [String:String]] else {
dispatchGroup.leave()
return
}
for articleDict in articleDictsForSource.values {
dispatchGroup.enter()
if cachedArticleURLs.contains(articleDict["url"]!) {
dispatchGroup.leave()
continue
}
// create article entity with firebase data
let article = Article(context: CoreDataHelper.managedContext)
article.time = Int16(time)
article.title = articleDict["title"]
article.url = articleDict["url"]
article.urlToImage = articleDict["urlToImage"]
article.publishedAt = articleDict["date"]
article.uid = UUID().uuidString
enabledNewsSource.addToArticles(article)
dispatchGroup.leave()
}
dispatchGroup.leave()
})
}
}
dispatchGroup.notify(queue: .main) {
CoreDataHelper.save()
completion()
}
}
static func uploadArticle(articleJSON : JSON) {
let url = articleJSON["url"].stringValue
ReadabilityService.textIn(url: url) { text in
// calculate read time
let characters = text.count
let words = Double(characters) / Double(Constants.Settings.charactersPerWord)
let roundedReadTime = Int16(round(words / Constants.Settings.wordsPerMinute))
// skip articles with unspecified read times
if !Constants.Settings.timeOptions.contains(Int(roundedReadTime)) {
return
}
let readTimeChild = "time\(roundedReadTime)minutes"
let newsSourceChild = articleJSON["source"]["id"].stringValue
// create reference
let ref = Database.database().reference()
.child(readTimeChild)
.child(newsSourceChild)
.childByAutoId()
// create/upload article
let article: [String : String] = ["url" : articleJSON["url"].stringValue,
"date" : articleJSON["publishedAt"].stringValue,
"title" : articleJSON["title"].stringValue,
"urlToImage" : articleJSON["urlToImage"].stringValue]
ref.updateChildValues(article)
}
}
// TODO: make this more asnyc
/* build database using relevant articles from saved news sources */
static func updateDatabase() {
let sourceURL = Constants.NewsAPI.articlesUrl()
let queue = DispatchQueue(label: "build-database-queue",
qos: .background,
attributes:.concurrent)
Alamofire.request(sourceURL).validate()
.responseJSON(queue: queue, options: .allowFragments) { response in
switch response.result {
case .success:
guard let value = response.result.value else {
print("Error: Alamofire response JSON could not be evaluated.")
return
}
let articleJSONs = JSON(value)["articles"].arrayValue
// upload article for each json
articleJSONs.forEach { articleJSON in
uploadArticle(articleJSON : articleJSON)
}
case .failure:
print("Error: Alamofire request to fetch article json failed.")
return
}
}
}
}
| true
|
7645c621dd86aedfe139ab90299584db6d596083
|
Swift
|
mystarains/CardCollection
|
/Drag/DragAndDrop-CollectionView/DragAndDropInCollectionView/Second/SecondController.swift
|
UTF-8
| 9,542
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
enum CellModel {
case simple(text: String)
case availableToDrop
}
class SecondController: UIViewController {
private lazy var cellIdentifier = "cellIdentifier"
private lazy var supplementaryViewIdentifier = "supplementaryViewIdentifier"
private lazy var sections = 10
private lazy var itemsInSection = 2
private lazy var numberOfElementsInRow = 3
private lazy var data: [[CellModel]] = {
var count = 0
return (0 ..< sections).map { _ in
return (0 ..< itemsInSection).map { _ -> CellModel in
count += 1
return .simple(text: "cell \(count)")
}
}
}()
override func viewDidLoad() {
super.viewDidLoad()
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.minimumLineSpacing = 5
collectionViewFlowLayout.minimumInteritemSpacing = 5
let _numberOfElementsInRow = CGFloat(numberOfElementsInRow)
let allWidthBetwenCells = _numberOfElementsInRow == 0 ? 0 : collectionViewFlowLayout.minimumInteritemSpacing*(_numberOfElementsInRow-1)
let width = (view.frame.width - allWidthBetwenCells)/_numberOfElementsInRow
collectionViewFlowLayout.itemSize = CGSize(width: width, height: width)
collectionViewFlowLayout.headerReferenceSize = CGSize(width: 0, height: 40)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewFlowLayout)
collectionView.backgroundColor = .white
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
collectionView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
collectionView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
collectionView.register(SupplementaryView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: supplementaryViewIdentifier)
collectionView.dragInteractionEnabled = true
collectionView.reorderingCadence = .fast
collectionView.dropDelegate = self
collectionView.dragDelegate = self
collectionView.delegate = self
collectionView.dataSource = self
}
}
extension SecondController: UICollectionViewDelegate { }
extension SecondController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch data[indexPath.section][indexPath.item] {
case .simple(let text):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CollectionViewCell
cell.label?.text = text
cell.backgroundColor = .gray
return cell
case .availableToDrop:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.green.withAlphaComponent(0.3)
return cell
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: supplementaryViewIdentifier, for: indexPath) as! SupplementaryView
return headerView
}
}
extension SecondController: UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let itemProvider = NSItemProvider(object: "\(indexPath)" as NSString)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = data[indexPath.section][indexPath.row]
return [dragItem]
}
func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] {
let itemProvider = NSItemProvider(object: "\(indexPath)" as NSString)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = data[indexPath.section][indexPath.row]
return [dragItem]
}
func collectionView(_ collectionView: UICollectionView, dragSessionWillBegin session: UIDragSession) {
var itemsToInsert = [IndexPath]()
(0 ..< data.count).forEach {
itemsToInsert.append(IndexPath(item: data[$0].count, section: $0))
data[$0].append(.availableToDrop)
}
collectionView.insertItems(at: itemsToInsert)
}
func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) {
var removeItems = [IndexPath]()
for section in 0..<data.count {
for item in 0..<data[section].count {
switch data[section][item] {
case .availableToDrop:
removeItems.append(IndexPath(item: item, section: section))
case .simple:
break
}
}
}
removeItems.forEach { data[$0.section].remove(at: $0.item) }
collectionView.deleteItems(at: removeItems)
}
}
extension SecondController: UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
let destinationIndexPath: IndexPath
if let indexPath = coordinator.destinationIndexPath {
destinationIndexPath = indexPath
} else {
let section = collectionView.numberOfSections - 1
let row = collectionView.numberOfItems(inSection: section)
destinationIndexPath = IndexPath(row: row, section: section)
}
switch coordinator.proposal.operation {
case .move:
reorderItems(coordinator: coordinator, destinationIndexPath:destinationIndexPath, collectionView: collectionView)
case .copy:
copyItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)
default: return
}
}
func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool { return true }
func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
if collectionView.hasActiveDrag, let destinationIndexPath = destinationIndexPath {
switch data[destinationIndexPath.section][destinationIndexPath.row] {
case .simple:
return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
case .availableToDrop:
return UICollectionViewDropProposal(operation: .move, intent: .insertIntoDestinationIndexPath)
}
}
else {
return UICollectionViewDropProposal(operation: .forbidden)
}
}
private func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
let items = coordinator.items
if items.count == 1, let item = items.first,
let sourceIndexPath = item.sourceIndexPath,
let localObject = item.dragItem.localObject as? CellModel {
collectionView.performBatchUpdates ({
data[sourceIndexPath.section].remove(at: sourceIndexPath.item)
data[destinationIndexPath.section].insert(localObject, at: destinationIndexPath.item)
collectionView.deleteItems(at: [sourceIndexPath])
collectionView.insertItems(at: [destinationIndexPath])
})
}
}
private func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
collectionView.performBatchUpdates({
var indexPaths = [IndexPath]()
for (index, item) in coordinator.items.enumerated() {
if let localObject = item.dragItem.localObject as? CellModel {
let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)
data[indexPath.section].insert(localObject, at: indexPath.row)
indexPaths.append(indexPath)
}
}
collectionView.insertItems(at: indexPaths)
})
}
}
| true
|
dd03558bab738dd3b5b097c4f51a2d251b13a3bc
|
Swift
|
CainLuo/SQLiteExample
|
/SQLExample/SQLExample/SQLManager+Users.swift
|
UTF-8
| 11,587
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// SQLManager+Users.swift
// SQLExample
//
// Created by YYKJ0048 on 2021/10/8.
//
import Foundation
import SQLite
// Expressions
fileprivate let index = Expression<Int64>("index")
fileprivate let balance = Expression<Double>("balance")
fileprivate let verified = Expression<Bool>("verified")
fileprivate let userID = Expression<String>("userID")
fileprivate let email = Expression<String>("email")
fileprivate let name = Expression<String?>("name")
fileprivate let gender = Expression<String?>("gender")
extension SQLManager {
/// 创建用户表
/// - Parameter db: Connection
func createUserTable(_ db: Connection) {
do {
try db.run(users.create(ifNotExists: true) { t in
// autoincrement:自动递增
t.column(index, primaryKey: .autoincrement)
// unique:用于保证多列中是唯一值
t.column(userID, unique: true)
t.column(email, unique: true)
t.column(name)
// defaultValue:默认值
t.column(balance, defaultValue: 0.0)
t.column(verified, defaultValue: false)
})
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
}
// MARK: - Users表-增
extension SQLManager {
/// 新建Users表的Gender行
func insetColumnInUserTable() {
guard !columns(table: "users", column: "gender") else {
print("💥💥💥 -------------- 插入失败,表中已有该列 -------------- 💥💥💥")
return
}
do {
try db.run(users.addColumn(gender))
userVersion += 1
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
/// 添加用户信息到Users表
/// - Parameters:
/// - uEmail: String
/// - uName: String
/// - uGender: String
func addUserInfo(_ model: UserModel) {
do {
try db.run(users.insert(userID <- model.userID, email <- model.email, name <- model.name, gender <- model.gender))
if let chat = model.chat {
insetChatSetings(model.userID, chat: chat)
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
/// 批量添加用户信息到Users表,⚠️⚠️⚠️非常耗时⚠️⚠️
/// - Parameter models: [UserModel]
// func addUserInfos(_ models: [UserModel], complete: @escaping (() -> Void)) {
// DispatchQueue.global().async {
// var userSetters: [[Setter]] = []
//
// models.forEach { model in
// let setter = [userID <- model.userID, email <- model.email, name <- model.name, gender <- model.gender]
// if let chat = model.chat {
// self.insetChatSetings(model.userID, chat: chat)
// }
// userSetters.append(setter)
// }
//
// do {
// try self.db.transaction {
// do {
// try self.db.run(self.users.insertMany(userSetters))
// complete()
// } catch {
// print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
// }
// }
// } catch {
// print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
// }
// }
// }
/// 批量添加用户信息到Users表
/// - Parameter models: [UserModel]
func addUserInfos(_ models: [UserModel]) {
do {
// 开启SQLite的事务
try db.transaction {
models.forEach { model in
do {
try db.run(users.insert(userID <- model.userID, email <- model.email, name <- model.name, gender <- model.gender))
if let chat = model.chat {
insetChatSetings(model.userID, chat: chat)
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
}
// MARK: - Users表-删
extension SQLManager {
/// 删除所有用户信息
func removeAllUsers() {
do {
if try db.run(users.delete()) > 0 {
removeAll()
print("👍🏻👍🏻👍🏻 -------------- 删除所有用户成功 -------------- 👍🏻👍🏻👍🏻")
} else {
print("💥💥💥 -------------- 没有找到对应得用户 -------------- 💥💥💥")
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
/// 删除指定邮箱的用户信息
/// - Parameter uEmail: String
func removeUser(_ uEmail: String) {
let userInfo = users.filter(email == uEmail)
do {
if try db.run(userInfo.delete()) > 0 {
print("👍🏻👍🏻👍🏻 -------------- 删除所有用户成功 -------------- 👍🏻👍🏻👍🏻")
} else {
print("💥💥💥 -------------- 没有找到对应得用户 -------------- 💥💥💥")
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
}
// MARK: - Users表-改
extension SQLManager {
/// 更新Users表的用户信息
/// - Parameters:
/// - uEmail: String
/// - uName: String
/// - uGender: String
func updateUserInfo(_ model: UserModel) {
do {
// 开启SQLite的事务
try db.transaction {
do {
let user = users.filter(userID == model.userID)
try db.run(user.update(userID <- model.userID, email <- model.email, name <- model.name, gender <- model.gender))
if let chat = model.chat {
updateChatSetting(model.userID, chat: chat)
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
}
// MARK: - Users表-查
extension SQLManager {
/// 遍地Users表的所有用户
func filterUsers(_ complete: ((_ userMode: [UserModel]) -> Void)) {
do {
try db.transaction {
do {
var userInfos: [UserModel] = []
try db.prepare(users).forEach({ user in
getChatSetting(user[userID]) { chatSetting in
userInfos.append(UserModel(userID: user[userID], email: user[email],
balance: user[balance], verified: user[verified],
name: user[name]!, gender: user[gender]!, chat: chatSetting))
}
})
print(userInfos.count)
complete(userInfos)
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
/// 选择Users表里的Email字段
func filterEmails() {
let query = users.select(email)
do {
try db.prepare(query).forEach({ user in
print("User: \(user[email]))")
})
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
/// 获取Users表指定邮箱的用户
/// - Parameter uEmail: String
func filterUserInfo(_ uEmail: String, complete: ((_ userMode: UserModel) -> Void)) {
// filter和where是一样的效果
let query = users.filter(email == uEmail)
// let query = users.where(email == uEmail)
do {
try db.prepare(query).forEach({ user in
getChatSetting(user[userID]) { chatSetting in
complete(UserModel(userID: user[userID], email: user[email],
balance: user[balance], verified: user[verified],
name: user[name]!, gender: user[gender]!, chat: chatSetting))
}
print("User: \(user[index]), \(user[email]), \(String(describing: user[name])), \(user[balance]), \(user[verified]), \(String(describing: user[gender]))")
})
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
/// 获取Users表的行数
/// - Returns: Int
func getUserCount() -> Int {
do {
return try db.scalar(users.count)
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
return 0
}
}
/// 获取users表和usersChatSetings里等于id的用户数据
/// - Parameter id: String
func filterUserAndChat(_ id: String) -> UserModel? {
let query = users.join(usersChatSetings, on: users[userID] == id && usersChatSetings[userID] == id)
do {
if let user = try db.pluck(query) {
let chatSetting = getChatSetting(user)
return UserModel(userID: user[users[userID]], email: user[email],
balance: user[balance], verified: user[verified],
name: user[name]!, gender: user[gender]!, chat: chatSetting)
}
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
return nil
}
/// 使用order对users表进行排序,desc:降序,asc:升序
func sortUsers() {
let query = users.order(userID.desc)
do {
try db.prepare(query).forEach({ user in
print(UserModel(userID: user[userID], email: user[email],
balance: user[balance], verified: user[verified],
name: user[name]!, gender: user[gender]!))
})
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
func searchLikeUser() {
let query = users.filter(userID.like("922_"))
do {
try db.prepare(query).forEach({ row in
print(row)
})
} catch {
print("💥💥💥 -------------- \(error.localizedDescription) -------------- 💥💥💥")
}
}
}
| true
|
6c0ec771aecf4982600a22dfd4ce3ede2e083776
|
Swift
|
mwoolery/GymMachineAssistant
|
/GymMachineAssistant/GymMachineAssistant/MuscleGroup.swift
|
UTF-8
| 339
| 2.59375
| 3
|
[] |
no_license
|
//
// MuscleGroup.swift
// GymMachineAssistant
//
// Created by Woolery,Matthew A on 10/20/17.
// Copyright © 2017 Woolery,Matthew A. All rights reserved.
//
import Foundation
struct MuscleGroup{
var name:String
init(_ name: String){
self.name = name
}
}
//use to define which muscles are worked by machine
| true
|
a6b80d141de625270623bc55241c7f9acbf183ab
|
Swift
|
com9712/EmojiChat
|
/EmojiChat/ChatRoom.swift
|
UTF-8
| 893
| 2.765625
| 3
|
[] |
no_license
|
//
// ChatRoom.swift
// EmojiChat
//
// Created by Eric Kim on 2/22/15.
// Copyright (c) 2015 Eric Kim. All rights reserved.
//
import UIKit
class ChatRoom: UIViewController {
var nameString:String?
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = nameString
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(255, 315, 100, 50)
button.backgroundColor = UIColor(red: 0.23, green: 0.6, blue: 0.9, alpha: 1.0)
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.setTitle("Send", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
}
| true
|
8455831637342131ae831775a047c70d9609dd41
|
Swift
|
Andrei-Popilian/VIP_Design_Xcode_Template
|
/SampleVIPSwift/SampleVIPSwift/SampleVIPSwiftTests/LoginTests/LoginInteractorTests.swift
|
UTF-8
| 2,451
| 2.625
| 3
|
[] |
no_license
|
//
// LoginInteractorTests.swift
// SampleVIPSwiftTests
//
// Created by Popilian Andrei on 12/14/19.
// Copyright © 2019 Andrei Popilian. All rights reserved.
//
import XCTest
@testable import SampleVIPSwift
final class LoginInteractorTests: XCTestCase {
private var presenter: LoginPresenterSpy!
private var interactor: LoginInteractor!
private var authService: AuthServiceSpy!
override func setUp() {
interactor = LoginInteractor(factory: self, viewController: nil, dataSource: LoginModel.DataSource())
}
override func tearDown() {
presenter = nil
interactor = nil
authService = nil
}
}
// MARK: - Tests
extension LoginInteractorTests {
func testAuthenticate() {
presenter.authExpectation = expectation(description: "authExpectation")
XCTAssertTrue(interactor.dataSource.userId == nil, "UserId should be nil at this step")
let testEmail = "email11"
let testPassword = "pass122"
interactor.doRequest(.authenticate(withEmail: testEmail, andPassword: testPassword))
wait(for: [presenter.authExpectation], timeout: 0.1)
XCTAssertEqual(testEmail, authService.passedEmail)
XCTAssertEqual(testPassword, authService.passedPassword)
XCTAssertEqual(testEmail+testPassword, presenter.passedUserId)
}
}
// MARK: - LoginFactorable
extension LoginInteractorTests: LoginFactorable {
func makePresenter(viewController: LoginDisplayLogic?) -> LoginPresentationLogic {
presenter = LoginPresenterSpy()
return presenter
}
func makeAuthService() -> AuthServiceProtocol {
authService = AuthServiceSpy()
return authService
}
}
// MARK: - Spy Classes Setup
private extension LoginInteractorTests {
final class LoginPresenterSpy: LoginPresentationLogic {
var authExpectation: XCTestExpectation!
var passedUserId: String!
func presentResponse(_ response: LoginModel.Response) {
switch response {
case .authenticate(let userId):
passedUserId = userId
authExpectation.fulfill()
}
}
}
final class AuthServiceSpy: AuthServiceProtocol {
var passedEmail: String!
var passedPassword: String!
func doAuth(withEmail email: String, password: String, completion: @escaping (Result<String, Error>) -> Void) {
passedEmail = email
passedPassword = password
let userId = email + password
completion(.success(userId))
}
}
}
| true
|
b8fd5846668e6672a7f4df6f4931a23d5a19f47c
|
Swift
|
realdoug/AudioFeature
|
/AudioFeature/Sources/AudioFeature/AudioFeature.swift
|
UTF-8
| 1,270
| 2.8125
| 3
|
[] |
no_license
|
import CAudioFeature
public protocol SupportedBySndFile {}
extension Double: SupportedBySndFile {}
extension Float: SupportedBySndFile {}
extension Int16: SupportedBySndFile {}
enum LoadSoundError: Error {
case invalidReturnType
}
// TODO: support formats other than float
public func loadSound<DType : SupportedBySndFile>(_ filename: String, as dtype: DType.Type) throws -> ([DType], SF_INFO) {
var info = SF_INFO()
info.format = 0
let file = sf_open(filename, Int32(SFM_READ), &info);
let dataSize: Int = Int(info.channels) * Int(info.frames)
if DType.self == Float.self {
var data = [Float](repeating: 0, count: dataSize) as! [DType]
sf_readf_float(file, UnsafeMutablePointer(&data), Int64(dataSize))
sf_close(file)
return (data, info)
} else if DType.self == Double.self {
var data = [Double](repeating: 0, count: dataSize) as! [DType]
sf_readf_double(file, UnsafeMutablePointer(&data), Int64(dataSize))
sf_close(file)
return (data, info)
} else if DType.self == Int16.self {
var data = [Int16](repeating: 0, count: dataSize) as! [DType]
sf_readf_int(file, UnsafeMutablePointer(&data), Int64(dataSize))
sf_close(file)
return (data, info)
} else {
throw LoadSoundError.invalidReturnType
}
}
| true
|
94b6ce4c8976f0b2e1af95003712b4cae9f52107
|
Swift
|
TalalObaidallah/week-01_HW_05_LOOPS_ARRAYS_DICT_SET
|
/HW 5.playground/Contents.swift
|
UTF-8
| 2,194
| 3.515625
| 4
|
[] |
no_license
|
print("Products sales at Nestle by Dollars")
var ProductsSalesAtNestle : Dictionary = ["KitKat":34456432, "Nescafe":14106132, "Maggi":9960312,"Nido":44506003 ]
print(ProductsSalesAtNestle)
print("")
print("products sales for Unilever by Dollars")
var ProductsSalesForUnilever : Dictionary = ["Lipton":23456000,"Breyers":1235891,"HellManns":17241412,"Marmite":11715324,]
print(ProductsSalesForUnilever)
print("")
for (UnileverTheSalesFigures) in ProductsSalesForUnilever{
print("products sold by Unilever and the sales figures by Dollars\(ProductsSalesForUnilever)")
}
for (NestleTheSalesFigures) in ProductsSalesAtNestle{
print("products sold by Nestle and the sales figures by Dollars\(NestleTheSalesFigures)")
}
var NumbersNestle: [Int] = []
print( "Numbers Of Products Company Nestle :\(ProductsSalesAtNestle.count)")
var NumbersUnilever: [Int] = []
print("Numbers Of Products Company Unilever:\(ProductsSalesForUnilever.count)")
let Nestle = [ 34,456,432, 14,106,132, 9,960,312, 44,506,003 ]
var MaxNumberNes = Int ()
for Numbers in Nestle {
MaxNumberNes = max (MaxNumberNes, Numbers as Int )
}
print("Top Selling Product From Nestle\(MaxNumberNes) ")
let Unilever = [23,456,000, 1,235,891, 17,241,412, 11,715,324 ]
var MaxNumberUni = Int ()
for Numbers in Unilever {
MaxNumberUni = max (MaxNumberUni, Numbers as Int )
}
print("Top Selling Product From Unilever\(MaxNumberUni) ")
var NestleCountries : Set = ["Saudi Arabia", "Oman", "Kuwait", "Egypt", "Jordan", "Sudan"]
var UnileverCountries : Set = ["Saudi Arabia", "Kuwait", "Iraq", "Yemen", "Emirates"]
var AllCountries = NestleCountries.union(UnileverCountries)
print("All Countries Between The Tow Company")
for Countries in AllCountries {
print(Countries)
}
var CommonCountries = NestleCountries.intersection(UnileverCountries)
print("Countries Common Between The Tow Company")
for CountriesCommon in CommonCountries {
print(CountriesCommon)
}
var NestleContriesOnly = NestleCountries.subtracting(UnileverCountries)
print("Countries Nestle sells , But Unilever Doesn't sell in")
for OnlyNestleCountries in NestleContriesOnly {
print(OnlyNestleCountries)
}
| true
|
dc1e0890329b2b9798c7c743b0cce1554c8a7fd3
|
Swift
|
danilboiko1302/AppTestBoiko
|
/AppTestBoiko/Data/HTTPRequester.swift
|
UTF-8
| 2,620
| 3
| 3
|
[] |
no_license
|
//
// HTTPRequester.swift
// AppTestBoiko
//
// Created by Данило Бойко on 02.11.2020.
//
import Foundation
class HTTPRequester{
typealias CompletionHandler = (_ data:Data?) -> Void
static func getRequest(_ url:String, completionHandler: @escaping CompletionHandler) {
let defaultSession = URLSession(configuration: .default)
var dataTask: URLSessionDataTask?
dataTask?.cancel()
if let urlComponents = URLComponents(string: url) {
if let url = urlComponents.url {
dataTask =
defaultSession.dataTask(with: url) { data, response, error in
if let error = error {
print(error.localizedDescription)
completionHandler(nil)
} else if let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
//print("I am HTTPRequester, I got new data and give it back to HTTPService.")
completionHandler( data)
}
}
dataTask?.resume()
}
}
}
static func loadImage(url:URL, completionHandler: @escaping CompletionHandler){
// print("Download Started")
// print("LOAD")
getData(from: url) { data, response, error in
guard let data = data, error == nil else { return }
//print(response?.suggestedFilename ?? url.lastPathComponent)
// print("Download Finished")
completionHandler( data)
}
}
static func loadImage(url:URL)->Data?{
return try? Data(contentsOf: url)
// DispatchQueue.global().async {
// if let data = try? Data(contentsOf: url) {
// if let image = UIImage(data: data) {
// Dispatch.DispatchQueue.main.async {
// self?.image.image = image
// }
// }
// }
// }
// return nil;
}
static func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
}
| true
|
4146e8bbee913343b69642916ca5d65f1be8f279
|
Swift
|
adventam10/ObjectsSample
|
/ObjectsSample/ObjectsSample/Screens/ContainersViewController.swift
|
UTF-8
| 7,166
| 2.53125
| 3
|
[] |
no_license
|
//
// ContainersViewController.swift
// ObjectsSample
//
// Created by am10 on 2020/06/14.
// Copyright © 2020 am10. All rights reserved.
//
import UIKit
final class SampleCollectionHeader: UICollectionReusableView {
@IBOutlet weak var label: UILabel!
}
final class Sample1TableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var subLabel: UILabel!
}
final class Sample1CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
final class ContainersViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "Sample2TableViewCell", bundle: nil), forCellReuseIdentifier: "Sample2")
}
}
@IBOutlet private weak var collectionView: UICollectionView! {
didSet {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "Sample2CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Sample2")
}
}
enum TableData {
case `default`
case sample1(text: String)
case sample2
}
enum CollectionData {
case sample1(Sample)
case sample2(Sample)
enum Sample {
case red
case blue
case green
case orange
case black
case pink
case purple
case yellow
var image: UIImage {
switch self {
case .red:
return UIImage(named: "botman_red")!
case .blue:
return UIImage(named: "botman_blue")!
case .green:
return UIImage(named: "botman_green")!
case .orange:
return UIImage(named: "botman_orange")!
case .black:
return UIImage(named: "botman_black")!
case .pink:
return UIImage(named: "botman_pink")!
case .purple:
return UIImage(named: "botman_purple")!
case .yellow:
return UIImage(named: "botman_yellow")!
}
}
var title: String {
switch self {
case .red:
return "Red"
case .blue:
return "Blue"
case .green:
return "Green"
case .orange:
return "Orange"
case .black:
return "Black"
case .pink:
return "Pink"
case .purple:
return "Purple"
case .yellow:
return "Yellow"
}
}
}
}
private let tableDataList: [TableData] = [
.default, .default, .sample1(text: "SubText"),
.sample2, .sample2, .sample1(text: "SubText"),
.sample2, .default, .sample1(text: "SubText")
]
private let collectionDataList: [CollectionData] = [
.sample1(.red), .sample2(.blue), .sample2(.green), .sample2(.yellow),
.sample1(.pink), .sample1(.black), .sample1(.purple), .sample1(.red),
.sample2(.green), .sample1(.blue), .sample1(.yellow), .sample2(.black),
.sample2(.pink), .sample2(.purple), .sample2(.blue), .sample2(.red),
]
private var sampleContainerViewController: SampleContainerViewController {
return children.first { $0 is SampleContainerViewController } as! SampleContainerViewController
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SampleContainerViewController {
// ここで初期化処理できる
print(destination.hoge)
}
}
}
extension ContainersViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableDataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch tableDataList[indexPath.row] {
case .default:
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
cell?.textLabel?.text = "Default Row: \(indexPath.row)"
return cell!
case .sample1(let text):
let cell = tableView.dequeueReusableCell(withIdentifier: "Sample1", for: indexPath) as! Sample1TableViewCell
cell.label.text = "Sample1 Row: \(indexPath.row)"
cell.subLabel.text = text
return cell
case .sample2:
let cell = tableView.dequeueReusableCell(withIdentifier: "Sample2", for: indexPath) as! Sample2TableViewCell
cell.label.text = "Sample2 Row: \(indexPath.row)"
return cell
}
}
}
extension ContainersViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("tableViewDidSelectRowAt indexPath: \(indexPath)")
}
}
extension ContainersViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionDataList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch collectionDataList[indexPath.row] {
case .sample1(let sample):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Sample1", for: indexPath) as! Sample1CollectionViewCell
cell.imageView.image = sample.image
return cell
case .sample2(let sample):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Sample2", for: indexPath) as! Sample2CollectionViewCell
cell.titleLabel.text = sample.title
cell.imageView.image = sample.image
return cell
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! SampleCollectionHeader
header.label.text = "セクション"
return header
}
}
extension ContainersViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("collectionViewDidSelectRowAt indexPath: \(indexPath)")
}
}
| true
|
f3784c742fd4949a49dcc99d38d32e76a00d2251
|
Swift
|
crescentflare/BitletSynchronizer
|
/BitletSynchronizerIOS/Example/BitletSynchronizer/Model/Session/Session.swift
|
UTF-8
| 2,504
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// Session.swift
// Bitlet Synchronizer example
//
// Session model: main session
// Stores the authenticated session
//
import UIKit
import BitletSynchronizer
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
class Session: Mappable {
// --
// MARK: Members
// --
var cookie: String?
var features: SessionFeatures?
// --
// MARK: Serialization
// --
required init?(map: Map) {
}
func mapping(map: Map) {
cookie <- map["cookie"]
features <- map["features"]
}
// --
// MARK: Bitlet integration
// --
class func bitlet(username: String, password: String) -> BitletClass {
return Settings.serverAddress?.count ?? 0 > 0 ? BitletClass(username: username, password: password) : MockedBitletClass(username: username, password: password)
}
class BitletClass: BitletHandler {
typealias BitletData = Session
private let username: String
private let password: String
init(username: String, password: String) {
self.username = username
self.password = password
}
func load(observer: BitletObserver<BitletData>) {
if let serverAddress = Settings.serverAddress, serverAddress.count > 0 {
Alamofire.request(serverAddress + "/sessions", method: .post, parameters: [ "user": username, "password": password ]).responseObject { (response: DataResponse<Session>) in
if let session = response.value {
observer.bitlet = session
observer.bitletExpireTime = .distantFuture
} else if let error = response.error {
observer.error = error
}
observer.finish()
}
}
}
}
class MockedBitletClass: BitletClass {
override func load(observer: BitletObserver<BitletData>) {
let mockedJson: [String: Any] = [
"cookie": "mocked",
"features": [
"usage": "view",
"servers": "view"
]
]
if let session = Mapper<Session>().map(JSONObject: mockedJson) {
observer.bitlet = session
observer.bitletExpireTime = .distantFuture
}
observer.finish()
}
}
}
| true
|
4405e37e933703c6ef60bb8566db0ea7aec7c7b7
|
Swift
|
kerrywang/WorkOut-Companion
|
/Physical Trainer/Physical Trainer/scoredata.swift
|
UTF-8
| 1,250
| 2.59375
| 3
|
[] |
no_license
|
//
// scoredata.swift
// Workout Companion
//
// Created by kaiyue wang on 12/8/16.
// Copyright © 2016 kaiyuewang. All rights reserved.
//
import UIKit
class datascore:NSObject,NSCoding
{
var score:Int
// var numtime:Int
struct propertyKey{
static let scoreKey = "score"
// static let numtimeKey = "numtime"
}
static let DocumentsDirectory=FileManager().urls(for: .documentDirectory, in:.userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("datascore")
func encode(with aCoder: NSCoder) {
aCoder.encode(score, forKey: propertyKey.scoreKey)
// aCoder.encode(numtime, forKey: propertyKey.numtimeKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObject(forKey: propertyKey.scoreKey) as! Int
// Because photo is an optional property of Meal, use conditional cast.
// let photo = aDecoder.decodeObject(forKey: propertyKey.numtimeKey) as! Int
// Must call designated initializer.
self.init(name: name)
}
init?(name:Int){
score=name
// numtime=time
super.init()
}
}
| true
|
628e20da19e5cb349264b127ec73df4eb8881b32
|
Swift
|
joesus/SwiftVaporHerokuCats
|
/Sources/App/Controllers/CatsController.swift
|
UTF-8
| 3,173
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
import Vapor
import HTTP
import VaporPostgreSQL
final class CatsController {
func addRoutes(drop: Droplet) {
let basic = drop.grouped("cats")
basic.get(handler: cats)
basic.get(Cat.self, handler: cat)
basic.patch(Cat.self, handler: update)
basic.post(handler: create)
basic.delete(Cat.self, handler: delete)
basic.get(Cat.self, "favorites", handler: favoritesIndex)
}
func cats(request: Request) throws -> ResponseRepresentable {
let cats = try Cat.all()
for cat in cats {
let favs = try cat.allFavorites()
cat.favorites = favs
}
return try JSON(node: cats.flatMap { try? $0.makeAllCatsJSON() })
}
func cat(request: Request, cat: Cat) throws -> ResponseRepresentable {
let favs = try cat.allFavorites()
cat.favorites = favs
return cat
}
func create(request: Request) throws -> ResponseRepresentable {
var cat = try request.cat()
try cat.save()
return cat
}
func update(request: Request, cat: Cat) throws -> ResponseRepresentable {
let new = try request.cat()
var cat = cat
setAttributesFor(cat, with: new)
try cat.save()
return cat
}
func delete(request: Request, cat: Cat) throws -> ResponseRepresentable {
let favs = try cat.allFavorites()
try favs.forEach { try $0.delete() }
try cat.delete()
return JSON([:])
}
func version(request: Request) throws -> ResponseRepresentable {
if let db = drop.database?.driver as? PostgreSQLDriver {
let version = try db.raw("SELECT version()")
return try JSON(node: version)
} else {
return "No db connection"
}
}
func favoritesIndex(request: Request, cat: Cat) throws -> ResponseRepresentable {
let children = try cat.allFavorites()
return try JSON(node: children.makeNode())
}
func setAttributesFor(_ cat: Cat, with new: Cat) {
if cat.about != new.about {
cat.about = new.about
}
if cat.name != new.name {
cat.name = new.name
}
if cat.age != new.age {
cat.age = new.age
}
if cat.city != new.city {
cat.city = new.city
}
if cat.state != new.state {
cat.state = new.state
}
if cat.cutenessLevel != new.cutenessLevel {
cat.cutenessLevel = new.cutenessLevel
}
if cat.gender != new.gender {
cat.gender = new.gender
}
if cat.adoptable != new.adoptable {
cat.adoptable = new.adoptable
}
if cat.greeting != new.greeting {
cat.greeting = new.greeting
}
if cat.pictureURL != new.pictureURL {
cat.pictureURL = new.pictureURL
}
if cat.weight != new.weight {
cat.weight = new.weight
}
}
}
extension Request {
func cat() throws -> Cat {
guard let json = json else { throw Abort.badRequest }
return try Cat(node: json)
}
}
| true
|
048d31e9ad790d7edb1525efec77d56f54a09b41
|
Swift
|
SwiftStudies/TiledKit
|
/Sources/TiledKit/Map/RenderingOrder.swift
|
UTF-8
| 2,340
| 3.3125
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2020 Swift Studies
//
// 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.
/// The rendering order for a `Map`
public enum RenderingOrder : String, Codable, CaseIterable {
/// Moving right, then down
case rightDown = "right-down"
/// Moving right, then up
case rightUp = "right-up"
/// Moving left, then down
case leftDown = "left-down"
/// Moving left, then up
case leftUp = "left-up"
/// Generatas a series of tile grid positions for the supplied map using the rendering order
/// - Parameter map: The map to use
/// - Throws: An error if the rendering order is not support
/// - Returns: An array of `TileGridPositions`
public func tileSequence(for map:Map) throws -> [TileGridPosition]{
var sequence = [TileGridPosition]()
switch self {
case .leftUp:
for y in (0..<map.mapSize.height).reversed() {
for x in (0..<map.mapSize.width).reversed() {
sequence.append(TileGridPosition(x: x, y: y))
}
}
case .leftDown:
for y in 0..<map.mapSize.height {
for x in (0..<map.mapSize.width).reversed() {
sequence.append(TileGridPosition(x: x, y: y))
}
}
case .rightUp:
for y in (0..<map.mapSize.height).reversed() {
for x in 0..<map.mapSize.width {
sequence.append(TileGridPosition(x: x, y: y))
}
}
case .rightDown:
for y in 0..<map.mapSize.height {
for x in 0..<map.mapSize.width {
sequence.append(TileGridPosition(x: x, y: y))
}
}
}
return sequence
}
}
| true
|
3ee8f24d653920924f08f8b80b6cc2df7ca09ded
|
Swift
|
otakisan/CoffeeJourneyProto
|
/CoffeeJourneyProto/Views/PickerViewController.swift
|
UTF-8
| 2,300
| 2.71875
| 3
|
[] |
no_license
|
//
// PickerViewController.swift
// CoffeeJourneyProto
//
// Created by takashi on 2014/08/31.
// Copyright (c) 2014年 TI. All rights reserved.
//
import UIKit
class PickerViewController: UIViewController {
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var selectedItemTextField: UITextField!
var pickerViewItems : [String] = []
var selectedItem : String = ""
var tagString : String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// 行もコンポーネントもインデックスはゼロ基点
self.pickerView.selectRow(pickerViewItems.count / 2, inComponent: 0, animated: true)
self.selectedItemTextField.text = self.selectedItem == "" ? pickerViewItems[pickerViewItems.count / 2] : self.selectedItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
self.selectedItem = self.selectedItemTextField.text
}
// func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String!{
// return items[row]
// }
}
extension PickerViewController : UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return pickerViewItems.count
}
}
extension PickerViewController : UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String!{
return pickerViewItems[row]
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
self.selectedItemTextField.text = self.pickerViewItems[row]
}
}
| true
|
a8e8e376e3995cfbd9d8a2bf53c8ffcc633fed49
|
Swift
|
KoYeJoon/swift_basic
|
/chapter4/classes8.playground/Contents.swift
|
UTF-8
| 346
| 3.46875
| 3
|
[] |
no_license
|
enum Car : Int{
case Benz = 0
case BMW
case Other
}
enum CarSize : String {
case Small = "소형"
case Medium = "중형"
case Big = "대형"
}
var car1 = Car(rawValue: 0)!
var size1 = CarSize(rawValue: "소형")!
print("자동차 구분 값 : \(car1.rawValue)")
print("자동차 크기 구분 값 : \(size1.rawValue)")
| true
|
cbfc0e3ad3653a60d1686dc4679d1014169f171a
|
Swift
|
Melvin24/StarkApp
|
/Stark/Shared/Protocols/PresenterDelegate.swift
|
UTF-8
| 757
| 3.171875
| 3
|
[] |
no_license
|
//
// PresenterDelegate.swift
// FruitViewer
import Foundation
/// A protocol which view controllers can conform to, to identify presenter updates.
protocol PresenterDelegate: class {
/// Delegate method sent when the presenter is about to start updating content.
func presenterWillUpdateContent()
/// Delegate method sent when the presenter has finished updating content.
func presenterDidUpdateContent()
/// Delegate method sent when the preseter failed with an error.
func presenterDidFail(withError error: Error)
}
extension PresenterDelegate {
func presenterWillUpdateContent() { }
func presenterDidUpdateContent() { }
func presenterDidFail(withError error: Error) { }
}
| true
|
0709eb25a694cd8ebd53e9a38708f418b4a72005
|
Swift
|
SwiftSnippets/swift-playgrounds
|
/Computed Properties/ComputedProperties.playground/Contents.swift
|
UTF-8
| 1,109
| 4.21875
| 4
|
[] |
no_license
|
import Cocoa
let pizzaSizeInInches = 12
var numberOfPeople = 10
let numberOfSlicesPerPerson = 4
//For computed properties, we need to use the "var" key word and we need to specify the return type explicitly
//We can get rid of the getter "get keyword" and the computed property will function in the same way
//To set the value of a computed property, we need to create a setter for it, which is executed at the exact moment where the value is set
//We can see the new assigned value using a special variable called "newValue"
var numberOfSlices : Int {
get{
return pizzaSizeInInches - 4
}
set {
print("number of slices has been assigned a new value, which is \(newValue)")
}
}
var numberOfPizzas : Int {
get {
let numberOfPeopleFedByPizza = numberOfSlices / numberOfSlicesPerPerson
return numberOfPeople / numberOfPeopleFedByPizza
}
set{
let totalSlices = numberOfSlices * newValue
numberOfPeople = totalSlices / numberOfSlicesPerPerson
}
}
print(numberOfSlices)
numberOfSlices = 9
numberOfPizzas = 5
print(numberOfPeople)
| true
|
90e405762f75ed762c7332daf41f792529b5e93f
|
Swift
|
noutram/SOFT254-2016
|
/04-App Architecture/Breadcrumbs/Breadcrumbs-2/Breadcrumbs/ViewController.swift
|
UTF-8
| 1,634
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// Breadcrumbs
//
// Created by Nicholas Outram on 20/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
lazy var locationManager : CLLocationManager = {
let loc = CLLocationManager()
//Set up location manager with defaults
loc.desiredAccuracy = kCLLocationAccuracyBest
loc.distanceFilter = kCLDistanceFilterNone
loc.delegate = self
//Optimisation of battery
loc.pausesLocationUpdatesAutomatically = true
loc.activityType = CLActivityType.fitness
loc.allowsBackgroundLocationUpdates = false
return loc
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.requestAlwaysAuthorization()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.authorizedAlways {
mapView.showsUserLocation = true
mapView.userTrackingMode = MKUserTrackingMode.follow
} else {
print("Permission Refused")
}
}
}
| true
|
6ea7eb15ce7dee085fe70a0f7f7bfed6ae3c7bf4
|
Swift
|
robertnicolo-okta/okta-idx-swift
|
/Samples/Signin Samples/MultifactorLogin.swift
|
UTF-8
| 16,742
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.
// The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
//
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and limitations under the License.
//
import Foundation
import OktaIdx
/// This class demonstrates how implementing signin with username, an optional password, and multiple factors.
///
/// The completion handler supplied to the `login` function will be invoked once, either with a fatal error, or with a token. When decisions need to be made during authentication (e.g. selecting an authenticator, or prompting the user for an MFA verification code), the `stepHandler` block supplied in the initializer will be called, giving you the option to interact with the authentication flow.
///
/// Example:
///
/// ```swift
/// self.authHandler = MultifactorLogin(configuration: configuration)
/// { step in
/// switch step {
/// case .chooseFactor(let factors):
/// // Use this to prompt the user for the factor you'd like to authenticate with.
/// if factors.contains(.email) {
/// self.authHandler?.select(factor: .email)
/// }
///
/// case .verifyCode(factor: let factor):
/// // Prompt the user for the verification code; when they supply it, call the `verify` function.
/// if factor == .email {
/// self.authHandler?.verify(code: "123456")
/// }
/// }
///
/// case .chooseMethod(let methods):
/// // Use this to prompt the user for the method you'd like to authenticate with.
/// if methods.contains(.sms) {
/// self.authHandler?.select(factor: .phone,
/// method: .sms,
/// phoneNumber: "+15551234567")
/// }
/// }
/// }
///
/// self.authHandler.login(username: "user@example.com",
/// password: "secretPassword")
/// { result in
/// switch result {
/// case .success(let token):
/// print(token)
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// Or, for user registration:
/// ```Swift
/// self.authHandler.register(username: "user@example.com",
/// password: "secretPassword",
/// profile: [
/// .firstName: "Jane",
/// .lastName: "Doe"
/// ])
/// { result in
/// switch result {
/// case .success(let token):
/// print(token)
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// Or to reset a user's password:
/// ```Swift
/// self.authHandler.resetPassword(username: "user@example.com")
/// { result in
/// switch result {
/// case .success(let token):
/// print(token)
/// case .failure(let error):
/// print(error)
/// }
/// }
///```
public class MultifactorLogin {
let configuration: IDXClient.Configuration
var username: String?
var password: String?
let stepHandler: ((Step) -> Void)?
var profile: [ProfileField: String]?
var client: IDXClient?
var response: IDXClient.Response?
var completion: ((Result<IDXClient.Token, LoginError>) -> Void)?
/// Initializer used to create a multifactor login session.
/// - Parameters:
/// - configuration: IDX client configuration.
/// - stepHandler: Closure used when input from the user is needed.
public init(configuration: IDXClient.Configuration, stepHandler: ((Step) -> Void)? = nil) {
self.configuration = configuration
self.stepHandler = stepHandler
}
// Internal convenience method used to initialize an IDXClient.
func start() {
IDXClient.start(with: configuration) { (client, error) in
guard let client = client else {
self.finish(with: error)
return
}
self.client = client
// Assign ourselves as the delegate receiver, to be notified
// when responses or errors are returned.
client.delegate = self
// Calls the IDX API to receive the first IDX response.
client.resume(completion: nil)
}
}
/// Public method that initiates the login flow.
/// - Parameters:
/// - username: Username to log in with.
/// - password: Password for the given username.
/// - completion: Comletion block invoked when login completes.
public func login(username: String, password: String, completion: @escaping (Result<IDXClient.Token, LoginError>) -> Void) {
self.username = username
self.password = password
self.completion = completion
start()
}
/// Public function used to initiate self-service user registration.
/// - Parameters:
/// - username: Username to register with.
/// - password: Password to select.
/// - profile: Profile information (e.g. firstname / lastname) for the new user.
/// - completion: Completion block invoked when registration completes.
public func register(username: String, password: String, profile: [ProfileField: String], completion: @escaping (Result<IDXClient.Token, LoginError>) -> Void) {
self.username = username
self.password = password
self.profile = profile
self.completion = completion
start()
}
/// Public function to initiate a password reset for an existing user.
///
/// The `stepHandler` supplied to the initializer is used for factor verification and password selection.
/// - Parameters:
/// - username: Username to reset.
/// - completion: Completion block invoked when registration completes.
public func resetPassword(username: String, completion: @escaping (Result<IDXClient.Token, LoginError>) -> Void) {
self.username = username
self.completion = completion
start()
}
/// Method called by you to select an authenticator. This can be used in response to a `Step.chooseFactor` stepHandler call.
/// - Parameter factor: Factor to select, or `nil` to skip.
public func select(factor: IDXClient.Authenticator.Kind?) {
guard let remediation = response?.remediations[.selectAuthenticatorAuthenticate] ?? response?.remediations[.selectAuthenticatorEnroll],
let authenticatorsField = remediation["authenticator"]
else {
finish(with: .cannotProceed)
return
}
if let factor = factor {
let factorField = authenticatorsField.options?.first(where: { field in
field.authenticator?.type == factor
})
authenticatorsField.selectedOption = factorField
remediation.proceed(completion: nil)
} else if let skipRemediation = response?.remediations[.skip] {
skipRemediation.proceed(completion: nil)
} else {
finish(with: .cannotProceed)
return
}
}
/// Method called by you to select an authentication factor method.
///
/// This can be used in response to a `Step.chooseMethod` stepHandler call.
///
/// Typically this is used to select either SMS or Voice when using a Phone factor.
/// When enrolling in a new factor, the phone number should be supplied with
/// the format: `+15551234567`. (e.g. + followed by the country-code and phone number).
/// - Parameters:
/// - factor: Factor being selected.
/// - method: Factor method (e.g. SMS or Voice) to select.
/// - phoneNumber: Optional phone number to supply, when enrolling in a new factor.
public func select(factor: IDXClient.Authenticator.Kind,
method: IDXClient.Authenticator.Method,
phoneNumber: String? = nil)
{
// Retrieve the appropriate remedation, authentication factor field and method, to
// select the appropriate method type.
guard let remediation = response?.remediations[.selectAuthenticatorAuthenticate] ?? response?.remediations[.selectAuthenticatorEnroll],
let authenticatorsField = remediation["authenticator"],
let factorField = authenticatorsField.options?.first(where: { field in
field.authenticator?.type == factor
}),
let methodOption = factorField["methodType"]?.options?.first(where: { field in
field.value as? String == method.stringValue
})
else {
finish(with: .cannotProceed)
return
}
authenticatorsField.selectedOption = methodOption
factorField["phoneNumber"]?.value = phoneNumber
remediation.proceed(completion: nil)
}
/// Method used to verify a factor.
///
/// When a factor is selected, the user will receive a verification code. Once they receive it, you will use this method to supply it back to Okta.
/// - Parameter code: Verification code received and supplied by the user.
public func verify(code: String) {
guard let remediation = response?.remediations[.challengeAuthenticator] ?? response?.remediations[.enrollAuthenticator]
else {
finish(with: .cannotProceed)
return
}
remediation.credentials?.passcode?.value = code
remediation.proceed(completion: nil)
}
/// Enumeration representing the different actionable steps that the
/// `stepHandler` can receive.
///
/// You can use these values to determine what UI to present to the user to select factors, authenticator methods, and to verify authenticator verification codes.
public enum Step {
case chooseFactor(_ factors: [IDXClient.Authenticator.Kind])
case chooseMethod(_ methods: [IDXClient.Authenticator.Method])
case verifyCode(factor: IDXClient.Authenticator.Kind)
}
public enum ProfileField: String {
case firstName, lastName
}
public enum LoginError: Error {
case error(_ error: Error)
case message(_ string: String)
case cannotProceed
case unexpectedAuthenticator
case noStepHandler
case unknown
}
}
extension MultifactorLogin: IDXClientDelegate {
// Delegate method sent when an error occurs.
public func idx(client: IDXClient, didReceive error: Error) {
finish(with: error)
}
// Delegate method sent when a token is successfully exchanged.
public func idx(client: IDXClient, didReceive token: IDXClient.Token) {
finish(with: token)
}
// Delegate method invoked whenever an IDX response is received, regardless
// of what action or remediation is called.
public func idx(client: IDXClient, didReceive response: IDXClient.Response) {
self.response = response
// If a response is successful, immediately exchange it for a token.
guard !response.isLoginSuccessful else {
response.exchangeCode(completion: nil)
return
}
// If we can select enroll profile, immediately proceed to that.
if let remediation = response.remediations[.selectEnrollProfile],
profile != nil
{
remediation.proceed(completion: nil)
return
}
// If no remediations are present, abort the login process.
guard let remediation = response.remediations.first else {
finish(with: .cannotProceed)
return
}
// If any error messages are returned, report them and abort the process.
if let message = response.messages.allMessages.first {
finish(with: .message(message.message))
return
}
// If we have no password, we assume we're performing an account recovery.
if password == nil,
(remediation.type == .identify || remediation.type == .challengeAuthenticator),
let passwordAuthenticator = response.authenticators.current as? IDXClient.Authenticator.Password
{
passwordAuthenticator.recover(completion: nil)
return
}
// Handle the various remediation choices the client may be presented with within this policy.
switch remediation.type {
case .identify: fallthrough
case .identifyRecovery:
remediation.identifier?.value = username
remediation.credentials?.passcode?.value = password
remediation.proceed(completion: nil)
// The challenge authenticator remediation is used to request a passcode
// of some sort from the user, either the user's password, or an
// authenticator verification code.
case .enrollAuthenticator: fallthrough
case .challengeAuthenticator:
guard let authenticator = remediation.authenticators.first else {
finish(with: .unexpectedAuthenticator)
return
}
switch authenticator.type {
// The challenge authenticator remediation is used to request a passcode
// of some sort from the user, either the user's password, or an
// authenticator verification code.
case .password:
if let password = password {
remediation.credentials?.passcode?.value = password
remediation.proceed(completion: nil)
} else {
fallthrough
}
default:
guard let stepHandler = stepHandler else {
finish(with: .noStepHandler)
return
}
stepHandler(.verifyCode(factor: authenticator.type))
}
case .selectAuthenticatorEnroll: fallthrough
case .selectAuthenticatorAuthenticate:
// Find the factor types available to the user at this time.
let factors: [IDXClient.Authenticator.Kind]
factors = remediation["authenticator"]?
.options?.compactMap({ field in
field.authenticator?.type
}) ?? []
// If a password is supplied, immediately select the password factor if it's given as a choice.
if factors.contains(.password) && password != nil {
select(factor: .password)
} else {
guard let stepHandler = stepHandler else {
finish(with: .noStepHandler)
return
}
stepHandler(.chooseFactor(factors))
}
case .authenticatorEnrollmentData: fallthrough
case .authenticatorVerificationData:
guard let stepHandler = stepHandler else {
finish(with: .noStepHandler)
return
}
// Find the methods available to the user.
let methods: [IDXClient.Authenticator.Method]
methods = remediation.authenticators.flatMap({ authenticator in
authenticator.methods ?? []
})
stepHandler(.chooseMethod(methods))
case .enrollProfile:
remediation["userProfile.firstName"]?.value = profile?[.firstName]
remediation["userProfile.lastName"]?.value = profile?[.lastName]
remediation["userProfile.email"]?.value = username
remediation.proceed(completion: nil)
default:
finish(with: .cannotProceed)
}
}
}
// Utility functions to help return responses to the caller.
extension MultifactorLogin {
func finish(with error: Error?) {
if let error = error {
finish(with: .error(error))
} else {
finish(with: .unknown)
}
}
func finish(with error: LoginError) {
completion?(.failure(error))
completion = nil
}
func finish(with token: IDXClient.Token) {
completion?(.success(token))
completion = nil
}
}
| true
|
e578ac0344c6c5292f35b7ffde8e0fbb3540dd44
|
Swift
|
minyigoh/Hipstagram
|
/Hipstagram/UncoveredContentViewController.swift
|
UTF-8
| 2,371
| 2.796875
| 3
|
[] |
no_license
|
// UncoveredContentViewController.swift
// Hipstagram
// For View Controllers where textfield-keyboard is concerned,subclass "UncoveredContentViewController".
// Substitute default "UIViewController" with "UncoveredContentViewController".
// Bind textField "Editing did Begin" & "Editing did End" to IBAction "textFieldEditingDidBegin" & "textFieldEditingDidEnd"
// http://glaucocustodio.com/2015/09/26/content-locked-under-keyboard-another-approach-to-solve/
// Created by Joshua Su on 09/09/2016.
// Copyright © 2016 Goh Min-Yi. All rights reserved.
import UIKit
class UncoveredContentViewController: UIViewController {
var activeField:UIView?
var changedY = false
var keyboardHeight : CGFloat = 300
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UncoveredContentViewController.keyboardViewWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UncoveredContentViewController.keyboardViewWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil);
}
func keyboardViewWillShow(sender: NSNotification) {
let kbSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
keyboardHeight = kbSize!.height
var aRect = self.view.frame;
aRect.size.height = aRect.size.height - kbSize!.height - CGFloat(20);
if activeField != nil && !CGRectContainsPoint(aRect, activeField!.frame.origin) {
if (!changedY) {
self.view.frame.origin.y -= keyboardHeight
}
changedY = true
}
}
func keyboardViewWillHide(sender: NSNotification) {
if changedY {
self.view.frame.origin.y += keyboardHeight
}
changedY = false
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self);
}
@IBAction func textFieldEditingDidBegin(sender: UITextField){
//println("did begin")
activeField = sender
}
@IBAction func textFieldEditingDidEnd(sender: UITextField) {
//println("did end")
activeField = nil
}
}
| true
|
b4a366740f047e4acfaff293a09f189dbb7e7e83
|
Swift
|
gdelarosa/Shine
|
/Shine/SlideUpCell.swift
|
UTF-8
| 1,418
| 2.65625
| 3
|
[] |
no_license
|
//
// SlideUpCell.swift
// Shine
//
// Created by Gina De La Rosa on 9/21/16.
// Copyright © 2016 Gina De La Rosa. All rights reserved.
//
import Foundation
import UIKit
class BaseCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
}
}
class SlideUpCell: BaseCell { // Add Flag inside of slide menu and create message.
// var flag: Flag? {
// didSet {
// nameLabel.text = flag?.name
//
// if let imageName = flag?.imageName {
// iconImageView.image = UIImage(named: imageName)?.imageWithRendingModel(.AlwaysTemplate)
// iconImageView.tintColor = UIColor.darkGrayColor()
// }
// }
//
//}
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Flag"
//label.font = UIFont.systemFontSize(13)
return label
}()
// let iconImageView: UIImageView = {
// let imageView = UIImageView()
// imageView.image = UIImage(named: "Flag")
// return imageView
// }
//
override func setupViews() {
super.setupViews()
addSubview(nameLabel)
//addSubview(iconImageView)
// addConstraint
}
}
| true
|
ec333abba7247547c1c05ed6629d65300297c1aa
|
Swift
|
cyambo/Password-Factory
|
/Password Factory iOS/Extensions/UIView+Extensions.swift
|
UTF-8
| 6,812
| 2.75
| 3
|
[] |
no_license
|
//
// UIView+Extensions.swift
// Password Factory iOS
//
// Created by Cristiana Yambo on 12/18/17.
// Copyright © 2017 Cristiana Yambo. All rights reserved.
//
import Foundation
extension UIView {
/// Adds an array of VFL constraints
///
/// - Parameters:
/// - constraints: array of vfl constraints
/// - views: views dictionary
/// - options: NSLayoutFormatOptions
/// - metrics: view metrics
func addVFLConstraints(constraints: [String], views: [String : Any], options: NSLayoutFormatOptions = [], metrics: [String : Any] = [:]) {
translatesAutoresizingMaskIntoConstraints = false
for (_ , view) in views {
(view as? UIView)?.translatesAutoresizingMaskIntoConstraints = false
}
for c in constraints {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: c, options: options, metrics: metrics, views: views))
}
}
/// Removes subviews from UIView
func removeSubviews() {
subviews.forEach({
if !($0 is UILayoutSupport) {
$0.removeSubviews()
$0.removeFromSuperview()
}
})
}
/// Removes constraints from subviews
func removeConstraintsOnSubviews() {
subviews.forEach({
$0.removeConstraints($0.constraints)
})
}
/// Removes subviews and constraints from view
func removeSubviewsAndConstraints() {
subviews.forEach({
$0.removeSubviewsAndConstraints()
$0.removeConstraints($0.constraints)
$0.removeFromSuperview()
})
}
/// gets the parent viewController from a view
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
func addBorder(_ sides: UIRectEdge, color: UIColor = UIColor.gray, width: CGFloat = 0.5) {
var borders = [CGRect]()
if sides.contains(.top) {
borders.append(CGRect(x:0,y: 0, width: frame.size.width, height:width))
}
if sides.contains(.right) {
borders.append(CGRect(x: frame.size.width - width,y: 0, width:width, height: frame.size.height))
}
if sides.contains(.bottom) {
borders.append(CGRect(x:0, y: frame.size.height - width, width: frame.size.width, height:width))
}
if sides.contains(.left) {
borders.append(CGRect(x:0, y:0, width:width, height: frame.size.height))
}
if let s = layer.sublayers {
for l in s {
//if we find that class, remove it so we don't have duplicate borders
if l.isKind(of: BorderedLayer.self) {
l.removeFromSuperlayer()
}
}
}
for b in borders {
let border = BorderedLayer() //using an empty class to identify borders
layer.masksToBounds = true
border.backgroundColor = color.cgColor
border.frame = b
layer.addSublayer(border)
}
}
func addGradient(_ topColor: UIColor = UIColor(white: 1, alpha: 1), _ bottomColor: UIColor = UIColor(white: 0.98, alpha: 1)) {
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [topColor.cgColor, bottomColor.cgColor]
layer.insertSublayer(gradient, at: 0)
}
/// Rounds the corners of view
///
/// - Parameter withBorder: add border if needed
/// - Parameter andRadius: setRadius
func roundCorners(withBorder: Bool = false, andRadius radius : CGFloat = 10) {
layer.cornerRadius = radius
layer.masksToBounds = true
if(withBorder) {
addBorder()
}
}
/// Round specific corners of a view
///
/// - Parameters:
/// - view: view to round corners
/// - corners: UIRectCorner array
/// - withBorder: add a border
func roundCorners(corners: UIRectCorner, withBorder: Bool = false) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: 10.0, height: 10.0))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
if(withBorder) {
addBorder()
}
}
/// adds a standard border
func addBorder(_ width: CGFloat = 0.5, color : UIColor = UIColor.gray) {
layer.borderColor = color.cgColor
layer.borderWidth = width
}
/// Adds a drop shadow
func dropShadow() {
clipsToBounds = false
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.3
layer.shadowOffset = CGSize(width: -10, height: 10)
layer.shadowRadius = 10
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
}
/// Fills view in a superview
///
/// - Parameters:
/// - view: view to fill container with
/// - margins: any margins around the view
func fillViewInContainer(_ view: UIView, margins: Int = 0) {
let views = ["sub" : view]
view.translatesAutoresizingMaskIntoConstraints = false
addVFLConstraints(constraints: ["H:|-(margin)-[sub]-(margin)-|","V:|-(margin)-[sub]-(margin)-|"], views: views,options: [], metrics: ["margin": margins])
}
/// Centers a view vertically in view
///
/// - Parameters:
/// - view: view to center
func centerViewVertically(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
translatesAutoresizingMaskIntoConstraints = false
view.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
/// Centers a view horizontally in view
///
/// - Parameters:
/// - view: view to center
func centerViewHorizontally(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
translatesAutoresizingMaskIntoConstraints = false
view.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
/// Makes the attributes of two views equal
///
/// - Parameters:
/// - firstView: first view
/// - secondView: second view
/// - attribute: NSLayoutAttribute to make equal
func equalAttributesTo(_ firstView: UIView, _ secondView: UIView, attribute: NSLayoutAttribute) {
addConstraint(NSLayoutConstraint.init(item: firstView, attribute: attribute, relatedBy: .equal, toItem: secondView, attribute: attribute, multiplier: 1, constant: 1))
}
}
class BorderedLayer: CALayer {}
| true
|
45285143445715508c2c53720290e74253304811
|
Swift
|
d8815460/cilo
|
/Cilo/StoreListAnnotationView.swift
|
UTF-8
| 1,704
| 2.8125
| 3
|
[] |
no_license
|
//
// StoreListAnnotationView.swift
// ZappShopFinder
//
// Created by Szabolcs Sztányi on 2014. 11. 12..
// Copyright (c) 2014. Szabolcs Sztányi. All rights reserved.
//
import UIKit
import MapKit
/**
* A custom MKAnnotationView to be able to present it on the mapView.
*/
class StoreListAnnotationView: MKAnnotationView {
/// Custom view that helps identifying the Store object better
private var markerView: StoreListMarkerView!
/// The position of the annotation view in the list.
var positionNumber: Int = 0 {
didSet { // update the markerView's property as well when set to update its label
markerView.positionNumber = positionNumber
}
}
/**
Initialiser method. Set the frame for the view, and add the markerView as a subview.
- parameter annotation: the annotation
- parameter reuseIdentifier: the identifier
- returns: self
*/
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
frame = CGRectMake(0.0, 0.0, 30.0, 30.0)
markerView = StoreListMarkerView(frame: CGRectMake(0.0, 0.0, 30.0, 30.0))
markerView.userInteractionEnabled = true
addSubview(markerView)
}
/**
Initialiser method
- parameter aDecoder: NSCoder object
- returns: self
*/
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
Initialiser method
- parameter frame: frame to use
- returns: self
*/
override init(frame: CGRect) {
super.init(frame: frame)
}
}
| true
|
024b01fb27a47d0d522b1f2af5f84ebcd41affef
|
Swift
|
tonybragin/imdbClient
|
/ItemView.swift
|
UTF-8
| 2,074
| 2.609375
| 3
|
[] |
no_license
|
//
// ItemViewController.swift
// imdbClient
//
// Created by TONY on 17/05/2019.
// Copyright © 2019 TONY. All rights reserved.
//
import UIKit
class ItemView: UIView {
var posterImage: UIImageView!
var titleLabel: UILabel!
var topInfoLabel: UILabel!
var ratingLabel: UILabel!
var otherInfoLabel: UILabel!
let lineSize = 25
var contentHeight: CGFloat!
override init(frame: CGRect) {
super.init(frame: frame)
posterImage = UIImageView(frame: CGRect(x: frame.midX - 120, y: 10, width: 240, height: 360))
posterImage.backgroundColor = .black
self.addSubview(posterImage)
titleLabel = UILabel(frame: CGRect(x: 10, y: Int(posterImage.frame.maxY + 10), width: Int(frame.width - 20), height: lineSize*3))
titleLabel.textAlignment = .center
titleLabel.font = .preferredFont(forTextStyle: .title1)
titleLabel.numberOfLines = 2
titleLabel.text = "Title"
self.addSubview(titleLabel)
topInfoLabel = UILabel(frame: CGRect(x: 10, y: Int(titleLabel.frame.maxY + 10), width: Int(frame.width - 20), height: lineSize*2))
topInfoLabel.numberOfLines = 2
topInfoLabel.text = "Year, Runtime, Genre"
self.addSubview(topInfoLabel)
ratingLabel = UILabel(frame: CGRect(x: 10, y: Int(topInfoLabel.frame.maxY + 10), width: Int(frame.width - 20), height: lineSize*5))
ratingLabel.numberOfLines = 5
ratingLabel.text = "Ratings"
self.addSubview(ratingLabel)
otherInfoLabel = UILabel(frame: CGRect(x: 10, y: Int(ratingLabel.frame.maxY - 90), width: Int(frame.width - 20), height: lineSize*20))
otherInfoLabel.numberOfLines = 20
otherInfoLabel.text = "Released, Rated, Plot, Actors, Director, Writer"
self.addSubview(otherInfoLabel)
contentHeight = otherInfoLabel.frame.maxY + 10
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
66c7881212b4e3993a3cb14eb4259b72fda6dfd8
|
Swift
|
ChawlaBhavuk/TransformerApp
|
/TransformerApp/View/Controllers/SurvivorViewController.swift
|
UTF-8
| 1,515
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// SurvivorViewController.swift
// TransformerApp
//
// Created by Bhavuk Chawla on 18/09/20.
// Copyright © 2020 Bhavuk Chawla. All rights reserved.
//
import UIKit
class SurvivorViewController: UIViewController {
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.tableFooterView = UIView()
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.register(cellClass: TranformersTableViewCell.self)
}
}
var survivors = [Transformer]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = AppLocalization.survivors
if survivors.count > 0 {
self.tableView.resetBackgroundView()
} else {
self.tableView.setEmptyView(title: AppLocalization.noData, message: AppLocalization.noSurvivor)
}
self.tableView.reloadData()
}
}
// MARK: TableView Delegates
extension SurvivorViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return survivors.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TranformersTableViewCell = tableView.dequeue(cellClass:
TranformersTableViewCell.self, forIndexPath: indexPath)
cell.item = survivors[indexPath.row]
return cell
}
}
| true
|
df9988cdc63b8cf37cedbf2bfc209919e75952bb
|
Swift
|
Mamadoukaba/UIScrollView
|
/ScrollViewSample/ViewController.swift
|
UTF-8
| 1,014
| 3
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ScrollViewSample
//
// Created by Mamadou Kaba on 6/14/16.
// Copyright © 2016 Mamadou Kaba. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//MARK - Properties
//Initializing Properties needed to build the ScrollView and ImageView
var imageView: UIImageView!
var scrollView: UIScrollView!
var image = UIImage(named: "SSGSS_GOKU.png")
//MARK: View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
//Constructing ImageView
imageView = UIImageView(image: image)
//Constructing ScrollView
scrollView = UIScrollView(frame: view.bounds)
//Setting ScrollViewSize
scrollView.contentSize = imageView.frame.size
//Adding the UIImage inside of the scrollView.
scrollView.addSubview(imageView)
//Adding the scrollView to the View.
view.addSubview(scrollView)
}
}
| true
|
3134a4de82462e90422f61aeb9ec8104ea3d121c
|
Swift
|
craleigh318/IkesLoveAndSandwiches
|
/Ike's Love and Sandwiches/Ike's Love and Sandwiches/FoodItem.swift
|
UTF-8
| 1,074
| 2.6875
| 3
|
[] |
no_license
|
//
// FoodItem.swift
// Ike's Love and Sandwiches
//
// Created by Christopher Raleigh on 2016-09-04.
// Copyright © 2016 Ike's Place. All rights reserved.
//
import Foundation
class FoodItem: InternalNameObject, PFoodItem, PReceiptPrintableRow, Hashable {
var hashValue: Int
private(set) var price: Int
init(internalName: String, price: Int = 0) {
hashValue = Hashing.getNextHashValue()
self.price = price
super.init(internalName: internalName)
}
func receiptPrintRow() -> IkesOrderRow {
let formattedPrice = IkesOrder.formatPrice(price: price)
var rightText: String
if let fp = formattedPrice {
rightText = fp
} else {
rightText = ""
}
return IkesOrderRow(leftCell: name, rightCell: rightText)
}
func receiptPrint() -> IkesOrderTable {
return IkesOrderTable(rows: [receiptPrintRow()])
}
}
func ==(lhs: FoodItem, rhs: FoodItem) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| true
|
6a63f50ac131ecdb1505a2bc4fffbd9eb60223da
|
Swift
|
apple/swift-format
|
/Sources/SwiftFormat/Core/FormatPipeline.swift
|
UTF-8
| 1,368
| 2.546875
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that invokes individual format rules.
///
/// Note that this type is not a `SyntaxVisitor` or `SyntaxRewriter`. That is because, at this time,
/// we need to run each of the format rules individually over the entire syntax tree. We cannot
/// interleave them at the individual nodes like we do for lint rules, because some rules may want
/// to access the previous or next tokens. Doing so requires walking up to the parent node, but as
/// the tree is rewritten by one formatting rule, it will not be reattached to the tree until the
/// entire `visit` method has returned.
///
/// This file will be extended with a `visit` method in Pipelines+Generated.swift.
struct FormatPipeline {
/// The formatter context.
let context: Context
/// Creates a new format pipeline.
init(context: Context) {
self.context = context
}
}
| true
|
d961f9976d34577087d83d8a44dbbf8f772e77e5
|
Swift
|
mran3/ios-biometrics-example
|
/BiometricExample/TimeAPI.swift
|
UTF-8
| 2,007
| 3.15625
| 3
|
[] |
no_license
|
//
// TimeAPI.swift
// BiometricExample
//
// Created by Andres Acevedo on 11/07/2018.
// Copyright © 2018 Andres Acevedo. All rights reserved.
//
import Foundation
enum TimeResult {
case success((String,String))
case failure(String)
}
struct TimeAPI {
//private static let baseURLString = "http://date.jsontest.com" //This server is not working right now
private static let baseURLString = "http://www.mocky.io/v2/5b46ec543200006e00301cee"
func parseDateTime(from data:Data)->TimeResult{
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard
let jsonDictionary = jsonObject as? [String:Any],
let date = jsonDictionary["date"] as? String,
let time = jsonDictionary["time"] as? String
else {
return .failure("Invalid JSON data")
}
return .success((date,time))
} catch let error {
return .failure("Error trying to convert data to JSON - " + error.localizedDescription)
}
}
func getDateTime(onComplete: @escaping (TimeResult)->Void){
let request = NetworkUtilities.sharedInstance.createGetRequest(endpoint: TimeAPI.baseURLString)
NetworkUtilities.sharedInstance.makeRequest(endPoint: request){
(data, response, error) in
guard error == nil else {
return onComplete(.failure(error!.localizedDescription))
}
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
if (statusCode != 200) {
return onComplete(.failure("Failed with code status: \(statusCode)"))
}
}
if let data = data {
return onComplete(self.parseDateTime(from: data))
}
}
}
}
| true
|
e345b3e210935a9abfdd9830b1fd5f25461c1c18
|
Swift
|
PureSwift/Bluetooth
|
/Sources/BluetoothGATT/GATTLocationName.swift
|
UTF-8
| 1,702
| 3.109375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// GATTLocationName.swift
// Bluetooth
//
// Created by Carlos Duclos on 7/4/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Location Name
The Location Name characteristic describes the name of the location the device is installed in.
- SeeAlso: [Location Name](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.location_name.xml)
*/
@frozen
public struct GATTLocationName: RawRepresentable, GATTCharacteristic {
public static var uuid: BluetoothUUID { return .locationName }
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init?(data: Data) {
guard let rawValue = String(data: data, encoding: .utf8)
else { return nil }
self.init(rawValue: rawValue)
}
public var data: Data {
return Data(rawValue.utf8)
}
}
extension GATTLocationName: Equatable {
public static func == (lhs: GATTLocationName, rhs: GATTLocationName) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension GATTLocationName: CustomStringConvertible {
public var description: String {
return rawValue
}
}
extension GATTLocationName: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(rawValue: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(rawValue: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(rawValue: value)
}
}
| true
|
b416ae2122c706ab59c513fd976278e287dab577
|
Swift
|
CasperNEw/Yandex_contest
|
/Mobilization.playground/Contents.swift
|
UTF-8
| 11,365
| 3.53125
| 4
|
[] |
no_license
|
/*
В Яндексе снова стартует проект «Мобилизация»! Компания набирает на трёхмесячную подготовку n молодых людей, увлечённых мобильной разработкой. В начале проекта был проведён тест, где скилл участника i в разработке был оценен как ai, а скилл в управлении как bi.
На время проекта участников необходимо разделить на две равные по количеству участников команды — разработчиков и менеджеров. Планируется сделать это таким образом, чтобы максимизировать суммарную пользу, приносимую всеми участниками. Если участнику достанется роль разработчика, его польза будет равняться ai, в противном случае — bi.
Но даже занятые проектом, участники находят время для получения новых знаний! Иногда участники приносят сертификаты о прохождении курсов, где сказано, что скилл участника i в разработке или же в управлении увеличился на di. В таком случае может быть выгодно переформировать команды для максимизации суммарной пользы (равные размеры команд необходимо сохранить).
Ваша задача помочь Яндексу и после рассмотрения каждого нового принесённого участником сертификата посчитать текущую суммарную пользу команд.
Формат ввода
В первой строке входного файла дано число n (2 ≤ n ≤ 2 ⋅ 105, n — чётное) — количество участников проекта. Вторая строка задаёт n целых чисел ai (0 ≤ ai ≤ 109) — скилл каждого из участников в разработке. Следующая строка в том же формате задаёт скилл участников в управлении bi (0 ≤ bi ≤ 109).
Следующая строка содержит целое число m (1 ≤ m ≤ 105) — количество принесённых участниками сертификатов. Каждая из следующих m строк содержит три целых числа numi, typei, di (1 ≤ numi ≤ n, 1 ≤ typei ≤ 2, 1 ≤ di ≤ 104) — номер участника, тип увеличиваемого скилла (1 — разработка, 2 — управление) и значение увеличения соответствующего навыка.
Формат вывода
После обработки каждого запроса на поступление нового сертификата выведите текущую суммарную пользу всех участников.
Пример 1.
Ввод
4
7 15 3 4
10 10 0 6
3
1 1 4
4 1 6
2 2 10
Вывод
34
35
43
*/
struct Student: Hashable {
let number: Int
let devSkill: Int
let manageSkill: Int
}
var count: Int = 0
var dev: [Int] = []
var manage: [Int] = []
// MARK: First - bad decision
func setupMobilization(_ studentCount: Int,_ devSkills: [Int],_ manageSkills: [Int]) -> Int {
count = studentCount
dev = devSkills
manage = manageSkills
if studentCount < 2 || studentCount > 2 * 105 || studentCount % 2 != 0 { return -1 }
if devSkills.count < 0 || devSkills.count > 109 { return -1 }
if manageSkills.count < 0 || manageSkills.count > 109 { return -1 }
var students = Set<Student>()
for index in 0..<studentCount {
students.insert(Student(number: index + 1, devSkill: devSkills[index], manageSkill: manageSkills[index]))
}
var totalSkills = 0
var devTeam = Set<Student>()
students.sorted { (studentOne, studentTwo) -> Bool in
return studentOne.devSkill > studentTwo.devSkill
}.forEach { (student) in
if devTeam.count != studentCount / 2 {
devTeam.insert(student)
totalSkills += student.devSkill
}
}
let otherTeam = students.subtracting(devTeam)
otherTeam.forEach { (student) in
totalSkills += student.manageSkill
}
var anotherTotalSkills = 0
let manageTeam = Set<Student>()
students.sorted { (studentOne, studentTwo) -> Bool in
return studentOne.manageSkill > studentTwo.manageSkill
}.forEach { (student) in
if devTeam.count != studentCount / 2 {
devTeam.insert(student)
anotherTotalSkills += student.manageSkill
}
}
let anotherOtherTeam = students.subtracting(manageTeam)
anotherOtherTeam.forEach { (student) in
anotherTotalSkills += student.devSkill
}
return totalSkills > anotherTotalSkills ? totalSkills : anotherTotalSkills
}
func addSert(_ sertCount: Int,_ serts: [(Int, Int, Int)]) {
if sertCount < 1 || sertCount > 105 { return }
serts.forEach { (numi, typei, di) in
if numi < 1 || numi > count { return }
if typei < 1 || typei > 2 { return }
if di < 1 || di > 104 { return }
}
if sertCount != serts.count { return }
serts.forEach { (numi, typei, di) in
switch typei {
case 1:
dev[numi - 1] += di
case 2:
manage[numi - 1] += di
default:
break
}
print(setupMobilization(count, dev, manage))
}
}
//setupMobilization(4, [7, 15, 3, 4], [10, 10, 0, 6])
//addSert(3, [(1, 1, 4), (4, 1, 6), (2, 2, 10)])
// --------------------------------------------------
// MARK: Second - expensive decision
var skills = Set<Int>()
func findMembers(_ students: inout Set<Student>,_ command: Set<Student>) {
var newCommand = command
students.forEach { (student) in
if newCommand.count < students.count / 2 {
if !newCommand.contains(student) {
newCommand.insert(student)
findMembers(&students, newCommand)
}
} else {
var totalSkills = 0
var anotherTotalSkills = 0
newCommand.forEach { (student) in
totalSkills += student.devSkill
anotherTotalSkills += student.manageSkill
}
let otherTeam = students.subtracting(newCommand)
otherTeam.forEach { (student) in
totalSkills += student.manageSkill
anotherTotalSkills += student.devSkill
}
skills.insert(totalSkills)
skills.insert(anotherTotalSkills)
}
}
}
func setupAgain(_ studentCount: Int,_ devSkills: [Int],_ manageSkills: [Int]) {
count = studentCount
dev = devSkills
manage = manageSkills
if studentCount < 2 || studentCount > 2 * 105 || studentCount % 2 != 0 { return }
if devSkills.count < 0 || devSkills.count > 109 { return }
if manageSkills.count < 0 || manageSkills.count > 109 { return }
var students = Set<Student>()
for index in 0..<studentCount {
students.insert(Student(number: index + 1, devSkill: devSkills[index], manageSkill: manageSkills[index]))
}
students.forEach { (student) in
var team = Set<Student>()
team.insert(student)
findMembers(&students, team)
}
}
func againAddSert(_ sertCount: Int,_ serts: [(Int, Int, Int)]) {
if sertCount < 1 || sertCount > 105 { return }
serts.forEach { (numi, typei, di) in
if numi < 1 || numi > count { return }
if typei < 1 || typei > 2 { return }
if di < 1 || di > 104 { return }
}
if sertCount != serts.count { return }
serts.forEach { (numi, typei, di) in
switch typei {
case 1:
dev[numi - 1] += di
case 2:
manage[numi - 1] += di
default:
break
}
setupAgain(count, dev, manage)
print(skills.max() as Any)
print(skills)
}
}
//setupAgain(4, [7, 15, 3, 4], [10, 10, 0, 6])
//againAddSert(3, [(1, 1, 4), (4, 1, 6), (2, 2, 10)])
// --------------------------------------------------
// MARK: Are you kidding me?! Third try ...
func addSertThird(_ sertCount: Int,_ serts: [(Int, Int, Int)]) {
if sertCount < 1 || sertCount > 105 { return }
serts.forEach { (numi, typei, di) in
if numi < 1 || numi > count { return }
if typei < 1 || typei > 2 { return }
if di < 1 || di > 104 { return }
}
if sertCount != serts.count { return }
serts.forEach { (numi, typei, di) in
switch typei {
case 1:
dev[numi - 1] += di
case 2:
manage[numi - 1] += di
default:
break
}
if let total = setupThird(count, dev, manage) {
print(total)
}
}
}
func setupThird(_ studentCount: Int,_ devSkills: [Int],_ manageSkills: [Int]) -> Int? {
count = studentCount
dev = devSkills
manage = manageSkills
if studentCount < 2 || studentCount > 2 * 105 || studentCount % 2 != 0 { return nil }
if devSkills.count < 0 || devSkills.count > 109 { return nil }
if manageSkills.count < 0 || manageSkills.count > 109 { return nil }
var students = Set<Student>()
for index in 0..<studentCount {
students.insert(Student(number: index + 1, devSkill: devSkills[index], manageSkill: manageSkills[index]))
}
var devTeam = Set<Student>()
var manageTeam = Set<Student>()
students.sorted { (studentOne, studentTwo) -> Bool in
var firstDi = 0
var secondDi = 0
if studentOne.devSkill > studentOne.manageSkill {
firstDi = studentOne.devSkill - studentOne.manageSkill
} else {
firstDi = studentOne.manageSkill - studentOne.devSkill
}
if studentTwo.devSkill > studentTwo.manageSkill {
secondDi = studentTwo.devSkill - studentTwo.manageSkill
} else {
secondDi = studentTwo.manageSkill - studentTwo.devSkill
}
return firstDi > secondDi
}.forEach { (student) in
if devTeam.count != students.count / 2 {
if manageTeam.count != students.count / 2 {
student.devSkill >= student.manageSkill ? devTeam.insert(student) : manageTeam.insert(student)
} else {
devTeam = devTeam.union(students.subtracting(manageTeam))
}
} else {
manageTeam = manageTeam.union(students.subtracting(devTeam))
}
}
var totalSkills = 0
devTeam.forEach { (student) in
totalSkills += student.devSkill
}
manageTeam.forEach { (student) in
totalSkills += student.manageSkill
}
return totalSkills
}
setupThird(4, [7, 15, 3, 4], [10, 10, 0, 6])
addSertThird(3, [(1, 1, 4), (4, 1, 6), (2, 2, 10)])
| true
|
d53bc0fb30337fda539b9d5021660e717cc2355f
|
Swift
|
JohnSmithCoder1/Petstagram
|
/Petstagram/Service Layer/Requests/CommentRequests.swift
|
UTF-8
| 1,730
| 3.046875
| 3
|
[] |
no_license
|
//
// CommentRequests.swift
// Petstagram
//
// Created by J S on 8/24/21.
//
import Foundation
struct GetCommentsForPostRequest: APIRequest {
private let postId: UUID
init(postId: UUID) {
self.postId = postId
}
typealias Response = [Comment]
var method: HTTPMethod { return .GET }
var path: String { return "/comments" }
var contentType: String { return "application/json" }
var additionalHeaders: [String : String] { return [:] }
var body: Data? { return nil }
var params: CommentParams? {
return CommentParams(postId: postId.uuidString)
}
func handle(response: Data) throws -> [Comment] {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(Response.self, from: response)
}
}
struct AddCommentToPostRequest: APIRequest {
private let comment: Comment
init(postId: UUID, caption: String) {
self.comment = Comment(postId: postId, caption: caption)
}
typealias Response = Comment
var method: HTTPMethod { return .POST }
var path: String { return "/comments" }
var contentType: String { return "application/json" }
var additionalHeaders: [String : String] { return [:] }
var body: Data? {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
return try? encoder.encode(comment)
}
var params: EmptyParams? { return nil }
func handle(response: Data) throws -> Comment {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(Response.self, from: response)
}
}
| true
|
94a5576abf5be74cadc69c8be6f5ba6124785e41
|
Swift
|
albertinopadin/Swiftchain
|
/Swiftchain/Swiftchain.swift
|
UTF-8
| 5,427
| 2.921875
| 3
|
[] |
no_license
|
//
// Swiftchain.swift
// Swiftchain
//
// Created by Albertino Padin on 3/11/17.
// Copyright © 2017 Albertino Padin. All rights reserved.
//
import Foundation
protocol SwiftchainDelegate {
func broadcastResponseLatestMsg()
}
// Maybe we could conform this class to certain protocols later on
class Swiftchain<T> where T: Equatable {
var blockchain: [Block<T>]
var delegate: SwiftchainDelegate?
init() {
self.blockchain = []
let genesisBlock = getGenesisBlock()
self.blockchain.append(genesisBlock)
}
func getGenesisBlock() -> Block<T> {
let genesisData: T? = nil
let currentTimestamp = Swiftchain.getCurrentTimeStamp()
let genesisHash: String = Swiftchain.calculateHash(index: 0, previousHash: "0", timestamp: currentTimestamp, data: genesisData)
return Block(index: 0,
previousHash: "0",
timestamp: currentTimestamp,
data: genesisData,
hash: genesisHash)
}
func generateNextBlock(data: T) -> Block<T>? {
guard let previousBlock = self.getLatestBlock() else {
return nil
}
let nextIndex = previousBlock.index + 1
let nextTimestamp = Swiftchain.getCurrentTimeStamp()
let nextHash = Swiftchain.calculateHash(index: nextIndex,
previousHash: previousBlock.hash,
timestamp: nextTimestamp,
data: data)
return Block(index: nextIndex,
previousHash: previousBlock.hash,
timestamp: nextTimestamp,
data: data,
hash: nextHash)
}
func calculateHashForBlock(block: Block<T>) -> String {
return Swiftchain.calculateHash(index: block.index,
previousHash: block.previousHash,
timestamp: block.timestamp,
data: block.data)
}
func addBlock(newBlock: Block<T>) {
if self.isValidNewBlock(newBlock: newBlock, previousBlock: self.getLatestBlock()) {
self.blockchain.append(newBlock)
}
}
func isValidNewBlock(newBlock: Block<T>, previousBlock: Block<T>?) -> Bool {
// TODO: Should include proper log function in the future:
if let prev = previousBlock {
if prev.index + 1 != newBlock.index {
print("Invalid index for block: \(newBlock)")
return false
}
else if prev.hash != newBlock.previousHash {
print("Invalid previous hash for block: \(newBlock)")
return false
}
else if self.calculateHashForBlock(block: newBlock) != newBlock.hash {
print("Invalid hash for block: \(newBlock)")
print("Calculated: \(self.calculateHashForBlock(block: newBlock)), passed in block: \(newBlock.hash)")
return false
}
// All checks passed:
return true
} else {
// We should always have at least the genesis block in the blockchain
// If we do not something is very wrong:
return false
}
}
func getLatestBlock() -> Block<T>? {
return self.blockchain.last
}
func replaceChain(newBlocks: [Block<T>]) {
if isValidChain(blockchainToValidate: newBlocks) && newBlocks.count > self.blockchain.count {
print("Recieved blockchain is valid; replacing current with new.")
self.blockchain = newBlocks
self.delegate?.broadcastResponseLatestMsg()
}
}
func isValidChain(blockchainToValidate: [Block<T>]) -> Bool {
if let genesisBlockToValidate = blockchainToValidate.first {
if genesisBlockToValidate != self.getGenesisBlock() {
return false
}
}
for i in 1 ..< blockchainToValidate.count {
if !isValidNewBlock(newBlock: blockchainToValidate[i], previousBlock: blockchainToValidate[i - 1]) {
return false
}
}
return true
}
/* STATIC FUNCTIONS */
// Returns the Unix time in milliseconds:
static func getCurrentTimeStamp() -> UInt64 {
return UInt64(NSDate().timeIntervalSince1970 * 1000.0)
}
static func calculateHash(index: UInt64, previousHash: String, timestamp: UInt64, data: T?) -> String {
let dataString = "\(index)\(previousHash)\(timestamp)\(String(describing: data))"
return Swiftchain.sha256(dataString: dataString) ?? ""
}
static func sha256(dataString: String) -> String? {
guard let stringData = dataString.data(using: String.Encoding.utf8) else { return nil }
var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes({ digestBytes in
stringData.withUnsafeBytes( { stringBytes in
CC_SHA256(stringBytes, CC_LONG(stringData.count), digestBytes)
})
})
let digestString = digestData.map { String(format: "%02hhx", $0) }.joined()
return digestString
}
}
| true
|
b9082d5b2bd611cfb194c4dae567bd4681b1b75e
|
Swift
|
VladIacobIonut/Playground
|
/MapEstate/UI/Scenes/Examples/TinderExample/BasicSpringlyCollectionViewCell.swift
|
UTF-8
| 3,595
| 2.734375
| 3
|
[] |
no_license
|
//
// BasicSpringlyCollectionViewCell.swift
// MapEstate
//
// Created by Vlad on 05/10/2018.
// Copyright © 2018 Vlad. All rights reserved.
//
import UIKit
class BasicSpringlyCollectionViewCell: UICollectionViewCell {
// MARK: - Properties
var shouldDismiss: VoidClosure?
let label = UILabel()
private var initialOffset: CGPoint = .zero
private var swipingVelocityThreshold: CGFloat = 800
private var rotationDegreeRatio: CGFloat = 0.50
private var divisor: CGFloat = 0
private var initialCenter: CGPoint = .zero
private var swipeableView = UIView()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
initialCenter = self.contentView.center
divisor = contentView.frame.width / rotationDegreeRatio
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - LayoutSubviews
override func layoutSubviews() {
super.layoutSubviews()
self.swipeableView.transform = CGAffineTransform.identity
}
// MARK: - Functions
private func setupUI() {
contentView.addSubview(swipeableView)
swipeableView.clipsToBounds = true
swipeableView.backgroundColor = UIColor.randomColor()
swipeableView.layer.cornerRadius = 25
swipeableView.addSubview(label)
swipeableView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
label.snp.makeConstraints {
$0.leading.equalToSuperview().offset(20)
$0.bottom.equalToSuperview().offset(-60)
}
label.font = UIFont.ceraPro(size: 34)
label.textColor = UIColor.white
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
swipeableView.addGestureRecognizer(panGesture)
}
@objc private func handlePan(recognizer: UIPanGestureRecognizer) {
let touchPoint = recognizer.location(in: self)
let xFromCenter = swipeableView.center.x - center.x
let scale = min(100 / abs(xFromCenter), 1)
switch recognizer.state {
case .began:
initialOffset = CGPoint(x: touchPoint.x - swipeableView.center.x, y: touchPoint.y - swipeableView.center.y)
case .changed:
swipeableView.center = CGPoint(x: touchPoint.x - initialOffset.x, y: touchPoint.y - initialOffset.y)
swipeableView.transform = CGAffineTransform(rotationAngle: xFromCenter / divisor).scaledBy(x: scale, y: scale)
case .ended, .cancelled:
handleSwipeEnding(for: recognizer.velocity(in: self).x)
default:
return
}
}
private func handleSwipeEnding(for xVelocity: CGFloat) {
let velocity = abs(xVelocity)
guard velocity > swipingVelocityThreshold else {
moveCardToInitialState()
return
}
swipeCardAway(with: xVelocity)
}
private func moveCardToInitialState() {
UIView.animate(withDuration: 0.2) {
self.swipeableView.center = self.center
}
swipeableView.transform = CGAffineTransform.identity
}
private func swipeCardAway(with xVelocity: CGFloat) {
UIView.animate(withDuration: 0.2) {
self.swipeableView.center = CGPoint(x: self.swipeableView.center.x + xVelocity, y: self.swipeableView.center.y)
}
shouldDismiss?()
}
}
| true
|
516d30d98e6529601e46be9cf24c6bd24953cf26
|
Swift
|
dehesa/Command-Line
|
/Template Query/Source/Utils/Sanitizer.swift
|
UTF-8
| 3,695
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
/// Namespace for the sanitizer functions.
enum Sanitizer {
/// Parses the Command-Line arguments for the targeted forlder path.
/// - parameters arguments: The Command-Line arguments. The first one shall be the name of the program.
static func parse(arguments: [String]) -> Arguments {
var introspected: (path: String?, key: String?) = (nil, nil)
var index = 1
while index < arguments.count {
switch arguments[index] {
case "-k":
guard case .none = introspected.key else {
CommandLine.write(to: .stderr, "Only one PLIST key is expected.\n")
exit(EXIT_FAILURE)
}
index += 1
guard index < arguments.count else {
CommandLine.write(to: .stderr, "No PLIST key was provided.\n")
exit(EXIT_FAILURE)
}
introspected.key = arguments[index]
default:
guard case .none = introspected.path else {
CommandLine.write(to: .stderr, "File paths cannot be written more than once.\n")
exit(EXIT_FAILURE)
}
introspected.path = arguments[index]
}
index += 1
}
guard case .some(let path) = introspected.path,
case .some(let key) = introspected.key, !key.isEmpty else {
CommandLine.write(to: .stderr, "A file/folder path and a PLIST key must be provided for the program to work.\n")
exit(EXIT_FAILURE)
}
let url = URL(fileURLWithPath: path)
guard let isReachable = try? url.checkResourceIsReachable(), isReachable else {
CommandLine.write(to: .stderr, "Invalid path: \"path\"\n")
exit(EXIT_FAILURE)
}
// TODO: Validate that the url points to a folder
return Arguments(url: url, key: key)
}
}
extension Sanitizer {
struct Arguments {
let url: URL
let key: String
}
}
extension Sanitizer {
static func representation(_ value: Any, indentationLevel level: Int) -> String {
let tab = String(repeating: "\t", count: level)
if let boolean = value as? Bool {
return (boolean) ? "true" : "false"
} else if let number = value as? NSNumber {
return number.stringValue
} else if let string = value as? String {
return "\"" + string + "\""
} else if let array = value as? [Any] {
guard !array.isEmpty else { return "[]" }
return "[" + array.map { representation($0, indentationLevel: level+1) }.joined(separator: ", ") + "]"
} else if let dictionary = value as? [String:Any] {
guard !dictionary.isEmpty else { return "{}" }
let indentation = tab + "\t"
var result = "{\n"
for (key, value) in dictionary {
result += indentation + key + ": " + representation(value, indentationLevel: level + 1) + "\n"
}
return result + tab + "}"
} else {
print(type(of: value))
return "\(value)"
}
}
static func curateURL(_ url: URL, prefix: TemplatesPath) -> String {
let prefix = "file://" + prefix.rawValue
let suffix = ".xctemplate/TemplateInfo.plist"
return url.absoluteString
.dropFirst(prefix.count)
.dropLast(suffix.count)
.replacingOccurrences(of: "%20", with: " ")
}
}
| true
|
b15d9abfcc555bb5372964a17e37bd41c2910efc
|
Swift
|
lmorelato/wallet-hub-macos
|
/WalletHub/WalletHub/Utils/CurrencyUtils.swift
|
UTF-8
| 1,728
| 3.125
| 3
|
[] |
no_license
|
import Foundation
public class CurrencyUtils {
/*
* Gets the currency factor between to currencies
*/
static func getFactor(from: String, to: String) -> Double {
var factor : Double = 1;
if (from == "BRL"){
switch to {
case "CAD":
factor = 0.394238;
break;
case "UAH":
factor = 8.26686;
break;
case "USD":
factor = 0.304952;
break;
default:
break;
}
}
if (from == "CAD"){
switch to {
case "BRL":
factor = 2.53723;
break;
case "UAH":
factor = 20.9660;
break;
case "USD":
factor = 0.774916;
break;
default:
break;
}
}
if (from == "UAH"){
switch to {
case "BRL":
factor = 0.121048;
break;
case "CAD":
factor = 0.0477007;
break;
case "USD":
factor = 0.0369849;
break;
default:
break;
}
}
if (from == "USD"){
switch to {
case "BRL":
factor = 3.27849;
break;
case "CAD":
factor = 1.29004;
break;
case "UAH":
factor = 27.0127;
break;
default:
break;
}
}
return factor;
}
}
| true
|
184e2d756d96b92c33cbaf083e12198f35996b7f
|
Swift
|
neyrpg/FoodCad
|
/FoodCad/model/Refeicao.swift
|
UTF-8
| 1,391
| 3.09375
| 3
|
[] |
no_license
|
//
// Refeicao.swift
// FoodCad
//
// Created by Ney on 11/3/17.
// Copyright © 2017 Giltecnologia. All rights reserved.
//
import Foundation
class Refeicao : NSObject, NSCoding{
let nome:String
let felicidade:Int
var itens = Array<Item>()
init(nome:String, felicidade:Int, itens: Array<Item> = []) {
self.nome = nome
self.felicidade = felicidade
self.itens = itens
}
init(nome:String, felicidade:Int) {
self.nome = nome
self.felicidade = felicidade
}
func todasCalorias() -> Double {
var total = 0.0
for item in itens {
total += item.calorias
}
return total
}
func detalhes() -> String {
var msg = "Itens: "
for item in itens {
msg += "\n \(item.nome) = \(item.calorias.description)"
}
return msg
}
func encode(with aCoder: NSCoder) {
aCoder.encode(nome, forKey : "nome")
aCoder.encode(felicidade, forKey: "felicidade")
aCoder.encode(itens, forKey: "itens")
}
required init?(coder aDecoder: NSCoder) {
nome = aDecoder.decodeObject(forKey: "nome") as! String
felicidade = aDecoder.decodeInteger(forKey: "felicidade")
itens = aDecoder.decodeObject(forKey: "itens") as! Array
}
}
| true
|
17af267990eb2e68782f8a004b21bc613c3a4f69
|
Swift
|
Xecca/LeetCodeProblems
|
/35.SearchInsertPosition.swift
|
UTF-8
| 2,024
| 4.15625
| 4
|
[] |
no_license
|
// Solved by Xecca
import Foundation
//35. Search Insert Position
//Difficult: Easy
//https://leetcode.com/problems/search-insert-position/
//Runtime: 20 ms, faster than 100.00% of Swift online submissions for Search Insert Position.
//Memory Usage: 14.6 MB, less than 10.01% of Swift online submissions for Search Insert Position.
//
//Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
//
//You must write an algorithm with O(log n) runtime complexity.
//
//Constraints:
//
//1 <= nums.length <= 10^4
//-10^4 <= nums[i] <= 10^4
//nums contains distinct values sorted in ascending order.
//-10^4 <= target <= 10^4
//
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
let length = nums.count
var insPos = 0
if target > nums[length - 1] {
insPos = length
} else if target < nums[0] {
insPos = 0
} else {
var leftInd = 0
var rightInd = length - 1
var middle = 0
while leftInd < rightInd {
middle = (rightInd + leftInd) / 2
if target < nums[middle] {
if rightInd - leftInd == 1 {
break
}
rightInd = middle
} else if target > nums[middle] {
if rightInd - leftInd == 1 {
middle += 1
break
}
leftInd = middle
} else {
return middle
}
}
insPos = middle
}
return insPos
}
//Example 1:
//
//Input: nums = [1,3,5,6], target = 5
//Output: 2
//Example 2:
//
//Input: nums = [1,3,5,6], target = 2
//Output: 1
//Example 3:
//
//Input: nums = [1,3,5,6], target = 7
//Output: 4
//Test cases:
let input = [1,3,5,6]
let input2 = 2
let answer = 1
if searchInsert(input, input2) == answer { print("Correct!") } else { print("Error! Expexted: \(answer)") }
| true
|
ef51d0d5cdd8d9f605cf92219cea289d402bc874
|
Swift
|
yusuftrn/SwiftUI-iOS-Dev
|
/CombineLearn/PublisherAndSubscriber/CombineBeginnerApp/TransformingOperators/ScanOperator.swift
|
UTF-8
| 558
| 3.203125
| 3
|
[] |
no_license
|
//
// ScanOperator.swift
// PublisherAndSubscriber
//
// Created by Yusuf Turan on 9.06.2021.
//
import SwiftUI
struct ScanOperator: View {
func scan() {
let publisher = (1...10).publisher
let subs = publisher.scan([]) { numbers, value -> [Int] in
numbers + [value]
}.sink {
print($0)
}
subs.cancel()
}
var body: some View {
Text("Hello, World!")
.onAppear() {
scan()
}
}
}
struct ScanOperator_Previews: PreviewProvider {
static var previews: some View {
ScanOperator()
}
}
| true
|
43b67f75784977175779a6f53d7a83241a260d60
|
Swift
|
lovehuyang/LuanQiBaZao
|
/Swift/基本语法/第二部分/06-监听类的属性改变.playground/Contents.swift
|
UTF-8
| 535
| 3.6875
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
// swift中没有set方法,所以用属性监听器监听属性变化
class Person :NSObject{
// 属性监听器
var name :String?{
// 属性即将改变时时进行监听
willSet{
print("1、属性即将发生改变")
print (newValue)
}
// 属性已经改变时进行监听
didSet{
print (name)
print (oldValue)
}
}
}
let p = Person()
p.name = "胡鲁阳"
| true
|
062d7b729f333f54a7cba607b4b3e7837e039ce9
|
Swift
|
bluemix/MovileNextCourse
|
/MovileNextV2/MovileNextV2/ViewControllers/ShowMoreViewController.swift
|
UTF-8
| 1,896
| 2.546875
| 3
|
[] |
no_license
|
//
// ShowMoreViewController.swift
// MovileNextV2
//
// Created by Dennis de Oliveira on 03/07/15.
// Copyright (c) 2015 Movile. All rights reserved.
//
import UIKit
import TraktModels
class ShowMoreViewController: UIViewController {
@IBOutlet weak var detailsTextView: UITextView!
var show:Show?
override func viewDidLoad() {
super.viewDidLoad()
// Carregando qualquer coisa para testar
//self.detailsTextView.text = self.show?.overview
self.loadDetails()
}
deinit {
println("\(self.dynamicType) deinit")
}
func loadDetails() {
var showDetails:String = ""
if let broadcasting = self.show?.network {
showDetails += "Broadcasting: \(broadcasting)"
}
if let status:ShowStatus = self.show?.status {
showDetails += "\nStatus: \(status.rawValue)"
}
if let startedIn = self.show?.firstAired {
// Cria uma formatação de data para obter apenas o ano
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let year = formatter.stringFromDate(startedIn) as String
showDetails += "\nStarted in: \(year)"
}
if let country = self.show?.country {
showDetails += "\nCountry: \(country.uppercaseString)"
}
self.detailsTextView.text = showDetails
}
// MARK: - ShowInternalProtocol
func intrinsicContentSize() -> CGSize {
var overviewHeight = self.detailsTextView.intrinsicContentSize().height + 39
//println("Details height: \(overviewHeight)")
return CGSize(width: self.view.frame.width, height: overviewHeight)
}
}
| true
|
8d9ba893d53ea78408345275a3d526dbeec2640b
|
Swift
|
gyugyu90/SwiftStudy
|
/algorithm/Kakao3-5)Autocomplete.playground/Contents.swift
|
UTF-8
| 976
| 3.78125
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
let words1 = ["go","gone","guild"]
let words2 = ["abc","def","ghi","jklm"]
let words3 = ["word","war","warrior","world"]
fileprivate func matchingWordCount(subject : String, from words: [String]) -> Int{
return words.filter { (word) -> Bool in
return word.contains(subject)
}.count
}
fileprivate func solution(words : [String]) -> Int{
var resultArray = [Int]()
for word in words {
var charStack = ""
for char in word {
charStack += String(char)
let matchingWordCnt = matchingWordCount(subject: charStack, from: words)
if matchingWordCnt == 1 || charStack.count == word.count {
print(charStack)
resultArray.append(charStack.count)
break
}
}
}
return resultArray.reduce(0, +)
}
solution(words: words1)
solution(words: words2)
solution(words: words3)
| true
|
e50d255dffe0d92dc7c6e8d70d1b7aef69100ae0
|
Swift
|
juancruzlepore/EscobaMac
|
/EscobaMac/Card/EscobaCard.swift
|
UTF-8
| 572
| 2.875
| 3
|
[] |
no_license
|
//
// EscobaCard.swift
// EscobaMac
//
// Created by Juan Cruz Lepore on 12/2/19.
// Copyright © 2019 Juan Cruz Lepore. All rights reserved.
//
import Foundation
class EscobaCard: Card {
var card: BaseCard
init(_ value: Int, _ palo: Palo) {
card = BaseCard(value: value, palo: palo)
}
func isGoldSeven() -> Bool{
return card.palo == .oro && card.value == 7
}
override func getValue() -> Int {
return card.value <= 7 ? card.value : card.value - 2
}
override func getPalo() -> Palo {
return card.palo
}
}
| true
|
173c2f02d95aa869104cd2334c1cc9e6bad16792
|
Swift
|
ridwan40046/Image-Machine
|
/Image Machine/Library Local/UITableView+BackgroundMessage.swift
|
UTF-8
| 1,162
| 2.6875
| 3
|
[] |
no_license
|
//
// UITableView+BackgroundMessage.swift
// Choose My Story
//
// Created by Martin Tjandra on 07/08/18.
// Copyright © 2018 idesolusiasia. All rights reserved.
//
import Foundation
import UIKit
extension UITableView {
func backgroundMessage (text: String?) {
// let view = UIView.init(frame: self.bounds);
// view.autoresizingMask = [.flexibleWidth, .flexibleHeight];
// view.backgroundColor = UIColor.clear;
let label = UILabel.init(frame: self.bounds);
label.font = UIFont.systemFont(ofSize: 14);
label.textColor = UIColor.lightGray;
label.textAlignment = .center;
label.text = text;
label.numberOfLines = 0;
// label.sizeToFit();
// label.center = view.center;
label.autoresizingMask = [.flexibleWidth, .flexibleHeight];
// view.addSubview(label);
self.backgroundView = label;
}
func backgroundMessageNoData() {
backgroundMessage(text: "No data to display. Pull down to refresh.");
}
func backgroundMessageFailed() {
backgroundMessage(text: "Failed to load. Pull down to refresh.");
}
}
| true
|
347eaaf4854f01a837d5763bf4ff3811f1beea6d
|
Swift
|
gitter-badger/ramda.swift
|
/Example/Tests/Extensions/IdenticalTests.swift
|
UTF-8
| 864
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// IdenticalTests.swift
// Ramda
//
// Created by Justin Guedes on 2016/09/18.
// Copyright (c) 2016 CocoaPods. All rights reserved.
//
import XCTest
import Ramda
class IdenticalTests: XCTestCase {
class Singleton {
static var string = "String"
}
func testShouldReturnTrueWhenStringsAreIdentical() {
let result = R.identical(&Singleton.string, to: &Singleton.string)
XCTAssertTrue(result)
}
func testShouldReturnFalseWhenStringsAreNotIdentical() {
var string1 = "String"
var string2 = "String"
let result = R.identical(&string1, to: &string2)
XCTAssertFalse(result)
}
func testShouldReturnFalseWhenArraysAreNotIdentical() {
var array1 = []
var array2 = []
let result = R.identical(&array1, to: &array2)
XCTAssertFalse(result)
}
}
| true
|
3704f50bd954f59fbb113bcbdee2b1835c59cd92
|
Swift
|
superjohan/jmlcollection
|
/jmlcollection/specialdiscoversion/BackgroundView.swift
|
UTF-8
| 8,695
| 2.84375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// BackgroundView.swift
// demo
//
// Created by Johan Halin on 15.9.2020.
// Copyright © 2020 Dekadence. All rights reserved.
//
import Foundation
import UIKit
class BackgroundView: UIView {
let viewCount = 64
let views: [UIView]
let viewContainer = UIView()
override init(frame: CGRect) {
var views = [UIView]()
for _ in 0...self.viewCount {
let view = UIView()
view.backgroundColor = .white
views.append(view)
}
self.views = views
super.init(frame: frame)
for view in views {
self.viewContainer.addSubview(view)
}
addSubview(self.viewContainer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animate(configuration: Configuration, duration: TimeInterval) {
self.transform = .identity
self.layer.removeAllAnimations()
self.viewContainer.layer.removeAllAnimations()
self.frame = self.superview!.bounds
self.viewContainer.frame = self.superview!.bounds
switch configuration {
case .verticalRandom:
verticalRandom(duration: duration)
case .verticalLinear:
verticalLinear(duration: duration)
case .horizontalRandom:
horizontalRandom(duration: duration)
case .horizontalLinear:
horizontalLinear(duration: duration)
case .angledRandom:
angledRandom(duration: duration)
case .angledLinear:
angledLinear(duration: duration)
}
}
private func verticalRandom(duration: TimeInterval) {
let width = (self.bounds.size.width / CGFloat(self.viewCount)) / 2.0
let colorConfig = Bool.random() ? Color.random : Color.white
for (i, view) in self.views.enumerated() {
view.frame = CGRect(
x: (width * CGFloat(i)) * 2.0,
y: 0,
width: width,
height: self.bounds.size.height
)
view.backgroundColor = color(colorConfig)
}
UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear], animations: {
for view in self.views {
view.frame.origin.x += CGFloat.random(in: -100...100)
}
}, completion: nil)
}
private func verticalLinear(duration: TimeInterval) {
let width = (self.bounds.size.width / CGFloat(self.viewCount)) / 2.0
for (i, view) in self.views.enumerated() {
view.frame = CGRect(
x: (width * CGFloat(i)) * 2.0,
y: 0,
width: width,
height: self.bounds.size.height
)
view.backgroundColor = color(.black)
}
let animation = CABasicAnimation(keyPath: "position.x")
animation.fromValue = NSNumber(floatLiteral: Double(self.bounds.size.width / 2.0) - (Double(width) * 2.0))
animation.toValue = NSNumber(floatLiteral: Double(self.bounds.size.width / 2.0))
animation.duration = duration / 4.0
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.repeatCount = Float.infinity
self.viewContainer.layer.add(animation, forKey: "xposition")
}
private func horizontalRandom(duration: TimeInterval) {
let height = self.bounds.size.height / CGFloat(self.viewCount)
let colorConfig = randomColorConfig()
for (i, view) in self.views.enumerated() {
view.frame = CGRect(
x: 0,
y: height * CGFloat(i),
width: self.bounds.size.width,
height: height
)
view.backgroundColor = color(colorConfig)
}
UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear], animations: {
for view in self.views {
view.frame.origin.y += CGFloat.random(in: -100...100)
}
}, completion: nil)
}
private func horizontalLinear(duration: TimeInterval) {
let height = (self.bounds.size.height / CGFloat(self.viewCount)) / 2.0
for (i, view) in self.views.enumerated() {
view.frame = CGRect(
x: 0,
y: (height * CGFloat(i)) * 2.0,
width: self.bounds.size.width,
height: height
)
view.backgroundColor = color(.black)
}
let animation = CABasicAnimation(keyPath: "position.y")
animation.fromValue = NSNumber(floatLiteral: Double(self.bounds.size.height / 2.0) - (Double(height) * 2.0))
animation.toValue = NSNumber(floatLiteral: Double(self.bounds.size.height / 2.0))
animation.duration = duration / 4.0
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.repeatCount = Float.infinity
self.viewContainer.layer.add(animation, forKey: "yposition")
}
private func angledRandom(duration: TimeInterval) {
let parentBounds = self.superview!.bounds
let length = sqrt(pow(parentBounds.size.width, 2.0) + pow(parentBounds.size.width, 2.0))
self.frame = CGRect(
x: parentBounds.midX - (length / 2.0),
y: parentBounds.midY - (length / 2.0),
width: length,
height: length
)
self.transform = CGAffineTransform.identity.rotated(by: CGFloat.pi * (0.25 + CGFloat(Int.random(in: 0...3)) * 0.5))
let height = (self.bounds.size.height / CGFloat(self.viewCount)) / 2.0
let colorConfig = randomColorConfig()
for (i, view) in self.views.enumerated() {
view.frame = CGRect(
x: 0,
y: 2.0 * height * CGFloat(i),
width: self.bounds.size.width,
height: height
)
view.backgroundColor = color(colorConfig)
}
UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear], animations: {
for view in self.views {
view.frame.origin.y += CGFloat.random(in: -100...100)
}
}, completion: nil)
}
private func angledLinear(duration: TimeInterval) {
let parentBounds = self.superview!.bounds
let length = sqrt(pow(parentBounds.size.width, 2.0) + pow(parentBounds.size.width, 2.0))
self.frame = CGRect(
x: parentBounds.midX - (length / 2.0),
y: parentBounds.midY - (length / 2.0),
width: length,
height: length
)
self.viewContainer.frame = CGRect(
x: 0,
y: 0,
width: length,
height: length
)
self.transform = CGAffineTransform.identity.rotated(by: CGFloat.pi * (0.25 + CGFloat(Int.random(in: 0...3)) * 0.5))
let height = (self.bounds.size.height / CGFloat(self.viewCount)) / 2.0
for (i, view) in self.views.enumerated() {
view.frame = CGRect(
x: 0,
y: (height * CGFloat(i)) * 2.0,
width: self.bounds.size.width,
height: height
)
view.backgroundColor = color(.black)
}
let animation = CABasicAnimation(keyPath: "position.y")
animation.fromValue = NSNumber(floatLiteral: Double(self.bounds.size.height / 2.0) - (Double(height) * 2.0))
animation.toValue = NSNumber(floatLiteral: Double(self.bounds.size.height / 2.0))
animation.duration = duration / 4.0
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.repeatCount = Float.infinity
self.viewContainer.layer.add(animation, forKey: "yposition")
}
private func randomColorConfig() -> Color {
switch Int.random(in: 0...2) {
case 0:
return .white
case 1:
return .black
case 2:
return .random
default:
abort()
}
}
private func color(_ color: Color) -> UIColor {
switch color {
case .white:
return .white
case .black:
return .black
case .random:
return Bool.random() ? .white : .black
}
}
enum Configuration {
case verticalRandom
case verticalLinear
case horizontalRandom
case horizontalLinear
case angledRandom
case angledLinear
}
enum Color {
case white
case black
case random
}
enum Position {
case back
case mask
case fore
}
}
| true
|
97b2540b73809143a25a39e105b2aba9240daacd
|
Swift
|
gudwnsepdy/Koktail
|
/Koktail/Koktail/DataModel/PlaceDetail.swift
|
UTF-8
| 1,848
| 2.890625
| 3
|
[] |
no_license
|
//
// PlaceDetail.swift
// Koktail
//
// Created by 최승명 on 2021/07/24.
//
import SwiftyJSON
class PlaceDetail {
var result: Detail
init(_ json: JSON) {
result = Detail(json["result"])
}
}
struct Detail {
var formatted_address = ""
var formatted_phone_number = ""
var geometry: Geometry
var icon = ""
var name = ""
var rating = 0.0
var place_id = ""
var reference = ""
var website = ""
var url = ""
var types = [String]()
var reviews = [Review]()
init(_ json: JSON) {
formatted_address = json["formatted_address"].stringValue
formatted_phone_number = json["formatted_phone_number"].stringValue
geometry = Geometry(json["geometry"])
icon = json["icon"].stringValue
name = json["name"].stringValue
rating = json["rating"].doubleValue
place_id = json["place_id"].stringValue
reference = json["reference"].stringValue
website = json["website"].stringValue
url = json["url"].stringValue
if let array = json["types"].array {
types = array.map { String($0.stringValue) }
}
if let array = json["reviews"].array {
reviews = array.map { Review($0) }
}
}
}
struct Review {
var author_name = ""
var author_url = ""
var profile_photo_url = ""
var rating = 0.0
var relative_time_description = ""
var text = ""
init(_ json: JSON) {
author_name = json["author_name"].stringValue
author_url = json["author_url"].stringValue
profile_photo_url = json["profile_photo_url"].stringValue
rating = json["rating"].doubleValue
relative_time_description = json["relative_time_description"].stringValue
text = json["text"].stringValue
}
}
| true
|
a2df0cc5ac96eb4fd8e0b04006b4c750cdeada5a
|
Swift
|
nrgway/nrgWayWellnessSwiftUI
|
/nrgWayWellness/core/CoreContentView.swift
|
UTF-8
| 3,274
| 3.140625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// nrgWayWellness
//
// Created by Hosein Alimoradi on 8/14/1399 AP.
// Copyright © 1399 wellness. All rights reserved.
//
import SwiftUI
//MARK:-
struct CoreContentView: View {
@State var alertMsg = ""
var alert: Alert {
Alert(title: Text(""), message: Text(alertMsg), dismissButton: .default(Text("OK")))
}
var body: some View {
Text("Hello")
}
}
//MARK:-
//MARK:- Textfields
struct textFieldWithSeperator: View {
var placeholder: String
var image: String
// var text : String
@State var username: String = ""
@State var name = ""
@Environment(\.editMode) var mode
var body: some View {
VStack {
HStack {
Image(image)
.padding(.leading, 20)
TextField(placeholder, text: $username)
.frame(height: 40, alignment: .center)
.padding(.leading, 10)
.padding(.trailing, 10)
.font(.system(size: 15, weight: .regular, design: .default))
.imageScale(.small)
// .disabled(mode?.wrappedValue == .inactive)
// .textFieldStyle(RoundedBorderTextFieldStyle())
}
Seperator()
}
}
}
struct buttons: View {
var btnText: String
var body: some View {
Text(btnText)
.font(.body)
.foregroundColor(.black)
// .frame(width: 150, height: 40)
.padding()
}
}
//MARK:-
//MARK:- Button with background & shaadow
struct buttonWithBackground: View {
var btnText: String
var body: some View {
HStack {
// Spacer()
Text(btnText)
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(width: 140, height: 50)
.background(lightblueColor)
.clipped()
.cornerRadius(5.0)
.shadow(color: lightblueColor, radius: 5, x: 0, y: 5)
// Spacer()
}
}
}
//MARK:-
//MARK:- Alert View
struct alertView: View {
@State var alertMsg = ""
var alert: Alert {
Alert(title: Text(""), message: Text(alertMsg), dismissButton: .default(Text("OK")))
}
var body: some View {
Text("Alert")
}
}
//MARK: - Date Picker View
struct DatePickerView: View {
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}
@State private var birthDate = Date()
var body: some View {
VStack {
DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) {
Text("Select a date")
}
Text("Date is \(birthDate, formatter: dateFormatter)")
}
}
}
struct CoreContentView_Previews: PreviewProvider {
static var previews: some View {
CoreContentView()
}
}
| true
|
f4538d6b6bcdf0d54164187c9cf5e368279c6de6
|
Swift
|
TokamakUI/OpenCombine
|
/Sources/OpenCombine/Publishers/Optional.Publisher.swift
|
UTF-8
| 10,503
| 3.15625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// Optional.Publisher.swift
//
//
// Created by Sergej Jaskiewicz on 17.06.2019.
//
extension Optional {
/// A namespace for disambiguation when both OpenCombine and Combine are imported.
///
/// Combine extends `Optional` with a nested type `Publisher`.
/// If you import both OpenCombine and Combine (either explicitly or implicitly,
/// e. g. when importing Foundation), you will not be able to write
/// `Optional<Int>.Publisher`, because Swift is unable to understand
/// which `Publisher` you're referring to.
///
/// So you have to write `Optional<Int>.OCombine.Publisher`.
///
/// This bug is tracked [here](https://bugs.swift.org/browse/SR-11183).
///
/// You can omit this whenever Combine is not available (e. g. on Linux).
public struct OCombine {
fileprivate let optional: Optional
fileprivate init(_ optional: Optional) {
self.optional = optional
}
public var publisher: Publisher {
return Publisher(optional)
}
/// The type of a Combine publisher that publishes the value of a Swift optional
/// instance to each subscriber exactly once, if the instance has any value at
/// all.
///
/// In contrast with the `Just` publisher, which always produces a single value,
/// this publisher might not send any values and instead finish normally,
/// if `output` is `nil`.
public struct Publisher: OpenCombine.Publisher {
/// The kind of value published by this publisher.
///
/// This publisher produces the type wrapped by the optional.
public typealias Output = Wrapped
/// The kind of error this publisher might publish.
///
/// The optional publisher never produces errors.
public typealias Failure = Never
/// The output to deliver to each subscriber.
public let output: Wrapped?
/// Creates a publisher to emit the value of the optional, or to finish
/// immediately if the optional doesn't have a value.
///
/// - Parameter output: The result to deliver to each subscriber.
public init(_ output: Output?) {
self.output = output
}
/// Implements the Publisher protocol by accepting the subscriber and
/// immediately publishing the optional’s value if it has one, or finishing
/// normally if it doesn’t.
///
/// - Parameter subscriber: The subscriber to add.
public func receive<Downstream: Subscriber>(subscriber: Downstream)
where Output == Downstream.Input, Failure == Downstream.Failure
{
if let output = output {
subscriber.receive(subscription: Inner(value: output,
downstream: subscriber))
} else {
subscriber.receive(subscription: Subscriptions.empty)
subscriber.receive(completion: .finished)
}
}
}
}
public var ocombine: OCombine {
return .init(self)
}
#if !canImport(Combine)
/// The type of a Combine publisher that publishes the value of a Swift optional
/// instance to each subscriber exactly once, if the instance has any value at
/// all.
///
/// In contrast with the `Just` publisher, which always produces a single value,
/// this publisher might not send any values and instead finish normally,
/// if `output` is `nil`.
public typealias Publisher = OCombine.Publisher
public var publisher: Publisher {
return Publisher(self)
}
#endif
}
extension Optional.OCombine {
private final class Inner<Downstream: Subscriber>
: Subscription,
CustomStringConvertible,
CustomReflectable,
CustomPlaygroundDisplayConvertible
where Downstream.Input == Wrapped
{
// NOTE: this class has been audited for thread safety.
// Combine doesn't use any locking here.
private var downstream: Downstream?
private let output: Wrapped
init(value: Wrapped, downstream: Downstream) {
self.output = value
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
demand.assertNonZero()
guard let downstream = self.downstream else { return }
self.downstream = nil
_ = downstream.receive(output)
downstream.receive(completion: .finished)
}
func cancel() {
downstream = nil
}
var description: String { return "Optional" }
var customMirror: Mirror {
return Mirror(self, unlabeledChildren: CollectionOfOne(output))
}
var playgroundDescription: Any { return description }
}
}
extension Optional.OCombine.Publisher: Equatable where Wrapped: Equatable {}
extension Optional.OCombine.Publisher where Wrapped: Equatable {
public func contains(_ output: Output) -> Optional<Bool>.OCombine.Publisher {
return .init(self.output.map { $0 == output })
}
public func removeDuplicates() -> Optional<Wrapped>.OCombine.Publisher {
return self
}
}
extension Optional.OCombine.Publisher where Wrapped: Comparable {
public func min() -> Optional<Wrapped>.OCombine.Publisher {
return self
}
public func max() -> Optional<Wrapped>.OCombine.Publisher {
return self
}
}
extension Optional.OCombine.Publisher {
public func allSatisfy(
_ predicate: (Output) -> Bool
) -> Optional<Bool>.OCombine.Publisher {
return .init(self.output.map(predicate))
}
public func collect() -> Optional<[Output]>.OCombine.Publisher {
return .init(self.output.map { [$0] } ?? [])
}
public func compactMap<ElementOfResult>(
_ transform: (Output) -> ElementOfResult?
) -> Optional<ElementOfResult>.OCombine.Publisher {
return .init(self.output.flatMap(transform))
}
public func min(
by areInIncreasingOrder: (Output, Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return self
}
public func max(
by areInIncreasingOrder: (Output, Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return self
}
public func contains(
where predicate: (Output) -> Bool
) -> Optional<Bool>.OCombine.Publisher {
return .init(self.output.map(predicate))
}
public func count() -> Optional<Int>.OCombine.Publisher {
return .init(self.output.map { _ in 1 })
}
public func dropFirst(_ count: Int = 1) -> Optional<Output>.OCombine.Publisher {
precondition(count >= 0, "count must not be negative")
return .init(self.output.flatMap { count == 0 ? $0 : nil })
}
public func drop(
while predicate: (Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return .init(self.output.flatMap { predicate($0) ? nil : $0 })
}
public func first() -> Optional<Output>.OCombine.Publisher {
return self
}
public func first(
where predicate: (Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return .init(output.flatMap { predicate($0) ? $0 : nil })
}
public func last() -> Optional<Output>.OCombine.Publisher {
return self
}
public func last(
where predicate: (Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return .init(output.flatMap { predicate($0) ? $0 : nil })
}
public func filter(
_ isIncluded: (Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return .init(output.flatMap { isIncluded($0) ? $0 : nil })
}
public func ignoreOutput() -> Empty<Output, Failure> {
return .init()
}
public func map<ElementOfResult>(
_ transform: (Output) -> ElementOfResult
) -> Optional<ElementOfResult>.OCombine.Publisher {
return .init(output.map(transform))
}
public func output(at index: Int) -> Optional<Output>.OCombine.Publisher {
precondition(index >= 0, "index must not be negative")
return .init(output.flatMap { index == 0 ? $0 : nil })
}
public func output<RangeExpression: Swift.RangeExpression>(
in range: RangeExpression
) -> Optional<Output>.OCombine.Publisher where RangeExpression.Bound == Int {
let range = range.relative(to: 0 ..< Int.max)
precondition(range.lowerBound >= 0, "lowerBound must not be negative")
// I don't know why, but Combine has this precondition
precondition(range.upperBound < .max - 1)
return .init(
output.flatMap { (range.lowerBound == 0 && range.upperBound != 0) ? $0 : nil }
)
}
public func prefix(_ maxLength: Int) -> Optional<Output>.OCombine.Publisher {
precondition(maxLength >= 0, "maxLength must not be negative")
return .init(output.flatMap { maxLength > 0 ? $0 : nil })
}
public func prefix(
while predicate: (Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return .init(output.flatMap { predicate($0) ? $0 : nil })
}
public func reduce<Accumulator>(
_ initialResult: Accumulator,
_ nextPartialResult: (Accumulator, Output) -> Accumulator
) -> Optional<Accumulator>.OCombine.Publisher {
return .init(output.map { nextPartialResult(initialResult, $0) })
}
public func scan<ElementOfResult>(
_ initialResult: ElementOfResult,
_ nextPartialResult: (ElementOfResult, Output) -> ElementOfResult
) -> Optional<ElementOfResult>.OCombine.Publisher {
return .init(output.map { nextPartialResult(initialResult, $0) })
}
public func removeDuplicates(
by predicate: (Output, Output) -> Bool
) -> Optional<Output>.OCombine.Publisher {
return self
}
public func replaceError(with output: Output) -> Optional<Output>.OCombine.Publisher {
return self
}
public func replaceEmpty(with output: Output) -> Just<Output> {
return .init(self.output ?? output)
}
public func retry(_ times: Int) -> Optional<Output>.OCombine.Publisher {
return self
}
}
| true
|
c2597522f77b53a40c80734a6b66b2d91703134a
|
Swift
|
irangareddy/Book-Club
|
/Shared/ReadingListViewer.swift
|
UTF-8
| 3,222
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// ReadingListViewer.swift
// Book Club
//
// Created by RANGA REDDY NUKALA on 25/06/20.
//
import SwiftUI
struct ReadingListViewer: View {
@StateObject var store: ReadingListStore
@SceneStorage("selectedItem") private var selectedItem: String?
var selectedID: Binding<UUID?> {
Binding<UUID?>(
get: { selectedItem.flatMap { UUID(uuidString: $0) } },
set: { selectedItem = $0?.uuidString }
)
}
var body: some View {
NavigationView {
List {
ForEach(store.books) { book in
BookCell(book: book,selectedId: selectedID)
}
}
.navigationBarTitle("Currently Reading")
Text("No Selection")
}
}
}
struct ReadingListViewer_Previews: PreviewProvider {
static var previews: some View {
ReadingListViewer(store: testStore)
}
}
struct BookCell: View {
var book: Book
var selectedId: Binding<UUID?>
var body: some View {
NavigationLink(destination: BookDetail(book: book),tag: book.id, selection: selectedId) {
HStack {
Image(book.imageName)
.resizable()
.frame(width: 54,height:100)
.padding(.horizontal,8)
VStack(alignment: .leading) {
Text(book.title)
.font(.body)
.fontWeight(.bold)
Text(book.author)
.font(.footnote)
.foregroundColor(.secondary).padding(.top, 2)
}
Spacer()
ProgressCircle(book: book)
}
}
}
}
struct ProgressCircle: View {
var book: Book
var body: some View {
ZStack {
Circle()
.trim(from: CGFloat(book.progress), to: 1)
.stroke(
LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)), Color(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1))]), startPoint: .topTrailing, endPoint: .bottomLeading),
style: StrokeStyle(lineWidth: 4, lineCap: .round)
)
.frame(width: 50, height: 50)
.rotationEffect(Angle(degrees: 90))
.rotation3DEffect(Angle(degrees: 180), axis: (x: 1, y: 0, z: 0))
.shadow(color: Color(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)).opacity(0.3), radius: 3, x: 0, y: 3)
.padding(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/, /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
Circle()
.stroke(Color.black.opacity(0.1), style: StrokeStyle(lineWidth: 5))
.frame(width: 50, height: 50)
Text("\(String(book.progress * 100))")
.font(.subheadline)
.fontWeight(.bold)
}
}
}
| true
|
e591d27211bf3dc8d881941efcf19f167eced7b7
|
Swift
|
bachino90/nquiz
|
/NQuiz/CountryManager.swift
|
UTF-8
| 817
| 3.078125
| 3
|
[] |
no_license
|
//
// CountryManager.swift
// NQuiz
//
// Created by Emiliano Bivachi on 15/4/16.
// Copyright © 2016 Emiliano Bivachi. All rights reserved.
//
import Foundation
let countryKey = "com.nquiz.country"
class CountryManager {
static let sharedManager = CountryManager()
var selectedCountry: Country? { return Country(rawValue: self.country ?? "") }
var country: String? {
didSet {
if let countryName = country {
saveCountry(countryName)
}
}
}
init() {
country = NSUserDefaults.standardUserDefaults().objectForKey(countryKey) as? String
}
func saveCountry(country: String) {
NSUserDefaults.standardUserDefaults().setObject(country, forKey: countryKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
| true
|
893c64e579cad184f506492eccd3808b42b81349
|
Swift
|
nateansel/flix
|
/Flix/Managers/MovieManager.swift
|
UTF-8
| 3,978
| 2.96875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// MovieManager.swift
// Flix
//
// Created by Nathan Ansel on 7/30/18.
// Copyright © 2018 Nathan Ansel. All rights reserved.
//
import Foundation
struct MovieListResults: Codable {
struct Dates: Codable {
var maximum: Date
var minimum: Date
}
var page: Int
var results: [Movie]
var dates: Dates?
var totalPages: Int
var totalResults: Int
}
class MovieManager {
private enum Locations {
static let base = "https://api.themoviedb.org/3"
static let nowPlaying = base + "/movie/now_playing"
static let topRated = base + "/movie/top_rated"
static func details(forMovieWithID id: String) -> String { return base + "/movie/\(id)" }
}
private enum Security {
static let apiKeyName = "api_key"
static let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
}
static let shared = MovieManager()
typealias NowPlayingListSucces = (MovieListResults) -> Void
typealias NowPlayingListFailure = (Error) -> Void
func nowPlayingList(page: Int? = nil, success: @escaping NowPlayingListSucces, failure: @escaping NowPlayingListFailure) {
// Uncomment the following code to simulate a network failure
// DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
// failure(NSError(domain: "", code: -1, userInfo: nil))
// })
// return
var components = URLComponents(string: Locations.nowPlaying)
components?.queryItems = [
URLQueryItem(name: Security.apiKeyName, value: Security.apiKey)
]
if let page = page {
components?.queryItems?.append(URLQueryItem(name: "page", value: "\(page)"))
}
guard let url = components?.url else {
fatalError("Invalid Now Playing list url: \(Locations.nowPlaying)")
}
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: .main)
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
// Inform the UI about any errors
failure(error!)
return
}
guard let data = data, !data.isEmpty else {
// TODO: Inform the UI about incorrect data
return
}
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let results = try decoder.decode(MovieListResults.self, from: data)
success(results)
} catch {
print(error)
failure(error)
}
}
task.resume()
}
typealias TopRatedSuccess = (MovieListResults) -> Void
typealias TopRatedFailure = NowPlayingListFailure
func topRatedList(page: Int? = nil, success: @escaping TopRatedSuccess, failure: @escaping TopRatedFailure) {
var components = URLComponents(string: Locations.topRated)
components?.queryItems = [
URLQueryItem(name: Security.apiKeyName, value: Security.apiKey)
]
if let page = page {
components?.queryItems?.append(URLQueryItem(name: "page", value: "\(page)"))
}
guard let url = components?.url else {
fatalError("Invalid Now Playing list url: \(Locations.topRated)")
}
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: .main)
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
// Inform the UI about any errors
failure(error!)
return
}
guard let data = data, !data.isEmpty else {
// TODO: Inform the UI about incorrect data
return
}
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let results = try decoder.decode(MovieListResults.self, from: data)
success(results)
} catch {
print(error)
failure(error)
}
}
task.resume()
}
}
| true
|
d5117cf8276967f2e48435647e4b10d3fe3aa36f
|
Swift
|
LaurenWeiss/MakeSchoolTutorialOfMakestagram
|
/Makestagram/Makestagram/Makestagram/StorageReference+Post.swift
|
UTF-8
| 735
| 2.5625
| 3
|
[] |
no_license
|
//
// StorageReference+Post.swift
// Makestagram
//
// Created by Lauren Weiss on 6/29/17.
// Copyright © 2017 Lauren Weiss. All rights reserved.
//
import Foundation
import FirebaseStorage
extension StorageReference {
static let dateFormatter = ISO8601DateFormatter()
static func newPostImageReference() -> StorageReference {
//creates an extension to StorageReference with a class method
//that will generate a new location for each new post image that
//is created by the current ISO timestamp
let uid = User.current.uid
let timestamp = dateFormatter.string(from: Date())
return Storage.storage().reference().child("image/posts/\(uid)/\(timestamp).jpg")
}
}
| true
|
c04fcafca9a653cfbf8db61e1e013565f087680e
|
Swift
|
josefdolezal/redmine-toggl-importer
|
/Sources/ImporterKit/Networking/Plugins/TogglAuthPlugin.swift
|
UTF-8
| 744
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// TogglAuthPlugin.swift
// Importr
//
// Created by Josef Dolezal on 10/08/2017.
//
//
import Foundation
import Moya
public final class TogglAuthPlugin: PluginType {
private let token: String
private struct HeaderKeys {
static let authorization = "Authorization"
static func basicAuthorization(_ token: String) -> String {
return "Basic \(token)"
}
}
public init(token: String) {
self.token = token
}
public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
var mutableRequst = request
mutableRequst.addValue(HeaderKeys.basicAuthorization(token), forHTTPHeaderField: HeaderKeys.authorization)
return mutableRequst
}
}
| true
|
77d065e14591813dafde117329fc6f6e2e70208d
|
Swift
|
yaoliangjun/Trade
|
/SwiftTrade/Classes/Common/View/ImageButton.swift
|
UTF-8
| 1,793
| 3.046875
| 3
|
[] |
no_license
|
//
// ImageButton.swift
// SwiftTrade
//
// Created by yaoliangjun on 2017/12/5.
// Copyright © 2017年 Jerry Yao. All rights reserved.
// 图片按钮
import UIKit
class ImageButton: UIButton {
var textAlignment: NSTextAlignment?
convenience init(title: String, titleColor: UIColor, textAlignment: NSTextAlignment?, font: UIFont, image: UIImage?, target: Any?, selector: Selector?) {
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
self.titleLabel?.font = font
self.setImage(image, for: .normal)
self.textAlignment = textAlignment
if let target = target, let selector = selector {
self.addTarget(target, action: selector, for: .touchUpInside)
}
}
override func layoutSubviews() {
super.layoutSubviews()
if textAlignment == NSTextAlignment.right {
// 修改图片的Frame
var imageFrame = self.imageView?.frame
let imageWidth = self.imageView?.frame.size.width
imageFrame?.origin.x = self.frame.size.width - imageWidth!
self.imageView?.frame = imageFrame!
// 修改Title的Frame
var titleFrame = self.titleLabel?.frame
titleFrame!.origin.x = (self.imageView?.frame.origin.x)! - (titleFrame?.size.width)! - 3
titleFrame!.size = (self.titleLabel?.frame.size)!
self.titleLabel?.frame = titleFrame!
} else {
// 修改图片的Frame
var imageFrame = self.imageView?.frame
let titleFrame = self.titleLabel?.frame
imageFrame?.origin.x = (titleFrame?.origin.x)! + (titleFrame?.size.width)! + 3
self.imageView?.frame = imageFrame!
}
}
}
| true
|
79de304af46dc647fa3772c32221a9f1b96f3301
|
Swift
|
dasdom/Phy
|
/Classes/Imprint/ImprintView.swift
|
UTF-8
| 2,751
| 2.59375
| 3
|
[] |
no_license
|
// Created by dasdom on 23.07.19.
// Copyright © 2019 dasdom. All rights reserved.
//
import UIKit
import SpriteKit
class ImprintView: UIView, UITextViewDelegate {
let caveScene: CaveScene
let gameView: SKView
let textView: UITextView
private var alreadyStarted = false
override init(frame: CGRect) {
let gameFrame = CGRect(x: 0, y: 0, width: 750, height: 400)
caveScene = CaveScene(size: gameFrame.size)
caveScene.scaleMode = .aspectFill
caveScene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
gameView = SKView(frame: gameFrame)
gameView.ignoresSiblingOrder = true
// gameView.showsFPS = true
// gameView.showsNodeCount = true
textView = UITextView()
textView.isEditable = false
textView.isSelectable = false
textView.decelerationRate = .fast
super.init(frame: frame)
backgroundColor = .white
textView.delegate = self
caveScene.imprintView = self
gameView.presentScene(startScene)
let stackView = UIStackView(arrangedSubviews: [gameView, textView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .fill
addSubview(stackView)
let gameViewHeightConstraint = gameView.heightAnchor.constraint(equalToConstant: 200)
gameViewHeightConstraint.priority = UILayoutPriority(999)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
stackView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
gameViewHeightConstraint,
stackView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate lazy var startScene: StartScene = {
let size = CGSize(width: 375, height: 200)
let startScene = StartScene(size: size)
startScene.backgroundColor = .black
startScene.textColor = .white
return startScene
}()
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let percentage = scrollView.contentOffset.y / (scrollView.contentSize.height - scrollView.frame.size.height);
if false == alreadyStarted {
alreadyStarted = true
gameView.presentScene(caveScene, transition: .doorsOpenHorizontal(withDuration: 0.5))
caveScene.scrollSpeed = 1
} else {
caveScene.updatePosition(for: percentage)
}
}
func didFinish() {
startScene.title = "Game Over"
startScene.subTitle = "Have fun with the imprint!"
gameView.presentScene(startScene, transition: .doorsCloseHorizontal(withDuration: 0.5))
}
}
| true
|
e798ce544faf102fa564d3203133fb30cea6e663
|
Swift
|
jeannieyeliu/UTS_ledger_ios_app
|
/MoMo/MoMo/Model/Record.swift
|
UTF-8
| 709
| 3.21875
| 3
|
[] |
no_license
|
//
// RecordInDay.swift
// MoMo
//
// Created by BonnieLee on 17/5/19.
// Copyright © 2019 Clima. All rights reserved.
//
import Foundation
// This class is to store the record data
class Record {
var id = String()
var amount: Double = 0.0
var note: String = String()
var category = String() // maybe this should be Category instance
init(id: String, amount: Double, category: String, note: String){
self.id = id
self.amount = amount
self.note = note
self.category = category
}
}
// This class is to store the record sum data
class RecordSum {
var amount = Double()
init (amount: Double) {
self.amount = amount
}
}
| true
|
02c4db59e7699eb30355611996c18520b2beff63
|
Swift
|
kingds/agricola
|
/Agricola/ViewController.swift
|
UTF-8
| 17,077
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Agricola
//
// Created by Daniel King on 12/14/14.
// Copyright (c) 2014 Daniel King. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Points labels on the right side of the view
@IBOutlet var grainPointsLabel : UILabel!
@IBOutlet var vegetablesPointsLabel : UILabel!
@IBOutlet var sheepPointsLabel : UILabel!
@IBOutlet var boarPointsLabel : UILabel!
@IBOutlet var cattlePointsLabel : UILabel!
@IBOutlet var fieldsPointsLabel : UILabel!
@IBOutlet var pasturesPointsLabel : UILabel!
@IBOutlet var unusedSpacesPointsLabel : UILabel!
@IBOutlet var fencedStablesPointsLabel : UILabel!
@IBOutlet var roomsPointsLabel : UILabel!
@IBOutlet var familyMembersPointsLabel : UILabel!
@IBOutlet var improvementPointsLabel : UILabel!
@IBOutlet var bonusPointsLabel : UILabel!
@IBOutlet var beggingCardsLabel : UILabel!
// Input fields in the center of the view
@IBOutlet var grainInputField : UITextField!
@IBOutlet var vegetablesInputField : UITextField!
@IBOutlet var sheepInputField : UITextField!
@IBOutlet var boarInputField : UITextField!
@IBOutlet var cattleInputField : UITextField!
@IBOutlet var fieldsInputField : UITextField!
@IBOutlet var pasturesInputField : UITextField!
@IBOutlet var unusedSpacesInputField : UITextField!
@IBOutlet var fencedStablesInputField : UITextField!
@IBOutlet var roomsInputField : UITextField!
@IBOutlet var familyMembersInputField : UITextField!
@IBOutlet var improvementPointsInputField : UITextField!
@IBOutlet var bonusPointsInputField : UITextField!
@IBOutlet var beggingCardsInputField : UITextField!
// Room type selector
@IBOutlet var roomTypeSelector : UISegmentedControl!
// Scroll View
@IBOutlet var scrollView: UIScrollView!
// Content View
@IBOutlet var contentView: UIView!
// Create the calculator class
let calc = Calculator()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.3176, green: 0.6902, blue: 0.5176, alpha: 1)
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
// Setup the keyboard for data entry
keyboardSetup()
// Set up the scroll view
scrollViewSetup()
}
func showGrainKeyboard() {
grainInputField.becomeFirstResponder()
}
func showVegetablesKeyboard() {
vegetablesInputField.becomeFirstResponder()
}
func showSheepKeyboard() {
sheepInputField.becomeFirstResponder()
}
func showBoarKeyboard() {
boarInputField.becomeFirstResponder()
}
func showCattleKeyboard() {
cattleInputField.becomeFirstResponder()
}
func showFieldsKeyboard() {
fieldsInputField.becomeFirstResponder()
}
func showPasturesKeyboard() {
pasturesInputField.becomeFirstResponder()
}
func showUnusedSpacesKeyboard() {
unusedSpacesInputField.becomeFirstResponder()
}
func showFencedStablesKeyboard() {
fencedStablesInputField.becomeFirstResponder()
}
func showRoomsKeyboard() {
roomsInputField.becomeFirstResponder()
}
func showFamilyMembersKeyboard() {
familyMembersInputField.becomeFirstResponder()
}
func showImprovementPointsKeyboard() {
improvementPointsInputField.becomeFirstResponder()
}
func showBonusPointsKeyboard() {
bonusPointsInputField.becomeFirstResponder()
}
func showBeggingCardsKeyboard() {
beggingCardsInputField.becomeFirstResponder()
}
func keyboardToolbar(nextAction: String, previousAction: String) -> UIToolbar {
var toolbar: UIToolbar = UIToolbar(frame:CGRectMake(0, 524, 320, 44))
var previousButton = UIBarButtonItem(title: "Previous", style: UIBarButtonItemStyle.Plain, target: self, action: Selector(previousAction))
if previousAction == "None" {
previousButton.enabled = false
}
var nextButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Plain, target: self, action: Selector(nextAction))
if nextAction == "None" {
nextButton.enabled = false
}
let fillerSpace = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
toolbar.setItems([previousButton, fillerSpace, nextButton], animated: false)
return toolbar
}
func moveToInputField(field: UITextField) {
field.becomeFirstResponder()
}
func keyboardSetup() {
grainInputField.inputAccessoryView = keyboardToolbar("showVegetablesKeyboard", previousAction: "None")
vegetablesInputField.inputAccessoryView = keyboardToolbar("showSheepKeyboard", previousAction:"showGrainKeyboard")
sheepInputField.inputAccessoryView = keyboardToolbar("showBoarKeyboard", previousAction: "showVegetablesKeyboard")
boarInputField.inputAccessoryView = keyboardToolbar("showCattleKeyboard", previousAction: "showSheepKeyboard")
cattleInputField.inputAccessoryView = keyboardToolbar("showFieldsKeyboard", previousAction: "showBoarKeyboard")
fieldsInputField.inputAccessoryView = keyboardToolbar("showPasturesKeyboard", previousAction: "showCattleKeyboard")
pasturesInputField.inputAccessoryView = keyboardToolbar("showUnusedSpacesKeyboard", previousAction: "showFieldsKeyboard")
unusedSpacesInputField.inputAccessoryView = keyboardToolbar("showFencedStablesKeyboard", previousAction: "showPasturesKeyboard")
fencedStablesInputField.inputAccessoryView = keyboardToolbar("showRoomsKeyboard", previousAction: "showUnusedSpacesKeyboard")
roomsInputField.inputAccessoryView = keyboardToolbar("showFamilyMembersKeyboard", previousAction: "showFencedStablesKeyboard")
familyMembersInputField.inputAccessoryView = keyboardToolbar("showImprovementPointsKeyboard", previousAction: "showRoomsKeyboard")
improvementPointsInputField.inputAccessoryView = keyboardToolbar("showBonusPointsKeyboard", previousAction: "showFamilyMembersKeyboard")
bonusPointsInputField.inputAccessoryView = keyboardToolbar("showBeggingCardsKeyboard", previousAction: "showImprovementPointsKeyboard")
beggingCardsInputField.inputAccessoryView = keyboardToolbar("None", previousAction: "showBonusPointsKeyboard")
}
func scrollViewSetup() {
scrollView.scrollEnabled = false
scrollView.contentSize = CGSizeMake(320, 1000)
// scrollView.addSubview(contentView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}
override func shouldAutorotate() -> Bool{
return false
}
@IBAction func viewTapped(sender : AnyObject) {
grainInputField.resignFirstResponder()
vegetablesInputField.resignFirstResponder()
sheepInputField.resignFirstResponder()
boarInputField.resignFirstResponder()
cattleInputField.resignFirstResponder()
fieldsInputField.resignFirstResponder()
pasturesInputField.resignFirstResponder()
unusedSpacesInputField.resignFirstResponder()
fencedStablesInputField.resignFirstResponder()
roomsInputField.resignFirstResponder()
familyMembersInputField.resignFirstResponder()
improvementPointsInputField.resignFirstResponder()
bonusPointsInputField.resignFirstResponder()
beggingCardsInputField.resignFirstResponder()
scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
}
func calculateTotal() {
let score = calc.calculateTotal()
self.title = "Total: " + String(score)
}
func getPointsString(score: Int) -> String {
var pointsString: String
if score == -1 || score == 1 {
pointsString = " Point"
} else {
pointsString = " Points"
}
return pointsString
}
@IBAction func inputFieldSelected(sender: UITextField) {
let originPoint = sender.frame.origin
if originPoint.y > 210 {
scrollView.setContentOffset(CGPointMake(0, originPoint.y - 210), animated: true)
} else {
scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
}
}
@IBAction func reset(sender: AnyObject) {
calc.grain = 0
calc.vegetables = 0
calc.sheep = 0
calc.boar = 0
calc.cattle = 0
calc.fields = 0
calc.unusedSpaces = 0
calc.pastures = 0
calc.fencedStables = 0
calc.rooms = 2
calc.roomType = "Wood"
calc.familyMembers = 2
calc.improvementPoints = 0
calc.bonusPoints = 0
calc.beggingCards = 0
grainInputField.text = nil
vegetablesInputField.text = nil
sheepInputField.text = nil
boarInputField.text = nil
cattleInputField.text = nil
fieldsInputField.text = nil
pasturesInputField.text = nil
unusedSpacesInputField.text = nil
fencedStablesInputField.text = nil
roomsInputField.text = nil
familyMembersInputField.text = nil
improvementPointsInputField.text = nil
bonusPointsInputField.text = nil
// beggingCardsInputField.text = nil
roomTypeSelector.selectedSegmentIndex = 0
grainChanged(self)
vegetablesChanged(self)
sheepChanged(self)
boarChanged(self)
cattleChanged(self)
fieldsChanged(self)
pasturesChanged(self)
unusedSpacesChanged(self)
fencedStablesChanged(self)
roomsChanged(self)
familyMembersChanged(self)
improvementPointsChanged(self)
bonusPointsChanged(self)
// beggingCardsChanged(self)
calculateTotal()
self.title = "Agricola Calculator"
}
@IBAction func grainChanged(sender : AnyObject) {
var grain: Int? = grainInputField.text.toInt()
if grain == nil {
grain = 0
}
calc.grain = grain!
let score = calc.grainScore(grain!)
let pointsString = getPointsString(score)
grainPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func vegetablesChanged(sender : AnyObject) {
var vegetables : Int? = vegetablesInputField.text.toInt()
if vegetables == nil {
vegetables = 0
}
calc.vegetables = vegetables!
let score = calc.vegetableScore(calc.vegetables)
let pointsString = getPointsString(score)
vegetablesPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func sheepChanged(sender : AnyObject) {
var sheep : Int? = sheepInputField.text.toInt()
if sheep == nil {
sheep = 0
}
calc.sheep = sheep!
let score = calc.sheepScore(calc.sheep)
let pointsString = getPointsString(score)
sheepPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func boarChanged(sender : AnyObject) {
var boar : Int? = boarInputField.text.toInt()
if boar == nil {
boar = 0
}
calc.boar = boar!
let score = calc.boarScore(calc.boar)
let pointsString = getPointsString(score)
boarPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func cattleChanged(sender : AnyObject) {
var cattle : Int? = cattleInputField.text.toInt()
if cattle == nil {
cattle = 0
}
calc.cattle = cattle!
let score = calc.cattleScore(calc.cattle)
let pointsString = getPointsString(score)
cattlePointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func fieldsChanged(sender : AnyObject) {
var fields : Int? = fieldsInputField.text.toInt()
if fields == nil {
fields = 0
}
calc.fields = fields!
let score = calc.fieldsScore(calc.fields)
let pointsString = getPointsString(score)
fieldsPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func pasturesChanged(sender : AnyObject) {
var pastures : Int? = pasturesInputField.text.toInt()
if pastures == nil {
pastures = 0
}
calc.pastures = pastures!
let score = calc.pasturesScore(calc.pastures)
let pointsString = getPointsString(score)
pasturesPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func unusedSpacesChanged(sender : AnyObject) {
var unusedSpaces : Int? = unusedSpacesInputField.text.toInt()
if unusedSpaces == nil {
unusedSpaces = 0
}
calc.unusedSpaces = unusedSpaces!
let score = calc.unusedSpaces * -1
let pointsString = getPointsString(score)
unusedSpacesPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func fencedStablesChanged(sender : AnyObject) {
var fencedStables : Int? = fencedStablesInputField.text.toInt()
if fencedStables == nil {
fencedStables = 0
}
calc.fencedStables = fencedStables!
let score = calc.fencedStables
let pointsString = getPointsString(score)
fencedStablesPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func familyMembersChanged(sender : AnyObject) {
var familyMembers : Int? = familyMembersInputField.text.toInt()
if familyMembers == nil {
familyMembers = 0
}
calc.familyMembers = familyMembers!
let score = calc.familyMembers * 3
let pointsString = getPointsString(score)
familyMembersPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func roomTypeChanged(sender : AnyObject) {
var roomTypeIndex: Int? = roomTypeSelector.selectedSegmentIndex
var roomType = "Wood"
if roomTypeIndex == nil {
roomTypeIndex = 0
}
if roomTypeIndex == 0 {
roomType = "Wood"
} else if roomTypeIndex == 1 {
roomType = "Clay"
} else if roomTypeIndex == 2 {
roomType = "Stone"
}
calc.roomType = roomType
let score = calc.roomsScore(calc.rooms, roomType: calc.roomType)
let pointsString = getPointsString(score)
roomsPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func roomsChanged(sender : AnyObject) {
var rooms : Int? = roomsInputField.text.toInt()
if rooms == nil {
rooms = 0
}
calc.rooms = rooms!
let score = calc.roomsScore(calc.rooms, roomType: calc.roomType)
let pointsString = getPointsString(score)
roomsPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func improvementPointsChanged(sender : AnyObject) {
var improvementPoints : Int? = improvementPointsInputField.text.toInt()
if improvementPoints == nil {
improvementPoints = 0
}
calc.improvementPoints = improvementPoints!
let score = calc.improvementPoints
let pointsString = getPointsString(score)
improvementPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func bonusPointsChanged(sender : AnyObject) {
var bonusPoints : Int? = bonusPointsInputField.text.toInt()
if bonusPoints == nil {
bonusPoints = 0
}
calc.bonusPoints = bonusPoints!
let score = calc.bonusPoints
let pointsString = getPointsString(score)
bonusPointsLabel.text = String(score) + pointsString
calculateTotal()
}
@IBAction func beggingCardsChanged(sender : AnyObject) {
var beggingCards : Int? = beggingCardsInputField.text.toInt()
if beggingCards == nil {
beggingCards = 0
}
calc.beggingCards = beggingCards!
let score = calc.beggingCardsScore(calc.beggingCards)
let pointsString = getPointsString(score)
beggingCardsLabel.text = String(score) + pointsString
calculateTotal()
}
}
| true
|
fa27dcce46b224add285f989d50ba8ea507f9069
|
Swift
|
ikoronka/AzureCupMonumentClassifier
|
/Pamatkovac verze 3/View/chatbot/MessageView.swift
|
UTF-8
| 3,226
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// MessageView.swift
// Pamatkovac verze 3
//
// Created by vojta on 11.05.2021.
//
import SwiftUI
struct MessageView: View {
@ObservedObject var vm: ChatBotModel
@EnvironmentObject var am: MicrophoneMonitor
var message: Message
var scroll: ScrollViewProxy
var body: some View {
HStack{
if message.who == .user{
Spacer()
}else{
VStack {
if message.image != nil {
Spacer()
}
Image("Robot")
.resizable()
.scaledToFill()
.frame(width: 50, height: 50, alignment: .center)
.background(Color.ghostWhite)
.clipShape(Circle())
}
}
if let image = message.image {
image
.resizable()
.scaledToFill()
.clipShape(RoundedRectangle(cornerRadius: 25.0))
.frame(maxWidth: UIScreen.main.bounds.width / 2)
.onTapGesture {
withAnimation{
vm.selectedImage = image
}
}
}
if let url = message.url {
Link(destination: url) {
Text("Here!")
}
}
if let mess = message.message {
Text(mess)
.foregroundColor(.primary)
.padding()
.background(GradientView(who: message.who))
.clipShape(RoundedRectangle(cornerRadius: 25.0))
.padding(.trailing,(message.who == .bot) ? 60:0)
.padding(.leading ,(message.who == .user) ? 60:0)
.id(message.id)
.onAppear(perform: {
if vm.messages.count > 1{
scroll.scrollTo(vm.messages[vm.messages.count - 1].id)
}
})
.onTapGesture{
vm.speak(messafe: message.message!)
}
}
if message.who == .bot {
Spacer()
} else {
VStack {
if message.image != nil {
Spacer()
}
Image("user")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50, alignment: .center)
.background(GradientView(who: .user))
.clipShape(Circle())
}
}
}.padding([.top,.bottom], (message.image != nil) ? 10 : 0)
}
}
struct MessageView_Previews: PreviewProvider {
static var previews: some View {
Chatbot(am: MicrophoneMonitor(numberOfSamples: 3))
.previewDevice("iPhone 12 Pro Max")
.environmentObject(ChatBotModel())
}
}
| true
|
81f0d2014c83af4b0833b37417ef094bd730be9f
|
Swift
|
xylxi/Kingfisher
|
/Demo/Kingfisher-Demo/AppDelegate.swift
|
UTF-8
| 5,802
| 2.71875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// AppDelegate.swift
// Kingfisher-Demo
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <onevcat@gmail.com>
//
// 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 Kingfisher
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let queueA: dispatch_queue_t = dispatch_queue_create("com.xylxi.Kingfisher.test", DISPATCH_QUEUE_SERIAL)
let queueB: dispatch_queue_t = dispatch_queue_create("com.xylxi.Kingfisher.test", DISPATCH_QUEUE_CONCURRENT)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.test_dispatch_barrier_async()
return true
}
/**
GCD的学习记录
关于同步和异步新理解 2016-04-29
dispatch_sync和dispatch_async本身就是一个函数
当执行到dispatch_sync函数的时候,只用处理完dispatch_sync函数中的block,dispatch_sync函数才能return返回,,才能继续往下
dispatch_async则不需要处理完dispatch_async函数中的block,就能return
*/
/**
* 首先main 队列执行test1任务
* 打印了 current thread 1
* 碰到了dispatch_sync(dispatch_get_global_queue(0, 0), ^{block});
* block加入了global队列,因为是同步任务,所以需要等到block执行完,才能返回,所以进程将在主线程挂起直到该 Block 完成
* global队列按照FIFO,调度队列中的任务
* 当调度了block,打印了current thread 3,block完成后,返回
* 返回后,继续主队的任务
* 打印current thread 2
*/
func test1() {
print("current thread 1 = \(NSThread.currentThread())")
dispatch_sync(dispatch_get_global_queue(0, 0)) { () -> Void in
print("current thread 3 = \(NSThread.currentThread())")
}
print("current thread 2 = \(NSThread.currentThread())")
}
/**
* 首先main 队列执行test2任务
* 打印了 current thread 1
* 碰到了dispatch_async(dispatch_get_global_queue(0, 0), ^{block});
* dispathch_async中的block加入global队列中,立即返回
* 继续test2中的任务,打印current thread 2
* 记住 Block 在全局队列中将按照 FIFO 顺序出列,但可以并发执行。
* 添加到 dispatch_async 的代码块开始执行。
*
* 打印current thread 2和current thread 3,不一定谁在前,谁在后
*/
func test2() {
print("current thread 1 = \(NSThread.currentThread())")
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
print("current thread 3 = \(NSThread.currentThread())")
}
print("current thread 2 = \(NSThread.currentThread())")
}
/**
* group中notify和wait的区别
*/
func test3() {
let queue = dispatch_get_global_queue(0, 0)
let group = dispatch_group_create()
print("begin group")
for i in 0..<10 {
dispatch_group_async(group, queue, { () -> Void in
print("do \(i) at group")
})
}
// 等group中的block都执行完后,调用这个,不阻塞当前线程
dispatch_group_notify(group, queue) { () -> Void in
print("all done at group")
}
//当前线程卡到这里,知道group中的block执行完,才往下走
// dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
print("after group")
}
/**
* dispatch_barrier_async处理多线程修改一个数据的问题
* dispatch_barrier_xxxx 函数,在将block派送到指定的queue中
* dispatch_barrier_xxxx中的block,等待前面的任务完成后,才能派送
* 在执行dispatch_barrier_xxxx中的block期间,queue不能在派送新的任务
*/
func test_dispatch_barrier_async() {
dispatch_async(queueB) { () -> Void in
// print(2)
}
dispatch_async(queueB) { () -> Void in
// print(3)
}
dispatch_async(queueB) { () -> Void in
// print(4)
}
dispatch_barrier_async(queueB) { () -> Void in
for _ in 0..<100 {
// print("<<<\(i)")
}
}
dispatch_async(queueB) { () -> Void in
// print(5)
}
dispatch_async(queueB) { () -> Void in
// print(6)
}
dispatch_async(queueB) { () -> Void in
// print(7)
}
}
}
| true
|
104a0eddb4057b1709ecaba64e15062ee59cc78c
|
Swift
|
kkk669/LibWebTranspiler
|
/Tests/LibWebTranspilerTests/LibWebTranspilerTests.swift
|
UTF-8
| 2,382
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
@testable import LibWebTranspiler
final class LibWebTranspilerTests: XCTestCase {
func testBabel() {
XCTAssertNoThrow(try Babel.instance.compile(code: """
class Shape {
constructor (id, x, y) {
this.id = id
this.move(x, y)
}
move (x, y) {
this.x = x
this.y = y
}
}
"""))
}
func testCoffeeScript() {
XCTAssertNoThrow(try CoffeeScriptCompiler.instance.compile(code: """
# Assignment:
number = 42
opposite = true
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -> x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
# Splats:
race = (winner, runners...) ->
print winner, runners
# Existence:
alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
"""))
}
func testSass() {
XCTAssertNoThrow(try SassCompiler.instance.compile(code: """
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
"""))
}
func testTypeScript() {
XCTAssertNoThrow(TypeScriptCompiler.instance.compile(code: """
class Greeter<T> {
greeting: T;
constructor(message: T) {
this.greeting = message;
}
greet() {
return this.greeting;
}
}
let greeter = new Greeter<string>("Hello, world");
let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
alert(greeter.greet());
}
document.body.appendChild(button);
"""))
}
static var allTests = [
("testBabel", testBabel),
("testCoffeeScript", testCoffeeScript),
("testSass", testSass),
("testTypeScript", testTypeScript),
]
}
| true
|
31aba81ceeeee2da9ca48533778936f71acf6523
|
Swift
|
joshuajhomann/Reversi-SwiftUI-Animation
|
/animations SwiftUI.playground/Pages/Explicit.xcplaygroundpage/Contents.swift
|
UTF-8
| 708
| 2.765625
| 3
|
[] |
no_license
|
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
@State private var isblurred = true
@State private var isSaturated = true
var body: some View {
VStack {
Image(uiImage:UIImage(named: "2.jpg")!)
.resizable()
.scaledToFit()
.blur(radius: isblurred ? 16 : 0)
.saturation(isSaturated ? 6 : 1)
Button ("animate") {
withAnimation(.linear(duration: 2)) {
isblurred.toggle()
}
withAnimation(Animation.linear(duration: 2)) {
isSaturated.toggle()
}
}
}
}
}
let hostingController = UIHostingController(rootView: ContentView())
PlaygroundPage.current.setLiveView(hostingController)
| true
|
344a379e6538961e0dc6580a3243fe3c8a190a3d
|
Swift
|
taquitos/SwiftRubyRPC
|
/swift/SwiftRubyRPC/SwiftRubyRPC/RubyCommand.swift
|
UTF-8
| 1,724
| 3.109375
| 3
|
[] |
no_license
|
//
// RubyCommand.swift
// SwiftRubyRPC
//
// Created by Joshua Liebowitz on 8/4/17.
// Copyright © 2017 Joshua Liebowitz. All rights reserved.
//
import Foundation
protocol RubyCommandable {
var json: String { get }
}
struct RubyCommand: RubyCommandable {
struct Argument {
let name: String
let value: Any?
var hasValue: Bool {
return nil != self.value
}
var json: String {
get {
if let someValue = value {
return "{\"name\" : \"\(name)\", \"value\" : \"\(someValue)\"}"
} else {
// Just exclude this arg if it doesn't have a value
return ""
}
}
}
}
let commandID: String
let methodName: String
let className: String?
let args: [Argument]
var json: String {
let argsArrayJson = self.args
.map { $0.json }
.filter { $0 != "" }
let argsJson: String?
if argsArrayJson.count > 0 {
argsJson = "\"args\" : [\(argsArrayJson.joined(separator: ","))]"
} else {
argsJson = nil
}
let commandIDJson = "\"commandID\" : \"\(commandID)\""
let methodNameJson = "\"methodName\" : \"\(methodName)\""
var jsonParts = [commandIDJson, methodNameJson]
if let argsJson = argsJson {
jsonParts.append(argsJson)
}
if let className = className {
let classNameJson = "\"className\" : \"\(className)\""
jsonParts.append(classNameJson)
}
let commandJsonString = "{\(jsonParts.joined(separator: ","))}"
return commandJsonString
}
}
| true
|
bfdc6a64580c78518d9dc80b8fa2a8cff058bca3
|
Swift
|
carabina/Raindrops
|
/RaindropsDemo/RaindropsDemo/Controllers/ForthVC.swift
|
UTF-8
| 2,269
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// ForthVC.swift
// RaindropsDemo
//
// Created by bach on 2017/1/10.
// Copyright © 2017年 bach. All rights reserved.
//
import UIKit
class ForthView: UIView {
var customTabBar: RdCustomTabBar!
override init(frame: CGRect) {
super.init(frame: frame)
loadUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func loadUI() {
self.backgroundColor = UIColor(red: 0.00, green: 0.80, blue: 0.00, alpha: 1.00)
customTabBar = RdCustomTabBar()
customTabBar.backgroundColor = UIColor(red: 0.29, green: 0.71, blue: 0.93, alpha: 1.00)
customTabBar.selectedIndex = 3
self.addSubview(customTabBar)
}
override func layoutSubviews() {
super.layoutSubviews()
let bounds = self.bounds
let tabBarFrame = CGRect(x: 0, y: bounds.size.height - 49, width: bounds.size.width, height: 49)
customTabBar.frame = tabBarFrame
}
}
class ForthVC: UIViewController, TabBarDataSource, TabBarDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadUI()
}
private func loadUI() {
let forthView = ForthView(frame: self.view.frame)
forthView.customTabBar.notificationsName = NotificationNames
forthView.customTabBar.datasource = self
forthView.customTabBar.delegate = self
self.view = forthView
}
func tabBar(_ tabBar: RdCustomTabBar, cellForItemAt index: Int) -> RdCustomBarItem {
let item = RdCustomBarItem(style: CustomBarItemStyle.Default)
item.titleLabel.text = TabBarModuleNames[index]
item.titleLabel.textColor = UIColor.black
item.imageView.image = UIImage(named: "index_\(index)_normal")
item.imageView.highlightedImage = UIImage(named: "index_\(index)_selected")
return item
}
func tabBarInsetsOfTop(_ tabBar: RdCustomTabBar, cellForItemAt index: Int) -> CGFloat {
return 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.