blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
625
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | repo_name
stringlengths 5
116
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 643
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 80.4k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 16
values | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_language
stringclasses 85
values | src_encoding
stringclasses 7
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 4
6.44M
| extension
stringclasses 17
values | content
stringlengths 4
6.44M
| duplicates
listlengths 1
9.02k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
52d6c64282607f32a1d9385fb1d72d534cea7a11 | 4be63857793563f7f5ca48b64a645febbc15bb79 | /Source/iOS/nSoft/Controllers/Consolidated/ConsolidateNoticeTableViewCell.swift | 39030db72a76a815279e5208bd2a61633e32ea3f | [] | no_license | istar07/Total_sources-web-mobile-desktop- | f44ff4a121e82d3e6f54020523b1790e3e84e8e8 | 9dbb50dea4f11e71a14564f4540d17840538382e | refs/heads/master | 2023-04-26T07:51:16.791555 | 2021-05-19T20:57:30 | 2021-05-19T20:57:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,251 | swift | //
// ConsolidateNoticeTableViewCell.swift
// nSoft
//
// Created by TIGER on 2019/12/27.
// Copyright © 2019 Xing. All rights reserved.
//
import UIKit
protocol ConsolidateNoticeTableViewCellDelegate {
func hideNotice(noticeNo:String)
func activeNotice(noticeNo:String)
}
class ConsolidateNoticeTableViewCell: UITableViewCell {
@IBOutlet weak var btnHide: UIButton!
@IBOutlet weak var btnYes: UIButton!
@IBOutlet weak var btnNo: UIButton!
@IBOutlet weak var imgLogo: UIImageView!
@IBOutlet weak var lblNoticeNo: UILabel!
@IBOutlet weak var lblNoticeTitle: UILabel!
@IBOutlet weak var lblNoticeContent: UILabel!
@IBOutlet weak var reqeustView: UIView!
var delegate:ConsolidateNoticeTableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBAction func tryHideMessage(_ sender: Any) {
delegate?.hideNotice(noticeNo: lblNoticeNo.text!)
}
@IBAction func tryDisagreeRequest(_ sender: Any) {
delegate?.activeNotice(noticeNo: lblNoticeNo.text! + "_0")
}
@IBAction func tryAgreeRequest(_ sender: Any) {
delegate?.activeNotice(noticeNo: lblNoticeNo.text! + "_1")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func set(model:NoticeModel) {
reqeustView.isHidden = true
btnHide.isHidden = false
btnYes.layer.cornerRadius = 7.0
btnNo.layer.cornerRadius = 7.0
btnHide.layer.cornerRadius = 7.0
lblNoticeNo.text = model.no
lblNoticeTitle.text = model.title
if model.content.count > 30 {
lblNoticeContent.text = model.content.prefix(30) + "..."
} else {
lblNoticeContent.text = model.content
}
if model.viewStatus != "True" {
lblNoticeTitle.font = UIFont.boldSystemFont(ofSize: 16.0)
} else {
lblNoticeTitle.font = UIFont.systemFont(ofSize: 16.0, weight: .thin)
}
if model.type == __NOTICE_REQUEST {
imgLogo.image = UIImage(named: "icon_notice_question")
if model.actionStatus != "True" {
reqeustView.isHidden = false
btnHide.isHidden = true
} else {
reqeustView.isHidden = true
btnHide.isHidden = false
}
} else if model.type == __NOTICE_NOTICE {
imgLogo.image = UIImage(named: "icon_notice_bell")
} else if model.type == __NOTICE_MESSAGE {
imgLogo.image = UIImage(named: "icon_notice_post")
} else if model.type == __NOTICE_WARNING {
imgLogo.image = UIImage(named: "icon_notice_remark")
}
}
}
extension ConsolidatedViewController:ConsolidateNoticeTableViewCellDelegate {
func hideNotice(noticeNo: String) {
selectedNoticeNo = noticeNo
isClickHiddenBtn = true
sendNoticeRequest(sqlNo: __NOTICE_HIDDEN, searchKey: noticeNo)
}
func activeNotice(noticeNo: String) {
isClickActionBtn = true
let noticeNoArr = noticeNo.split(separator: "_")
selectedNoticeNo = String(noticeNoArr[0])
sendNoticeRequest(sqlNo: __NOTICE_ACTED, searchKey: noticeNo)
}
}
| [
-1
] |
a788b2729efebf9bdd1b67e4999da11f6d627452 | b769f830b01fdb8f03ba3a868ea47bbf53c76736 | /EXCurriculum/ViewController.swift | 218b99ffd694113c24884855a7dd988a900df507 | [] | no_license | erick100f/EXCurriculum-VIPER | 60ae5ed4e08f8a20529396d02664fb2aa827664f | b3ee11c4610dfb8ca77492b69c120a144edf55f5 | refs/heads/master | 2020-08-06T22:45:15.495076 | 2019-10-12T17:35:45 | 2019-10-12T17:35:45 | 213,187,377 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 499 | swift | //
// ViewController.swift
// EXCurriculum
//
// Created by Erick Cienfuegos on 9/29/19.
// Copyright © 2019 Erick Cienfuegos. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = EXConstants.cvTitle
}
@IBAction func startPress(_ sender: Any) {
let vc = EXCurriculumViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
}
| [
-1
] |
10d8081568897b907ebdb52329cde8560f0e5d0d | 715e7dd3f0ff47e7a2ff2e03a68f81b20b05eff6 | /btcutilTests/AddressTests.swift | ebb3d80147aebb63b8bbf712d1e3be306fa471e8 | [
"MIT"
] | permissive | jkandzi/btcutil.swift | 951c8af2fb180b8d49d4cfa6df756ccccfc716ba | 648d169f316cbbcbb51ce382e8908049283ed738 | refs/heads/master | 2021-01-24T16:15:24.214227 | 2018-02-28T16:16:09 | 2018-02-28T16:16:09 | 123,179,726 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 1,522 | swift | //
// btcutilTests
//
// Created by Justus Kandzi on 28.02.18.
// Copyright © 2018 Justus Kandzi. All rights reserved.
//
import XCTest
import btcutil
class AddressTests: XCTestCase {
func testAddressTypes() {
let tests: [(String, Address.AddressType)] = [
("17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem", .pubkeyHash),
("3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX", .scriptHash),
("5Hwgr3u458GLafKBgxtssHSPqJnYoGrSzgQsPwLFhLNYskDPyyA", .privateKey),
("mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn", .testnetPubkeyHash),
("2MzQwSSnBHWHqSAqtTVQ6v47XtaisrJa1Vc", .testnetScriptHash),
("92Pg46rUhgTT7romnV7iGW6W1gbGdeezqdbJCzShkCsYNzyyNcc", .testnetPrivateKey),
("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", .pubkeyHash),
("1111111111111111111114oLvT2", .pubkeyHash),
("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j", .pubkeyHash),
("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", .pubkeyHash),
]
for (input, type) in tests {
let address = Address(string: input)
XCTAssertEqual(address?.type, type)
}
}
func testInvalidAddresses() {
let invalid = [
"1badbadbadbadbadbadbadbadbadbadbad",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X",
"1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"
]
for input in invalid {
XCTAssertNil(Address(string: input))
}
}
}
| [
-1
] |
862b30076bb94a2bbedca5323189e48e53863b4b | 9160a4f7098a3d1478b488276f0d64b0f4ff43ed | /DatePicer/DatePicer/ViewController.swift | c36d7ae6e20359fc5405e4d6a06f169c5b8b13bf | [] | no_license | Prasetyo5/datePicer | 16c96214acd9523eae34a8f2307b994a1b08176f | 5b6f3812bb37cf17cc0acb20ed659d6bfbc6bdac | refs/heads/master | 2021-05-06T18:34:26.939494 | 2017-11-24T15:24:54 | 2017-11-24T15:24:54 | 111,932,333 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 846 | swift | //
// ViewController.swift
// DatePicer
//
// Created by FatahKhair on 11/24/17.
// Copyright © 2017 FatahKhair. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var LabelDate: UIDatePicker!
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func btnData(_ sender: Any) {
let dataFormatter = DateFormatter()
dataFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let strDate = dataFormatter.string(from: LabelDate.date)
Label.text = strDate
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
293888,
277508,
279046,
234511,
278543,
236057,
286234,
282145,
296487,
234551,
237624,
288827,
226878,
277057,
286786,
129604,
284740,
226887,
243786,
300107,
158285,
226896,
212561,
228945,
300116,
237655,
307288,
212573,
284261,
356460,
307311,
281202,
300149,
287350,
303242,
285837,
311437,
234641,
278675,
282262,
280219,
284315,
284317,
299165,
285855,
302235,
278693,
287399,
100521,
234665,
284336,
307379,
276150,
280760,
282301,
285377,
228551,
284361,
287437,
313550,
229585,
307410,
189655,
363743,
298211,
284391,
277224,
228585,
312049,
289524,
288501,
234232,
286462,
276736,
299786,
312586,
295696,
296216,
329499,
281373,
228127,
282917,
234279,
283433,
293682,
289596,
279360,
289600,
288579,
238920,
234829,
287055,
295766,
188253,
308064,
293742,
299374,
199024,
313733,
324491,
234380,
304015,
310673,
227740,
285087,
234402,
144811,
291755,
277935,
324528,
282548,
292277,
296374,
130487,
234423,
281530,
165832,
289224,
306633,
288205,
301012,
168936,
286189,
183278,
277487,
282095,
298989,
308721,
227315,
237556,
296436,
287231
] |
fd95f37149cbc3336f6bb37fe43e9f010772b4f8 | f33167ce04ca67b11d500a3f40d510e10133c9c3 | /ios/domain/utils/GetSdkConfig.swift | a601b7128e86fbb19e02c075ffd7f22d41979114 | [
"MIT"
] | permissive | pradeep-dev-shamlatech/ReactNativeSDK | d5ed7e36b3471c01e479f4d6068d58ecc4429c79 | 27919f66b3d9ec1f3a2cd5fbf9597ae60ca46b18 | refs/heads/master | 2023-01-14T16:27:27.076868 | 2020-11-26T16:02:43 | 2020-11-26T16:02:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 370 | swift | //
// GetSdkConfig.swift
// IdenfyReactNative
//
// Created by Viktor Vostrikov on 2020-10-13.
// Copyright © 2020 Facebook. All rights reserved.
//
import Foundation
import iDenfySDK
class GetSdkConfig {
static func getAuthToken(config: NSDictionary) -> String {
let authToken: String = config["authToken"] as! String
return authToken
}
}
| [
-1
] |
330a0978eab56047549e5dd3ce3cfd7d9f52d795 | d1275cc4051d121baef09c8b9002c6083e25dc18 | /Fursahh/HelperClasses/Constants/Constants.swift | 6084bba676dc88184313ab702d0ea4fbfe8efa33 | [] | no_license | Farhadsurani/fursah | 6d07677d72daba48349b2a2a04adfaf5d8e21e37 | 3ccabcb1749b9c3f9d7127dfa1a61964e9fdf561 | refs/heads/master | 2022-12-30T19:14:07.075457 | 2020-10-23T15:37:27 | 2020-10-23T15:37:27 | 306,673,778 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 839 | swift | //
// Constants.swift
// ProQ
//
// Created by Akber Sayni on 15/02/2019.
// Copyright © 2019 Akber Sayani. All rights reserved.
//
import UIKit
struct Constants {
static let APP_DELEGATE = UIApplication.shared.delegate as! AppDelegate
}
struct API {
static let INSTAGRAM_AUTHURL = "https://api.instagram.com/oauth/authorize/"
static let INSTAGRAM_USER_INFO = "https://api.instagram.com/v1/users/self/?access_token="
static let INSTAGRAM_CLIENT_ID = "c11dd1a5f92b4e3bbc760cf665a35b34"
static let INSTAGRAM_CLIENT_SERCRET = "2e8ffaf3229c4251811329105ae7b78e"
static let INSTAGRAM_REDIRECT_URI = "http://fursahh.com"
static let INSTAGRAM_SCOPE = "basic"
//static let INSTAGRAM_SCOPE = "follower_list+public_content" /* add whatever scope you need https://www.instagram.com/developer/authorization/ */
}
| [
-1
] |
b7334e5529b6066f29046e57fd8e55153cca6d87 | 90f6b57674ceda51751ddb3cab5edb6cc15056cb | /Memorize/Memorize/Grid.swift | 7ed8abd3bdee245b94ea6d970c5ce6116ecfe0e3 | [] | no_license | yyu/DevApps4iOSStanford2020 | c19425667956f010585a60ddb85f490cd5efbdfd | 5fcc447aab6c40987ab0111f5e9da267cbe67363 | refs/heads/master | 2022-11-24T23:51:58.762716 | 2020-08-02T03:50:12 | 2020-08-02T03:52:33 | 282,397,688 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,425 | swift | //
// Grid.swift
// Memorize
//
// Created by Yuan Yu on 7/27/20.
// Copyright © 2020 YY. All rights reserved.
//
import SwiftUI
struct Grid<Item, ItemView>: View where Item: Identifiable, ItemView: View {
private var items: [Item]
private var viewForItem: (Item) -> ItemView
init(_ items: [Item], viewForItem: @escaping (Item) -> ItemView) {
self.items = items
self.viewForItem = viewForItem
}
var body: some View {
GeometryReader { geometry in
self.body(for: GridLayout(itemCount: self.items.count, in: geometry.size))
}
}
private func body(for layout: GridLayout) -> some View {
ForEach(items) { item in
self.body(for: item, in: layout)
}
}
private func body(for item: Item, in layout: GridLayout) -> some View {
let index = items.firstIndex(matching: item)!
return viewForItem(item)
.frame(width: layout.itemSize.width, height: layout.itemSize.height)
.position(layout.location(ofItemAt: index))
// could be written as:
// let index = items.firstIndex(matching: item)
// return Group {
// if index != nil {
// viewForItem(item)
// .frame(width: layout.itemSize.width, height: layout.itemSize.height)
// .position(layout.location(ofItemAt: index!))
// }
// }
}
}
| [
-1
] |
1b8635445b3b25dfc095637dd320e2db87c6ea6d | 809161a095fbb1f208957164c2d4977051d32c16 | /PrimaMateria/Source/Features/Preferences/SUIPreferencesHostingController.swift | 64a9b3bce3dc64c8617d51b18bb7971b072e848b | [] | no_license | jep9816/PrimaMateria | f6c7a688391165d4b39ff0b510d9539903443475 | e3d984d9d2df8f97c46d3f7b5fe9e3bff5696a46 | refs/heads/master | 2023-06-07T22:59:09.893984 | 2023-06-03T16:42:04 | 2023-06-03T16:42:04 | 20,577,503 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 282 | swift | //
// SUIPreferencesHostingController.swift
// PrimaMateria
//
// Created by Jerry Porter on 7/22/21.
// Copyright ©2023 Jerry Porter. All rights reserved.
//
import UIKit
import SwiftUI
class SUIPreferencesHostingController: UIHostingController<SUIPreferencesView> {
}
| [
-1
] |
b2086466eb02e27a518fd5c6714922c0178f0b19 | cafbd8b0c92b5f4a3609c63b071a2515fb04e278 | /Todoey/Data Model/Category.swift | 364ad5e1d356af2a0fc78c67c021d967411df149 | [] | no_license | kahwai1234/Todoey | 3c7ffdcb7d4ad8bb32fdf447ce697f12e2887e79 | c43fb1cfa8631e1dbcd1b8603f58019fe8c9f236 | refs/heads/master | 2020-04-18T22:14:25.612796 | 2019-02-16T13:37:45 | 2019-02-16T13:37:45 | 167,787,867 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 368 | swift | //
// Category.swift
// Todoey
//
// Created by Kahwai Lee on 7/2/19.
// Copyright © 2019 Kahwai Lee. All rights reserved.
//
import Foundation
import RealmSwift
class Category: Object {
@objc dynamic var name:String=""
@objc dynamic var hexValue:String=""
let items=List<Item>() // == single relationship to items
//var array=[Item]()
}
| [
-1
] |
000e08413f2568902cda727bf34e06d80859bfb5 | 225aa5326db6e2ce3c1a87ffef83351c0a5bf003 | /SwiftStateTests/MyState.swift | 0b432d010dcd88e870b0e12159e233301f156d96 | [
"MIT"
] | permissive | norfanos/SwiftState | 2db9722e819d4f0ce61bb632fd7d74440067a964 | 02df79641bb458b66a9f9705992d9347b24b69ea | refs/heads/master | 2020-05-30T17:43:24.087672 | 2014-09-22T07:41:38 | 2014-09-22T14:27:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 759 | swift | //
// MyState.swift
// SwiftState
//
// Created by Yasuhiro Inami on 2014/08/03.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import SwiftState
enum MyState: Int, StateType, Printable
{
case State0, State1, State2, State3
case AnyState // IMPORTANT: create case=Any & use it in convertFromNilLiteral()
//
// NOTE: enum + associated value is our future, but it won't conform to Equatable so easily
// http://stackoverflow.com/questions/24339807/how-to-test-equality-of-swift-enums-with-associated-values
//
//case MyState(Int)
static func convertFromNilLiteral() -> MyState
{
return AnyState
}
var description: String
{
return "\(self.rawValue)"
}
} | [
-1
] |
9f89af72071f61b06d473afba3c87ed50f2ca735 | 79bd435b108330e4cd1a2d4586f668d05a0e2dfb | /DataModels/PersistedObjects/DownloadedVideoPersistedObject.swift | b6df4d167838934f54332076070cbb9257374ffc | [
"MIT"
] | permissive | samwelnella/OpenTube | 198196eb02b6ef7e39250dabced200b2cbaf5b72 | de205ec57d72243446ad1733d1cf592e24792cd0 | refs/heads/master | 2022-11-11T10:25:30.855043 | 2020-06-26T04:45:49 | 2020-06-26T04:45:49 | 275,056,435 | 0 | 0 | MIT | 2020-06-26T02:22:03 | 2020-06-26T02:22:03 | null | UTF-8 | Swift | false | false | 643 | swift |
import Foundation
import RealmSwift
final class DownloadedVideoPersistedObject: Object {
@objc dynamic var remoteUrlString: String = ""
@objc dynamic var fileName: String = ""
@objc dynamic var videoEntry: VideoPersistedObject!
var remoteUrl: URL {
return URL(string: remoteUrlString).unsafelyUnwrapped
}
var localUrl: URL {
return DownloadManager.mediaDirectory.appendingPathComponent(fileName)
}
convenience init(model: VideoModel, remoteUrl: URL, fileName: String) {
self.init()
self.remoteUrlString = remoteUrl.absoluteString
self.fileName = fileName
self.videoEntry = model.persisted
}
}
| [
-1
] |
b460df4174535b75b5fe4d8ac48057439e5851b9 | 58c09fedb0ca4945e8654fb0d4170b2c6e007d4d | /ImageClassificationTests/RemoteConversationVCTests.swift | d915f766ebf90ca718b2cca711ae160f163052cc | [] | no_license | Cortlandd/iASL-iOS | 05c0c8b1b6acc77cb584fd44c1e71b569ed787eb | dd47c9441638c095339255ee5b8450b4718c150f | refs/heads/master | 2023-03-15T17:20:32.250881 | 2021-03-07T07:29:58 | 2021-03-07T07:29:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,894 | swift | //
// RemoteConversationsTest.swift
// ImageClassificationTests
//
// Created by Liam Miller on 4/18/20.
// Copyright © 2020 Y Media Labs. All rights reserved.
//
import XCTest
@testable import iASL
class RemoteConversationVCTests: XCTestCase {
let partner = "bill_id"
//need to sign in
let email = "[email protected]"
let password = "password"
let uid = "ppmK3FXm7gPc6HwhS5wOvBtfLFP2"
var remote: RemoteConversationVC?
override func setUp() {
remote = RemoteConversationVC()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
///Test if the observe user messages function can run by looking for a boolean representing success as a result
func testObserveUserMessagesSuccess() {
let observeUserMessagesTrue = remote?.observeUserMessages(uid: uid)
XCTAssertTrue(observeUserMessagesTrue!)
}
///Test if the observe user messages function can fail by looking for a boolean representing failure as a result
func testObserveUserMessagesFailure() {
let observeUserMessagesFalse = remote?.observeUserMessages(uid: "")
XCTAssertFalse(observeUserMessagesFalse!)
}
///Test if the observe delete messages function can run by looking for a boolean representing success as a result
func testObserveDeleteMessagesSuccess() {
let deleteTestSuccess = remote?.handleDeleteNote(uid: uid)
XCTAssertTrue(deleteTestSuccess!)
}
///Test if the observe delete messages function can fail by looking for a boolean representing failure as a result
func testObserveDeleteMessagesFailure() {
let deleteTestFailure = remote?.handleDeleteNote(uid: "")
XCTAssertFalse(deleteTestFailure!)
}
}
| [
-1
] |
64656ebe4ccb7b17fea26055928052bd4d766166 | 4d428aa870c0692a9f45eb35b847a224cb78b809 | /SiXinWen-iOS/LoginController.swift | c22b81ed8ad1bdfe6160ec6ce1004885bd5df6e9 | [] | no_license | SiXinWen/SiXinWen-iOS | 69c53df67b8591edeab80e05ddc282311321a77f | 4edce813bce1e7bf593c462e891f8998aa2b6227 | refs/heads/master | 2021-01-13T02:04:16.313077 | 2015-07-02T15:38:33 | 2015-07-02T15:38:33 | 32,501,997 | 0 | 2 | null | 2015-03-20T09:12:59 | 2015-03-19T05:04:09 | Swift | UTF-8 | Swift | false | false | 3,461 | swift | //
// LoginController.swift
// SiXinWen-iOS
//
// Created by walker on 15/5/11.
// Copyright (c) 2015年 SiXinWen. All rights reserved.
//
import UIKit
import AVOSCloud
class LoginController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
// user log in
@IBAction func login() {
// ensure the name and password not empty
if usernameField.text == "" || passwordField.text == "" {
KVNProgress.showErrorWithStatus("用户名/密码不能为空")
return
}
KVNProgress.showWithStatus(" ")
// log in
AVUser.logInWithUsernameInBackground(usernameField.text, password: passwordField.text){
(user :AVUser!, error :NSError!) -> Void in
if error == nil {
// set the user name and nick name
me.username = AVUser.currentUser().username
me.nickname = AVUser.currentUser().objectForKey("NickName") as? String
// set the avatar
var avartarFile = AVUser.currentUser().objectForKey("Avartar") as? AVFile
if avartarFile != nil{
// find the avatar
avartarFile?.getDataInBackgroundWithBlock(){
(imgData:NSData!, error:NSError!) -> Void in
if(error == nil){
// save the avatar
me.avartar = UIImage(data: imgData)
// save the password\gender\email
me.password = AVUser.currentUser().password
me.gender = AVUser.currentUser().objectForKey("gender") as? String
me.email = AVUser.currentUser().objectForKey("email") as? String
KVNProgress.dismiss()
KVNProgress.showSuccessWithStatus("登陆成功")
self.navigationController?.popViewControllerAnimated(true)
}
else {
KVNProgress.dismiss()
// fail to get the avatar
KVNProgress.showErrorWithStatus("载入头像失败")
}
}
}
else {
// cannot find the avatar
// save the password\gender\email
me.password = AVUser.currentUser().password
me.gender = AVUser.currentUser().objectForKey("gender") as? String
me.email = AVUser.currentUser().objectForKey("email") as? String
KVNProgress.dismiss()
KVNProgress.showSuccessWithStatus("登陆成功")
self.navigationController?.popViewControllerAnimated(true)
}
}
else {
// fail to log in
KVNProgress.dismiss()
KVNProgress.showErrorWithStatus("用户名或密码错误")
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.hidden = true
}
}
| [
-1
] |
63b9f42f646873086f98540a32a86eb5defd6128 | a067bf52bce507343c27b91e916281c260f39621 | /ReactiveProjectTests/ReactiveProjectTests.swift | 3af0d2ebcef2b6b997b38bcec8b60f14db417141 | [] | no_license | hmmelton/ReactiveProject | 9a1dc7c11c5dd49b1b43fd7488af628336804c96 | 9baa2bb7cd50659f38454835024c5977c49eb7fb | refs/heads/master | 2021-06-22T09:50:28.640446 | 2017-08-18T19:06:24 | 2017-08-18T19:06:24 | 100,742,328 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,009 | swift | //
// ReactiveProjectTests.swift
// ReactiveProjectTests
//
// Created by Harrison Melton on 8/16/17.
// Copyright © 2017 Harrison Melton. All rights reserved.
//
import XCTest
@testable import ReactiveProject
class ReactiveProjectTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| [
333828,
282633,
313357,
182296,
317467,
241692,
98333,
16419,
102437,
229413,
292902,
204840,
354345,
223274,
278570,
344107,
233517,
124975,
253999,
229424,
346162,
229430,
319542,
124984,
358456,
288828,
325694,
288833,
288834,
352326,
254027,
311372,
311374,
354385,
196691,
315476,
280661,
329814,
278615,
338007,
307289,
200794,
354393,
180311,
180312,
315487,
237663,
309345,
280675,
227428,
280677,
307299,
313447,
329829,
278634,
315498,
319598,
288879,
352368,
299121,
284788,
233589,
280694,
333940,
237689,
288889,
292988,
215164,
313469,
215166,
278655,
292992,
333955,
280712,
215178,
235662,
241808,
323729,
325776,
317587,
278677,
284826,
278685,
346271,
311458,
278691,
233636,
49316,
299174,
333991,
333992,
284842,
32941,
278704,
239793,
323762,
299187,
278708,
125109,
131256,
182456,
295098,
184505,
280762,
299198,
379071,
299203,
301251,
309444,
227524,
338119,
299209,
282831,
321745,
286202,
254170,
356576,
317664,
280802,
338150,
176362,
321772,
286958,
125169,
338164,
327929,
184570,
243962,
227578,
125183,
309503,
125188,
184584,
313608,
125193,
375051,
180493,
125198,
325905,
254226,
125203,
319763,
296392,
125208,
325912,
309529,
299293,
278816,
125217,
233762,
211235,
217380,
305440,
227616,
151847,
282919,
211238,
98610,
125235,
332085,
280887,
125240,
332089,
278842,
282939,
315706,
287041,
241986,
260418,
332101,
182598,
323916,
319821,
254286,
348492,
250192,
6481,
323920,
344401,
348500,
366929,
289110,
155990,
366930,
6489,
272729,
379225,
106847,
323935,
391520,
321894,
280939,
242029,
246127,
354676,
199029,
139640,
246136,
246137,
291192,
291198,
313727,
362881,
248194,
311685,
225670,
395659,
227725,
395661,
240016,
178582,
190871,
291224,
293274,
317852,
283038,
61857,
285090,
381347,
61859,
289189,
246178,
375207,
289194,
108972,
340398,
377264,
299441,
61873,
61880,
283064,
293306,
278970,
319930,
336317,
293310,
299456,
291265,
278978,
127427,
127428,
283075,
291267,
188871,
324039,
317901,
373197,
289232,
281040,
278993,
326100,
278999,
328152,
176601,
242139,
369116,
285150,
287198,
279008,
227809,
342498,
188894,
242148,
195045,
279013,
279018,
281072,
279029,
293367,
279032,
233978,
279039,
291333,
342536,
287241,
279050,
340490,
303636,
289304,
279065,
342553,
291358,
182817,
180771,
375333,
377386,
293419,
283184,
289332,
23092,
234036,
315960,
338490,
352829,
242237,
301638,
348742,
293448,
322120,
55881,
348749,
281166,
281171,
244310,
285271,
354911,
436832,
242273,
295519,
66150,
111208,
344680,
191082,
279146,
313966,
281199,
295536,
287346,
279164,
189057,
311941,
348806,
279177,
369289,
330379,
344715,
184973,
311949,
311954,
330387,
330388,
352917,
227990,
117397,
230040,
271000,
289434,
342682,
221852,
295576,
279206,
295590,
287404,
205487,
295599,
303793,
299699,
299700,
164533,
338613,
314040,
287417,
158394,
342713,
230072,
285373,
287422,
66242,
363211,
242386,
279252,
287452,
318173,
289502,
363230,
295652,
338662,
285415,
346858,
330474,
289518,
299759,
199414,
154359,
230134,
221948,
35583,
205568,
291585,
295682,
162561,
299776,
363263,
285444,
242433,
291592,
322319,
295697,
285458,
291604,
310036,
166676,
207640,
326429,
336671,
326433,
344865,
283430,
289576,
279336,
318250,
295724,
152365,
312108,
318252,
353069,
295729,
285487,
328499,
242485,
353078,
230199,
353079,
285497,
293693,
336702,
342847,
281408,
295746,
420677,
353094,
353095,
299849,
283467,
293711,
281427,
353109,
281433,
230234,
301918,
242529,
293730,
303972,
351077,
275303,
230248,
342887,
290811,
201577,
242541,
246641,
330609,
209783,
246648,
209785,
269178,
177019,
308092,
279417,
361337,
291712,
254850,
359298,
416646,
240518,
287622,
228233,
228234,
308107,
295824,
56208,
308112,
293781,
209817,
289690,
324506,
324507,
318364,
289698,
189348,
324517,
289703,
293800,
279464,
353195,
140204,
353197,
189374,
289727,
353216,
349121,
363458,
213957,
213960,
279498,
316364,
338899,
340955,
248797,
207838,
50143,
130016,
340961,
64485,
314342,
52200,
123881,
324586,
203757,
289774,
183279,
304110,
320494,
340974,
316405,
240630,
295927,
201720,
304122,
314362,
320507,
328700,
293886,
328706,
330754,
320516,
293893,
230410,
330763,
320527,
146448,
324625,
316437,
140310,
418837,
320536,
197657,
281626,
201755,
336929,
189474,
300068,
330788,
357414,
248872,
345132,
238639,
252980,
300084,
322612,
359478,
324666,
238651,
302139,
21569,
359495,
238664,
300111,
314448,
341073,
296019,
353367,
156764,
156765,
304222,
113760,
314467,
281700,
250981,
322663,
300136,
316520,
228458,
207979,
300135,
316526,
357486,
144496,
187506,
353397,
291959,
160891,
341115,
363644,
150657,
187521,
248961,
349316,
279685,
349318,
222343,
330888,
228491,
228493,
285838,
169104,
162961,
177296,
308372,
326804,
296086,
185493,
187544,
119962,
300187,
296092,
300188,
339102,
302240,
343203,
300201,
300202,
253099,
238765,
3246,
279728,
238769,
367799,
294074,
339130,
230588,
64700,
208058,
322749,
228542,
343234,
367810,
259268,
283847,
353479,
62665,
353481,
353482,
244940,
283852,
283853,
290000,
228563,
189652,
333011,
279765,
316627,
296153,
357595,
279774,
298212,
298213,
304356,
290022,
330984,
228588,
234733,
298221,
253167,
279792,
328940,
353523,
298228,
234742,
216315,
208124,
316669,
363771,
388349,
228609,
234755,
279814,
322824,
242954,
292107,
312587,
328971,
251153,
245019,
320796,
126237,
130338,
130343,
351537,
298291,
345396,
300343,
116026,
222524,
333117,
191990,
286018,
193859,
279875,
304456,
230729,
294218,
224586,
372043,
177484,
251213,
234831,
238927,
296273,
120148,
318805,
283991,
222559,
314720,
234850,
292195,
230756,
294243,
333160,
134506,
230765,
296303,
243056,
279920,
312689,
296307,
314739,
116084,
327025,
327031,
327024,
111993,
306559,
148867,
179587,
378244,
298374,
314758,
314760,
388487,
142729,
368011,
314766,
296335,
112017,
234898,
112018,
306579,
9619,
282007,
357786,
318875,
290207,
314783,
333220,
314789,
279974,
282024,
241066,
316842,
310701,
286129,
173491,
210358,
284089,
228795,
292283,
302529,
302531,
292292,
163268,
380357,
300487,
415171,
300489,
361927,
370123,
148940,
280013,
310732,
64975,
312782,
327121,
222675,
366037,
210390,
210391,
353750,
210393,
329173,
228827,
286172,
239068,
310757,
187878,
316902,
280041,
361963,
54765,
191981,
321009,
251378,
308723,
333300,
306677,
343542,
300535,
300536,
280055,
288249,
343543,
290300,
286205,
300542,
290301,
333303,
230913,
210433,
282114,
228867,
366083,
323080,
230921,
329225,
253452,
296461,
323087,
304656,
329232,
316946,
146964,
398869,
308756,
308764,
349726,
230943,
333343,
282146,
306723,
286244,
245287,
245292,
349741,
169518,
230959,
286254,
288309,
290358,
312889,
235070,
288318,
280130,
349763,
124485,
56902,
282183,
292423,
288326,
288327,
292425,
243274,
128587,
333388,
218696,
333393,
280147,
290390,
235095,
300630,
306776,
196187,
343647,
333408,
286306,
300644,
282213,
374372,
323178,
54893,
138863,
222832,
325231,
314998,
247416,
366203,
175741,
325245,
337535,
294529,
224901,
282245,
282246,
288392,
229001,
286343,
310923,
188048,
323217,
239250,
282259,
345752,
229020,
298654,
255649,
282273,
245412,
298661,
40613,
290471,
40614,
40615,
229029,
282280,
323236,
282276,
321207,
300728,
296632,
319162,
280251,
282303,
286399,
280257,
218819,
321219,
306890,
280267,
212685,
333517,
282318,
212688,
333520,
241361,
245457,
302802,
333521,
333523,
280278,
280280,
298712,
18138,
278234,
241365,
286423,
294622,
321247,
298720,
278240,
282339,
12010,
212716,
212717,
280300,
282348,
284401,
282358,
313081,
229113,
286459,
325371,
124669,
194303,
278272,
175873,
319233,
323331,
323332,
288512,
280329,
284429,
284431,
161554,
278291,
294678,
321302,
366360,
116505,
249626,
284442,
325404,
321310,
282400,
241441,
325410,
339745,
341796,
241442,
247590,
257830,
333610,
294700,
317232,
282417,
296755,
280374,
319288,
321337,
282427,
360252,
280380,
345919,
325439,
315202,
307011,
282434,
282438,
345929,
341836,
323406,
325457,
216918,
18262,
370522,
188251,
280410,
300894,
345951,
362337,
302946,
284514,
345955,
296806,
276327,
292712,
282474,
288619,
325484,
280430,
296814,
292720,
362352,
313199,
313203,
325492,
282480,
300918,
241528,
317304,
194429,
124798,
325503,
182144,
305026,
241540,
253829,
333701,
67463,
243591,
325515,
243597,
325518,
110480,
282518,
294807,
282519,
124824,
214937,
329622,
214938,
298909,
118685,
294809,
319392,
300963,
292771,
354212,
294823,
333735,
284587,
323507,
124852,
243637,
282549,
288697,
290746,
294843,
214977,
163781,
214984,
151497,
284619,
344013,
247757,
212946,
24532,
219101,
280541,
329695,
298980,
292836,
294886,
337895,
247785,
253929,
296941,
327661,
362480,
325619,
333817,
292858,
313339
] |
e96bf151eaacb7d5264f8bc1dcefec7d8007942e | 1505f2d3d1737eedc3cb0dbc9bd32e47eb7014ab | /Sources/LyftUI/LyftDeepLink.swift | e8f5745cf835971fc15b544d2e51e1615016d119 | [
"Apache-2.0"
] | permissive | lyft/Lyft-iOS-sdk | 8a438c027c4946d8520a79f5060599403599ac98 | b0c5e3324cb3ac1aa585003c952d5b2d2f756359 | refs/heads/master | 2023-08-20T12:05:16.427225 | 2019-06-24T20:54:25 | 2019-06-24T20:54:25 | 71,945,625 | 51 | 33 | NOASSERTION | 2023-03-20T03:03:17 | 2016-10-25T22:53:22 | Swift | UTF-8 | Swift | false | false | 3,742 | swift | import CoreLocation
import Foundation
import UIKit
/// Designates the kind of deeplinking to perform
///
/// - native: Launches the native Lyft app if available
/// - web: Launches a safari view controller without leaving the app, enabling ride request function
public enum LyftDeepLinkBehavior {
case native
case web
fileprivate var baseUrl: URL {
switch self {
case .native:
return URL(staticString: "lyft://ridetype")
case .web:
return URL(staticString: "https://ride.lyft.com/u")
}
}
}
/// Collection of deep links into the main Lyft application
public struct LyftDeepLink {
/// Prepares to request a ride with the given parameters
///
/// - parameter behavior: The deep linking mode to use for this deep link
/// - parameter kind: The kind of ride to create a request for
/// - parameter pickup: The pickup position of the ride
/// - parameter destination: The destination position of the ride
/// - parameter couponCode: A coupon code to be applied to the user
public static func requestRide(using behavior: LyftDeepLinkBehavior = .native, kind: RideKind = .Standard,
from pickup: CLLocationCoordinate2D? = nil,
to destination: CLLocationCoordinate2D? = nil,
couponCode: String? = nil)
{
var parameters = [String: Any]()
parameters["partner"] = LyftConfiguration.developer?.clientId
parameters["credits"] = couponCode
parameters["id"] = kind.rawValue
parameters["pickup[latitude]"] = pickup.map { $0.latitude }
parameters["pickup[longitude]"] = pickup.map { $0.longitude }
parameters["destination[latitude]"] = destination.map { $0.latitude }
parameters["destination[longitude]"] = destination.map { $0.longitude }
self.launch(using: behavior, parameters: parameters)
}
private static func launch(using behavior: LyftDeepLinkBehavior, parameters: [String: Any])
{
let request = lyftURLEncodedInURL(request: URLRequest(url: behavior.baseUrl),
parameters: parameters).0
guard let url = request.url else {
return
}
switch behavior {
case .native:
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:]) { success in
if !success {
self.launchAppStore()
}
}
} else {
UIApplication.shared.openURL(url)
}
case .web:
Safari.openURL(url, from: UIApplication.shared.topViewController)
}
}
@available(iOS 10.0, *)
private static func launchAppStore() {
let signUp = LyftConfiguration.signUpIdentifier
let id = LyftConfiguration.developer?.clientId ?? "unknown"
let infoDictionary = Bundle.lyftSDKBundle?.infoDictionary
let version = infoDictionary?["CFBundleShortVersionString"] as? String ?? "?.?.?"
let url = "https://www.lyft.com/signup/\(signUp)?clientId=\(id)&sdkName=iOS&sdkVersion=\(version)"
if let signUpUrl = URL(string: url) {
UIApplication.shared.open(signUpUrl, options: [:], completionHandler: nil)
}
}
}
private extension UIApplication {
var topViewController: UIViewController? {
var topController = self.keyWindow?.rootViewController
while let viewController = topController?.presentedViewController {
topController = viewController
}
return topController
}
}
| [
310921
] |
34995669153691ad080b5031f04f0c041ad823f2 | a5a9690e8a50133d3166f4c02f076f12f126c748 | /DecisionsDecisons/ChoiceListVC.swift | 16ab5e3b240ddb4314c52cb233c4370ee5de7ae5 | [] | no_license | dancemonkey/decisionsDecisions | 09dd1f5868bc839ee41c9ab1c4800612ce92cadc | b477622622faa910a5878baccdce673130d8fe09 | refs/heads/master | 2021-01-09T20:00:44.171576 | 2016-08-14T03:33:16 | 2016-08-14T03:33:16 | 61,763,665 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,703 | swift | //
// ChoiceListVC.swift
// DecisionsDecisons
//
// Created by Drew Lanning on 7/11/16.
// Copyright © 2016 Drew Lanning. All rights reserved.
//
import UIKit
import CoreData
class ChoiceListVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var decision: Decision!
var newChoice: Choice!
var choiceList: [Choice]!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let choices = decision.choices {
choiceList = Array(choices) as? [Choice]
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return choiceList.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("choiceSelected", sender: choiceList[indexPath.row])
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("choiceCell", forIndexPath: indexPath) as! ChoiceCell
configureCell(cell, indexPath: indexPath)
return cell
}
func configureCell(cell: ChoiceCell, indexPath: NSIndexPath) {
cell.configureCell(withChoice: choiceList[indexPath.row])
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 115
}
@IBAction func newChoiceTapped(sender: UIButton) {
if let nc = NSEntityDescription.entityForName("Choice", inManagedObjectContext: appDel.managedObjectContext) {
self.newChoice = NSManagedObject(entity: nc, insertIntoManagedObjectContext: nil) as? Choice
performSegueWithIdentifier("newChoiceSegue", sender: self)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "newChoiceSegue" {
if let destVC = segue.destinationViewController as? AddChoiceVC {
destVC.newChoice = self.newChoice
destVC.decision = self.decision
}
}
if segue.identifier == "choiceSelected" {
if let destVC = segue.destinationViewController as? ChoiceVC {
destVC.choice = sender as? Choice
}
}
}
}
| [
-1
] |
1f44833c644dbb0782236e2e7a64be218a68d973 | c395ccab4a6454f0ea7b714dec50daba7677a37c | /TexInPdf/AuxTools/AuxFunctions.swift | b5aec92b10c00058bc3d66802bdd0632d7f56274 | [
"MIT"
] | permissive | chenxiaoyu233/TexInPdf | 4c7c7110b243b547e42b7b5c9dfc33b6a38617e5 | c8bc5c8b2060d8d2d02c4569667cfe2ed917ded2 | refs/heads/master | 2020-09-09T12:04:25.746445 | 2019-12-18T16:54:01 | 2019-12-18T16:54:01 | 221,442,206 | 2 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 520 | swift | //
// AuxFunctions.swift
// TexInPdf
//
// Created by 陈小羽 on 2019/12/11.
// Copyright © 2019 chenxiaoyu233. All rights reserved.
//
import Foundation
import Cocoa
func NewWindowController(storyboard: String, identifier: String) -> NSWindowController {
let storyboard = NSStoryboard(name: NSStoryboard.Name(storyboard), bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(identifier)) as! NSWindowController
return windowController
}
| [
-1
] |
34e77ed8525bf13776309983a7d6f4499ef726ad | fba18565b70dded4dc19cb50154dfb625b25982d | /IngenicoConnectKit/Enumerations/PreferredInputType.swift | 555068d0c5b074a45651fe79343bbad2efbf5718 | [
"MIT"
] | permissive | qlicks-team/connect-sdk-client-swift | 9e47faddea20e540470ccb67bbd1fbc559c27f27 | 3425414e24d65627f88030a35ea617dd1dc8eda8 | refs/heads/master | 2021-01-20T21:32:19.534439 | 2017-07-28T11:11:51 | 2017-07-28T11:11:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 343 | swift | //
// PreferredInputType.swift
// IngenicoConnectKit
//
// Created for Ingenico ePayments on 15/12/2016.
// Copyright © 2016 Global Collect Services. All rights reserved.
//
public enum PreferredInputType {
case stringKeyboard
case integerKeyboard
case emailAddressKeyboard
case phoneNumberKeyboard
case noKeyboard
}
| [
-1
] |
3f03b14f9635aa580130ac95f9336877cbf97ef4 | 0e70467b2630fa80c865fafe8804477efc5f4f63 | /OvercomingMS/UI Views/ReusableViews/TextFieldAbstractSVCs/AmountTFI.swift | 0d6f2b506a59418b7b5119c30fe865734e872e05 | [] | no_license | DrexelOMS/OvercomingMS | 26d5ed74d67faaf2a9d83853114bc8d09597b8dc | eb87d7058b643ce427ffe309b7fa63942833e8c8 | refs/heads/Development | 2020-04-15T03:03:21.413820 | 2019-05-28T20:01:48 | 2019-05-28T20:01:48 | 164,334,365 | 2 | 0 | null | 2019-05-28T00:39:31 | 2019-01-06T18:32:29 | Swift | UTF-8 | Swift | false | false | 1,458 | swift | //
// LengthTFI.swift
// OvercomingMS
//
// Created by Vincent Finn on 2/13/19.
// Copyright © 2019 DrexelOMS. All rights reserved.
//
import UIKit
class AmountTFI : TFIAbstract {
var savedText : String = ""
var selectedAmount : Int? {
didSet {
if isTenK {
textField.text = "\(selectedAmount!)k \(uom)"
}
else {
textField.text = "\(selectedAmount!) \(uom)"
}
}
}
var uom: String = ""
var isTenK: Bool = false
convenience init(uom: String, isTenK: Bool = false) {
self.init()
self.uom = uom
self.isTenK = isTenK
}
override func customSetup() {
super.customSetup()
label.text = "Amount"
}
override func showTextFieldInput() {
savedText = textField.text ?? ""
textField.text = ""
textField.keyboardType = .numberPad
}
override func doneFunction(){
if let text = textField.text {
if text != "" {
self.selectedAmount = Int(text) ?? 0
}
else {
textField.text = savedText
}
}
else {
textField.text = savedText
}
parentVC.view.endEditing(true)
}
override func cancelFunction() {
textField.text = savedText
super.cancelFunction()
}
}
| [
-1
] |
833dde41efe913d3ffe3278a8443eaa4aab56184 | 56aa35afb9c7ecae952cf60a80900ef3bb563beb | /SidebarMenu/NewsTableViewCell.swift | 9369964882b42e04808a03d266459460f4a889b6 | [] | no_license | abidgcuf/SportsGoLive | c909605bc1473a1ea1ec9b1858238d0290b94b99 | 3d5850f23fdb5f919c51bca0cf7433482ed47028 | refs/heads/master | 2016-08-12T08:18:59.650445 | 2016-04-07T06:11:38 | 2016-04-07T06:11:38 | 55,497,933 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 689 | swift | //
// NewsTableViewCell.swift
// SidebarMenu
//
// Created by Simon Ng on 2/2/15.
// Copyright (c) 2015 AppCoda. All rights reserved.
//
import UIKit
class NewsTableViewCell: UITableViewCell {
@IBOutlet weak var postImageView:UIImageView!
// @IBOutlet weak var authorImageView:UIImageView!
// @IBOutlet weak var postTitleLabel:UILabel!
// @IBOutlet weak var authorLabel:UILabel!
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
}
}
| [
172545,
322306,
277904,
230545,
307218,
320404,
336158,
123678,
366111,
123681,
349477,
278567,
293674,
287022,
300206,
110387,
281014,
282934,
289336,
292919,
123451,
228599,
66109,
306623,
200513,
306625,
306626,
306627,
317377,
317378,
317379,
142532,
313546,
311755,
278220,
311756,
311757,
311759,
228602,
282576,
310778,
332882,
278231,
290007,
291544,
298746,
235609,
235610,
282584,
200542,
226782,
317284,
115313,
244599,
244602,
196093,
285694
] |
bfe93b40f24d4b5b6dcaa4b21f8ea058da65e5ae | 6eb6d86b410f9a7c6a218ee3b8c102aa7ecf3a21 | /LImagePickerControllerTests/LImagePickerControllerTests.swift | f34da99595783feb89ffd5c75a46e78ae5fcbce0 | [
"MIT"
] | permissive | lessSource/LImagePicker | fe302aecaafe1d82758daabbb60e83a91ebb3836 | 390161572f793a83865be9bd2f6f9a75485eeb6c | refs/heads/master | 2023-06-26T20:12:31.472063 | 2021-08-06T10:03:37 | 2021-08-06T10:03:37 | 261,818,747 | 4 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 992 | swift | //
// LImagePickerControllerTests.swift
// LImagePickerControllerTests
//
// Created by L j on 2020/8/28.
// Copyright © 2020 L. All rights reserved.
//
import XCTest
@testable import LImagePickerController
class LImagePickerControllerTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| [
282633,
313357,
182296,
241692,
98333,
16419,
223268,
102437,
229413,
292902,
204840,
354345,
223274,
278570,
344107,
233517,
124975,
253999,
346162,
229430,
319542,
124984,
358456,
352315,
376894,
288833,
352326,
311372,
354385,
196691,
315476,
280661,
329814,
278615,
338007,
307289,
200794,
354393,
356447,
309345,
280675,
280677,
313447,
278634,
315498,
319598,
288879,
352368,
299121,
284788,
233589,
280694,
333940,
237689,
215164,
313469,
215166,
278655,
292992,
333955,
280712,
215178,
241808,
323729,
325776,
317587,
278677,
284826,
278685,
346271,
311458,
278691,
49316,
233636,
258214,
333991,
333992,
284842,
32941,
278704,
239793,
278708,
125109,
131256,
182456,
184505,
299198,
379071,
299203,
301251,
309444,
338119,
282831,
321745,
254170,
356576,
338150,
176362,
286958,
125169,
338164,
327929,
184570,
243962,
125183,
309503,
125188,
313608,
125193,
375051,
180493,
125198,
325905,
254226,
125203,
272660,
125208,
325912,
299293,
278816,
125217,
233762,
211235,
217380,
305440,
151847,
282919,
125235,
332085,
280887,
125240,
332089,
278842,
282939,
315706,
287041,
241986,
260418,
332101,
182598,
323916,
319821,
254286,
383311,
250192,
348492,
366930,
6481,
348500,
323920,
344401,
366929,
155990,
272729,
6489,
379225,
106847,
323935,
391520,
321894,
280939,
242029,
160110,
246127,
354676,
139640,
246136,
246137,
291192,
362881,
248194,
340357,
225670,
395659,
227725,
395661,
240016,
291224,
39324,
317852,
283038,
61857,
285090,
61859,
289189,
375207,
340398,
377264,
61873,
342450,
61880,
283064,
278970,
319930,
336317,
293310,
336320,
342466,
278978,
127427,
127428,
283075,
188871,
324039,
317901,
281040,
278993,
326100,
278999,
328152,
176601,
242139,
369116,
285150,
287198,
279008,
342498,
242148,
340453,
195045,
279013,
279018,
281072,
279029,
254456,
279032,
233978,
279039,
254465,
342536,
287241,
279050,
340490,
289304,
279065,
342553,
291358,
207393,
182817,
375333,
377386,
197167,
283184,
23092,
315960,
348732,
352829,
348742,
301638,
322120,
55881,
348749,
340558,
281166,
244310,
354911,
436832,
66150,
111208,
344680,
191082,
313966,
281199,
279164,
189057,
311941,
336518,
348806,
369289,
279177,
344715,
330379,
184973,
311949,
330387,
346772,
330388,
352917,
227990,
271000,
230040,
342682,
363163,
344738,
279206,
295590,
287404,
303793,
299699,
299700,
164533,
338613,
314040,
342713,
287417,
158394,
285373,
66242,
363211,
164560,
279252,
361176,
318173,
289502,
363230,
295652,
338662,
285415,
346858,
289518,
199414,
154359,
348920,
35583,
205568,
162561,
299776,
363263,
285444,
322319,
166676,
207640,
326429,
336671,
344865,
326433,
279336,
318250,
189228,
295724,
152365,
312108,
318252,
353069,
328499,
242485,
353078,
230199,
353079,
336702,
252741,
420677,
353094,
353095,
299849,
283467,
293711,
281427,
353109,
281433,
230234,
189275,
357218,
293730,
303972,
351077,
275303,
342887,
242541,
207727,
246641,
330609,
246648,
361337,
209785,
269178,
177019,
279417,
254850,
359298,
260996,
240518,
287622,
228233,
228234,
349067,
308107,
349072,
355217,
56208,
295824,
308112,
209817,
324506,
324507,
318364,
189348,
324517,
289703,
353195,
140204,
353197,
252847,
353216,
349121,
363458,
359364,
213960,
279498,
316364,
338899,
359381,
340955,
343005,
248797,
207838,
130016,
50143,
340961,
64485,
314342,
123881,
324586,
289774,
304110,
320494,
340974,
316405,
240630,
295927,
201720,
304122,
314362,
320507,
328700,
257024,
328706,
320516,
230410,
320527,
146448,
324625,
418837,
316437,
197657,
281626,
201755,
252958,
336929,
300068,
357414,
248872,
345132,
357423,
238639,
252980,
300084,
322612,
359478,
324666,
238651,
302139,
21569,
248901,
359495,
238664,
250954,
300111,
314448,
341073,
353367,
156764,
156765,
314467,
281700,
253029,
257125,
250981,
322663,
300136,
316520,
228458,
207979,
316526,
357486,
187506,
353397,
341115,
363644,
160891,
248961,
150657,
187521,
349316,
279685,
349318,
222343,
228491,
228493,
285838,
169104,
162961,
177296,
308372,
326804,
296086,
119962,
300187,
339100,
296092,
351390,
300188,
339102,
302240,
343203,
300201,
300202,
253099,
238765,
279728,
367799,
339130,
64700,
367810,
343234,
259268,
283847,
353479,
62665,
353481,
353482,
244940,
283852,
283853,
290000,
228563,
351446,
296153,
357595,
134366,
359647,
279774,
298212,
304356,
222440,
330984,
228588,
234733,
253167,
279792,
353523,
351476,
298228,
351478,
363771,
216315,
208124,
316669,
388349,
228609,
279814,
322824,
369930,
242954,
292107,
312587,
328971,
353551,
251153,
349462,
257305,
245019,
320796,
126237,
130338,
130343,
351537,
345396,
300343,
116026,
222524,
286018,
193859,
279875,
337225,
230729,
224586,
372043,
251213,
177484,
238927,
353616,
296273,
120148,
318805,
283991,
159066,
222559,
314720,
292195,
230756,
294243,
333160,
230765,
243056,
279920,
312689,
314739,
116084,
327025,
327031,
306559,
378244,
298374,
388487,
314758,
314760,
368011,
314766,
296335,
112017,
112018,
234898,
306579,
282007,
357786,
290207,
314783,
251298,
333220,
314789,
279974,
282024,
241066,
316842,
286129,
173491,
210358,
284089,
228795,
292283,
302529,
302531,
163268,
380357,
415171,
300487,
361927,
300489,
370123,
148940,
280013,
310732,
64975,
312782,
327121,
222675,
366037,
353750,
210391,
210392,
210390,
210393,
228827,
286172,
310757,
187878,
280041,
361963,
54765,
191981,
321009,
251378,
343542,
280055,
300536,
288249,
343543,
286205,
290301,
210433,
282114,
366083,
228867,
323080,
230921,
253451,
253452,
323087,
304656,
329232,
316946,
146964,
398869,
253463,
308764,
134686,
349726,
282146,
306723,
355876,
245287,
245292,
349741,
347694,
169518,
230959,
286254,
288309,
290358,
235070,
288318,
349763,
124485,
56902,
288326,
288327,
292425,
243274,
128587,
333388,
333393,
290390,
235095,
300630,
196187,
343647,
374372,
282213,
323178,
120427,
54893,
138863,
222832,
314998,
370296,
247416,
366203,
175741,
337534,
337535,
339584,
294529,
224901,
282245,
282246,
288392,
229001,
310923,
188048,
323217,
239250,
282259,
345752,
229020,
255649,
245412,
40613,
40614,
40615,
229029,
282280,
298661,
323236,
224946,
321207,
296632,
319162,
280251,
282303,
286399,
218819,
321219,
306890,
280267,
212685,
333517,
333520,
241361,
245457,
302802,
333521,
333523,
345814,
280278,
224984,
280280,
298712,
18138,
278234,
294622,
321247,
278240,
345834,
12010,
372460,
212716,
212717,
280300,
282348,
284401,
282358,
313081,
286459,
325371,
124669,
194303,
278272,
175873,
319233,
360195,
323331,
323332,
280329,
284429,
278291,
294678,
345879,
321302,
366360,
249626,
116505,
284442,
325404,
321310,
282400,
241441,
325410,
339745,
341796,
247590,
257830,
362283,
317232,
282417,
321337,
259899,
282427,
360252,
325439,
315202,
307011,
360264,
345929,
341836,
325457,
255829,
18262,
341847,
370522,
188251,
350044,
345951,
362337,
284514,
345955,
296806,
292712,
288619,
325484,
362352,
292720,
313203,
325492,
341879,
241528,
194429,
124798,
325503,
182144,
305026,
253829,
333701,
67463,
243591,
243597,
325518,
282518,
282519,
124824,
214937,
329622,
350109,
118685,
298909,
253856,
319392,
292771,
354212,
294823,
333735,
284587,
362417,
124852,
243637,
288697,
188348,
362431,
214977,
163781,
247757,
212942,
344013,
212946,
346067,
219101,
280541,
360417,
292836,
298980,
294886,
337895,
253929,
247785,
327661,
247791,
362480,
325619,
333817,
313339
] |
374dc9203275206c5f31e16bcb94f31e5f65a100 | ab3f946cfb71d2b48e294ede6bd4f2983a5b935f | /iExpense/Views/iExpenseApp.swift | 6ca3cead268b7f8939a64d42a695d9e0cb9c8010 | [] | no_license | theorangajang/iExpense | c181ac57d05335b4eabe4067425a4f6cbc473557 | 6b9fd92e464c1645246393c696ef671765508e76 | refs/heads/main | 2023-03-20T10:12:29.059054 | 2021-03-12T23:40:15 | 2021-03-12T23:40:15 | 324,283,671 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 242 | swift | //
// iExpenseApp.swift
// iExpense
//
// Created by Alex Jang on 12/21/20.
//
import SwiftUI
@main
struct iExpenseApp: App {
var body: some Scene {
WindowGroup {
ContentView().environmentObject(LoginViewModel())
}
}
}
| [
156438
] |
1e88ada560425f979c2819d03ec5029d79f73b18 | ee71ce1ab3a71bd0d15bdb537851cb0379d1e02c | /cotEditor/Document Window/Sidebar/SidebarViewController.swift | 69916e082b2ce4049f1e264b3d9ef98761935d09 | [
"MIT"
] | permissive | MoonfishApp/Composite | 9c08d3ecf3ed2b863b1ee875f72ef21ad99b4a25 | 1ccde807c690739b1739e22f02213e195265a992 | refs/heads/master | 2022-12-17T20:12:53.635892 | 2020-09-17T20:58:08 | 2020-09-17T20:58:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,885 | swift | //
// SidebarViewController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-06-05.
//
// ---------------------------------------------------------------------------
//
// © 2016-2018 1024jp
//
// 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
//
// https://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 Cocoa
protocol TabViewControllerDelegate: AnyObject {
func tabViewController(_ viewController: NSTabViewController, didSelect tabViewIndex: Int)
}
final class SidebarViewController: NSTabViewController {
enum TabIndex: Int {
case documentInspector
case outline
case incompatibleCharacters
}
// MARK: Public Properties
weak var delegate: TabViewControllerDelegate?
var selectedTabIndex: TabIndex { return TabIndex(rawValue: self.selectedTabViewItemIndex) ?? .documentInspector }
// MARK: Private Properties
@IBOutlet private weak var documentInspectorTabViewItem: NSTabViewItem?
@IBOutlet private weak var outlineTabViewItem: NSTabViewItem?
@IBOutlet private weak var incompatibleCharactersTabViewItem: NSTabViewItem?
// MARK: -
// MARK: Tab View Controller Methods
/// prepare tabs
override func viewDidLoad() {
super.viewDidLoad()
// bind segmentedControl manually (2016-09 on macOS 10.12)
if let segmentedControl = (self.tabView as? InspectorTabView)?.segmentedControl {
segmentedControl.bind(.selectedIndex, to: self, withKeyPath: #keyPath(selectedTabViewItemIndex))
}
// select last used pane
self.selectedTabViewItemIndex = UserDefaults.standard[.selectedInspectorPaneIndex]
// set accessibility
self.view.setAccessibilityElement(true)
self.view.setAccessibilityRole(.group)
self.view.setAccessibilityLabel("inspector".localized)
}
/// restore last state
override class var restorableStateKeyPaths: [String] {
return super.restorableStateKeyPaths + [
#keyPath(selectedTabViewItemIndex),
]
}
/// deliver passed-in document instance to child view controllers
override var representedObject: Any? {
didSet {
guard let document = representedObject as? TextDocument else { return }
self.documentInspectorTabViewItem?.viewController?.representedObject = document.analyzer
self.outlineTabViewItem?.viewController?.representedObject = document
self.incompatibleCharactersTabViewItem?.viewController?.representedObject = document.incompatibleCharacterScanner
}
}
override var selectedTabViewItemIndex: Int {
didSet {
guard selectedTabViewItemIndex != oldValue else { return }
self.delegate?.tabViewController(self, didSelect: self.selectedTabViewItemIndex)
if self.isViewLoaded { // avoid storing initial state (set in the storyboard)
UserDefaults.standard[.selectedInspectorPaneIndex] = self.selectedTabViewItemIndex
}
}
}
override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
super.tabView(tabView, didSelect: tabViewItem)
}
}
| [
-1
] |
0f9d2f51eab34b165f72a0e303c18c631f83fa9a | 322be5f2454237dc350e468eb4209f81c9f93a10 | /Sources/Fuzzilli/FuzzIL/Program.swift | 008848645941ba429486d382585e9313d18b0207 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | jack51706/fuzzilli | e746afe9ea39da96d0cd5927e6e7ed12923b523d | 94075e0ab35fb624e2f23d7663f61d8e9ce6ffc3 | refs/heads/master | 2022-12-16T08:00:52.844247 | 2020-09-11T12:45:59 | 2020-09-11T12:48:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,231 | swift | // Copyright 2019 Google LLC
//
// 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
//
// https://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.
/// Immutable unit of code that can, amongst others, be lifted, executed, scored, (de)serialized, and serve as basis for mutations.
///
/// A Program's code is guaranteed to have a number of static properties, as checked by code.isStaticallyValid():
/// * All input variables must have previously been defined
/// * Variables have increasing numbers starting at zero and there are no holes
/// * Variables are only used while they are visible (the block they were defined in is still active)
/// * Blocks are balanced and the opening and closing operations match (e.g. BeginIf is closed by EndIf)
/// * An instruction always produces a new output variable
///
public final class Program {
/// The immutable code of this program.
public let code: Code
/// Runtype types of variables if available.
public var runtimeTypes = VariableMap<[Int: Type]>()
/// Result of runtime type collection execution, by default there was none.
public var typeCollectionStatus = TypeCollectionStatus.notAttempted
/// Constructs an empty program.
public init() {
self.code = Code()
}
/// Constructs a program with the given code. The code must be statically valid.
public init(with code: Code) {
assert(code.isStaticallyValid())
self.code = code
}
/// The number of instructions in this program.
var size: Int {
return code.count
}
/// Indicates whether this program is empty.
var isEmpty: Bool {
return size == 0
}
/// Save type of given variable
public func setRuntimeType(of variable: Variable, to type: Type, at instrIndex: Int) {
// Initialize type structure for given variable if not already
if runtimeTypes[variable] == nil {
runtimeTypes[variable] = [:]
}
runtimeTypes[variable]![instrIndex] = type
}
}
extension Program: ProtobufConvertible {
public typealias ProtobufType = Fuzzilli_Protobuf_Program
func asProtobuf(with opCache: OperationCache?) -> ProtobufType {
return ProtobufType.with {
$0.instructions = code.map({ $0.asProtobuf(with: opCache) })
for (variable, instrMap) in runtimeTypes {
$0.runtimeTypes[UInt32(variable.number)] = Fuzzilli_Protobuf_TypeMap()
for (instrIndex, type) in instrMap {
$0.runtimeTypes[UInt32(variable.number)]!.typeMap[UInt32(instrIndex)] = type.asProtobuf()
}
}
$0.typeCollectionStatus = Fuzzilli_Protobuf_TypeCollectionStatus(rawValue: typeCollectionStatus.rawValue)!
}
}
public func asProtobuf() -> ProtobufType {
return asProtobuf(with: nil)
}
public convenience init(from proto: ProtobufType, with opCache: OperationCache?) throws {
var code = Code()
for protoInstr in proto.instructions {
code.append(try Instruction(from: protoInstr, with: opCache))
}
guard code.isStaticallyValid() else {
throw FuzzilliError.programDecodingError("Decoded code is not statically valid")
}
self.init(with: code)
for (varNumber, instrMap) in proto.runtimeTypes {
for (instrIndex, protoType) in instrMap.typeMap {
setRuntimeType(of: Variable(number: Int(varNumber)), to: try Type(from: protoType), at: Int(instrIndex))
}
}
self.typeCollectionStatus = TypeCollectionStatus(rawValue: proto.typeCollectionStatus.rawValue)
}
public convenience init(from proto: ProtobufType) throws {
try self.init(from: proto, with: nil)
}
}
| [
-1
] |
59524e7ca35851691ae5a8cfb9157888cf0fe78d | 06db9d3ee74036890fa471c5d3ea5d2bfd84d08f | /ImageGallery/ViewModel.swift | b4c6953eec180378c6d2aa6857b7d2e95f06e300 | [] | no_license | guangLess/imageLoadingWithGrids_and_subGrid | bf002080686f72d35b2a07154fc312c7986e0b44 | d9b0778ae9ee89b43671083d5c64708d169a7c1e | refs/heads/master | 2021-08-11T12:36:16.881915 | 2017-08-14T19:54:19 | 2017-08-14T19:54:19 | 110,582,634 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,455 | swift | //
// ImagesViewModel.swift
// ImageGallery
//
// Created by Guang on 8/5/17.
// Copyright © 2017 Guang. All rights reserved.
//
import Foundation
struct ViewModel {
let all: [ImageElement]
//collect each Album's first image
func getAlbumSamplesFromAll() -> [ImageElement] {
var albumSamples = [ImageElement]()
var tempAlbumIds = Set<Int>()
for each in all {
if !tempAlbumIds.contains(each.albumId) {
tempAlbumIds.insert(each.albumId)
albumSamples.append(each)
}
}
return albumSamples
}
//collect all the image elements from selected Album with bineray search
func getImagesWith(albumId id: Int) -> [ImageElement] {
var imagesFromAlbum = [ImageElement]()
func getStartIndex() -> Int {
var start = 0
var end = all.count
while start < end {
let mid = start + Int((end - start)/2)
if all[mid].albumId < id {
start = mid + 1
} else {
end = mid
}
}
return start
}
for each in all[getStartIndex()..<all.count] {
if each.albumId == id {
imagesFromAlbum.append(each)
} else { break }
}
//print(imagesFromAlbum.count)
return imagesFromAlbum
}
}
| [
-1
] |
e0df05e3c8358f165a10e6019e1571dcb9d39490 | 44559664be21675fa4d76c4c9fb1a5000b3844c7 | /MBMobileSDK/MBMobileSDK/Model/Business/AutomatedValetParking/AVPReservationStatusModel.swift | 2294408a935171d02e64c8ad2cea828b03913be0 | [
"MIT"
] | permissive | iospro/MBSDK-Mobile-iOS | 7813001c400a4ecae70b6cbbe6a88303a6f06c19 | 1abb6adcf59aeef1af42bf6c610d0fe82eed5e86 | refs/heads/master | 2023-06-21T04:39:10.429049 | 2021-07-22T13:38:06 | 2021-07-22T13:38:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,225 | swift | //
// Copyright © 2020 Daimler AG. All rights reserved.
//
import Foundation
/// Reservation status model of Automated Valet Parking
public struct AVPReservationStatusModel {
/// Reservation identifier
public let reservationId: String
/// Drive type of a reservation
public let driveType: AutomaticValetParkingDriveType?
/// Drive status of a reservation
public let driveStatus: AutomatedValetParkingDriveStatus
public let errorIds: [String]?
/// Estimated arrival time
public let estimatedTimeOfArrival: Date?
/// Parked location
public let parkedLocation: String?
public init(reservationId: String,
driveType: AutomaticValetParkingDriveType?,
driveStatus: AutomatedValetParkingDriveStatus,
errorIds: [String]? = nil,
estimatedTimeOfArrival: Date? = nil,
parkedLocation: String? = nil) {
self.reservationId = reservationId
self.driveType = driveType
self.driveStatus = driveStatus
self.errorIds = errorIds
self.estimatedTimeOfArrival = estimatedTimeOfArrival
self.parkedLocation = parkedLocation
}
}
| [
-1
] |
10a94e44a6a9fa5b4f69d5d16f736627a44a317a | ee9ce0d35ad6023c88ac6f21584e3e018beddf95 | /DremListerApp/DreamItem+CoreDataProperties.swift | 6c43999cf93f99900f2a0007bcdcaed1fd20ece3 | [] | no_license | emaddev/DreamList | d3039b60117996bde34b3caf09acff85a3daedda | 59a10638b77371b640ca25828e89cb5aa02d50c1 | refs/heads/master | 2021-01-16T00:09:54.271019 | 2017-08-10T20:34:10 | 2017-08-10T20:34:10 | 99,962,082 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 685 | swift | //
// DreamItem+CoreDataProperties.swift
// DremListerApp
//
// Created by Emad Roghani on 5/14/1396 AP.
// Copyright © 1396 AP Emad Roghani. All rights reserved.
//
import Foundation
import CoreData
extension DreamItem {
@nonobjc public class func fetchRequest() -> NSFetchRequest<DreamItem> {
return NSFetchRequest<DreamItem>(entityName: "DreamItem");
}
@NSManaged public var created: NSDate?
@NSManaged public var details: String?
@NSManaged public var price: String?
@NSManaged public var title: String?
@NSManaged public var toImage: Image?
@NSManaged public var toItemType: ItemType?
@NSManaged public var toStore: Store?
}
| [
-1
] |
f1e16d825f30d9b6e18b07dc9d99392d830e5d60 | f8451f412e35d86356d400e63c1f7e980963b50d | /NodeKit/Layers/ResponseProcessingLayer/ResponseDataParserNode.swift | 69cd00eca2bb3a09b38b307a2008cabf02839642 | [
"MIT"
] | permissive | IxllOllxl/NodeKit | 236789a966cce5b8fbd88c32525f52ef05f97243 | af8a498d61a4db37d60c97be54a1278f03102c93 | refs/heads/master | 2020-07-24T03:32:01.269713 | 2019-09-04T10:26:28 | 2019-09-04T10:26:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,613 | swift | //
// ResponseDataParserNode.swift
// CoreNetKit
//
// Created by Александр Кравченков on 04/02/2019.
// Copyright © 2019 Кравченков Александр. All rights reserved.
//
import Foundation
/// Ошибки для узлы `ResponseDataParserNode`
///
/// - cantDeserializeJson: Возникает в случае, если не удалось получить `Json` из ответа сервера.
/// - cantCastDesirializedDataToJson: Возникает в случае, если из `Data` не удалось сериализовать `JSON`
public enum ResponseDataParserNodeError: Error {
case cantDeserializeJson(String)
case cantCastDesirializedDataToJson(String)
}
/// Выполняет преобразование преобразование "сырых" данных в `Json`
/// - SeeAlso: `MappingUtils`
open class ResponseDataParserNode: Node<UrlDataResponse, Json> {
/// Следующий узел для обработки.
public var next: ResponsePostprocessorLayerNode?
/// Инициаллизирует узел.
///
/// - Parameter next: Следующий узел для обработки.
public init(next: ResponsePostprocessorLayerNode? = nil) {
self.next = next
}
/// Парсит ответ и в случае успеха передает управление следующему узлу.
///
/// - Parameter data: Модель овтета сервера.
open override func process(_ data: UrlDataResponse) -> Observer<Json> {
let context = Context<Json>()
var json = Json()
var log = self.logViewObjectName
do {
let (raw, logMsg) = try self.json(from: data)
json = raw
log += logMsg + .lineTabDeilimeter
} catch {
switch error {
case ResponseDataParserNodeError.cantCastDesirializedDataToJson(let logMsg), ResponseDataParserNodeError.cantDeserializeJson(let logMsg):
log += logMsg
default:
log += "Catch \(error)"
}
context.log(Log(log, id: self.objectName, order: LogOrder.responseDataParserNode)).emit(data: Json())
return context
}
guard let nextNode = next else {
log += "Next node is nil -> terminate chain process"
return context.log(Log(log, id: self.objectName, order: LogOrder.responseDataParserNode)).emit(data: json)
}
log += "Have next node \(nextNode.objectName) -> call `process`"
let networkResponse = UrlProcessedResponse(dataResponse: data, json: json)
return nextNode.process(networkResponse).log(Log(log, id: self.objectName, order: LogOrder.responseDataParserNode)).map { json }
}
/// Получает `json` из модели ответа сервера.
/// Содержит всю логику парсинга.
///
/// - Parameter responseData: Модель ответа сервера.
/// - Returns: Json, которй удалось распарсить.
/// - Throws:
/// - `ResponseDataParserNodeError.cantCastDesirializedDataToJson`
/// - `ResponseDataParserNodeError.cantDeserializeJson`
open func json(from responseData: UrlDataResponse) throws -> (Json, String) {
var log = ""
guard responseData.data.count != 0 else {
log += "Response data is empty -> returns empty json"
return (Json(), log)
}
guard let jsonObject = try? JSONSerialization.jsonObject(with: responseData.data, options: .allowFragments) else {
log += "Cant deserialize \(String(describing: String(data: responseData.data, encoding: .utf8)))"
throw ResponseDataParserNodeError.cantCastDesirializedDataToJson(log)
}
let anyJson = { () -> Json? in
if let result = jsonObject as? [Any] {
return [MappingUtils.arrayJsonKey: result]
} else if let result = jsonObject as? Json {
return result
} else {
return nil
}
}()
guard let json = anyJson else {
log += "After parsing get nil json"
throw ResponseDataParserNodeError.cantDeserializeJson(log)
}
if let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) {
log += "Result:" + .lineTabDeilimeter
log += String(data: data, encoding: .utf8) ?? "CURRUPTED"
}
return (json, log)
}
}
| [
-1
] |
ac3928c7bf4dd9bd4b5da3cc2061e2408300dcf8 | 81c3307b63bd97e5e92468b84ecd13c1c3059542 | /27.iOS9Swift2.2UIBezierPath/BezierCurves/ViewController.swift | a2ac300bac36bfb457d26f6379b4076bb0e8ef00 | [] | no_license | IvanAkulov/iOS-Demos | 13aec30fd38f4c7637eb95d01febe2b61174d41b | e7f5621df05d3cf03de72cb0df87fd473c811466 | refs/heads/master | 2023-02-08T00:30:05.510543 | 2023-01-26T09:03:10 | 2023-01-26T09:03:10 | 43,281,079 | 217 | 215 | null | null | null | null | UTF-8 | Swift | false | false | 486 | swift | //
// ViewController.swift
// BezierCurves
//
// Created by Ivan Akulov on 01/08/16.
// Copyright © 2016 Ivan Akulov. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
293888,
279041,
279046,
275466,
281107,
300057,
284197,
296489,
286249,
237616,
360501,
281142,
300089,
238653,
286786,
129604,
228932,
284240,
228945,
203858,
280146,
284242,
292435,
307288,
212573,
309347,
276580,
309349,
281701,
309351,
284261,
309353,
286314,
296042,
277612,
311913,
164974,
281703,
306791,
284275,
277108,
284277,
276597,
284279,
292478,
284289,
284298,
311437,
226447,
278675,
349332,
282262,
284315,
284317,
299165,
285855,
228000,
282275,
284323,
225955,
280231,
284328,
287399,
313007,
284336,
276150,
286390,
280760,
296638,
283839,
277696,
285377,
280770,
280772,
228548,
280775,
276167,
284361,
230604,
298189,
302286,
230608,
317137,
290004,
284373,
290006,
189655,
302295,
226009,
298202,
278749,
280797,
298206,
363743,
290020,
301284,
284391,
277224,
280808,
199402,
280810,
312049,
289524,
120054,
226038,
280826,
204027,
286462,
276736,
280832,
278786,
358147,
226055,
312586,
278298,
329499,
287004,
281373,
276256,
278304,
281380,
233767,
283433,
312107,
278845,
279360,
289600,
300358,
238920,
296272,
276309,
307029,
289112,
188253,
292701,
311645,
323933,
227688,
303977,
306540,
278897,
277364,
310649,
207738,
290175,
183173,
324491,
233869,
304015,
306578,
226196,
284570,
284574,
284577,
289187,
289190,
289191,
305577,
284586,
291755,
289196,
370093,
279982,
286126,
297903,
305582,
277935,
324528,
282548,
230323,
293816,
127418,
293308,
278973,
291774,
306633,
286158,
280015,
301012,
280030,
276959,
286175,
279011,
276965,
294889,
289771,
286189,
282095,
277487,
302580,
310773,
236022,
288251,
286204,
287231
] |
4494713a58109d5c535a41f7f1d24e7ff3041bff | 693e5283a3890817ee6f6069d8e0f86bc2df31de | /JYDYTabBar/JYDYTabBar/Comments.swift | 4d33234173145d0ece4c437c81195adb17c077b0 | [] | no_license | jydemo/JYSwift | 598031b39c8fc86beb7e42111202f613c1706553 | 7e026dd9f0480b13573ca662ec8888b9cbea15e1 | refs/heads/master | 2021-01-21T06:38:44.244608 | 2016-11-02T07:06:06 | 2016-11-02T07:06:06 | 83,263,138 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,406 | swift | //
// Hotcomments.swift
// JYDYTabBar
//
// Created by atom on 16/5/5.
// Copyright © 2016年 cyin. All rights reserved.
//
import UIKit
class Comments: NSObject {
var content: String? //= "\U7a7f\U82cf\U83f2\U7684\U597d\Uff0c\U5e7f\U544a\U4e0a\U8bf4\U5438\U6c34\U7279\U5f3a!";
var ctime: String? //= "2016-05-05 09:21:37";
var data_id: String? //= 18362009;
var id: String? //= 50768750;
var like_count: String? //= 3;
var user: User?
//precid //= 0;
//precmt //= (
//);
//preuid //= 0;
//status //= 0;
//voicetime = 0;
//voiceuri = "";
init(dict: [String: AnyObject]) {
super.init()
self.content = dict["content"] as? String
self.ctime = dict["ctime"] as? String
self.data_id = dict["data_id"] as? String
self.id = dict["id"] as? String
self.like_count = dict["like_count"] as? String
let userDict = dict["user"] as? [String: AnyObject]
self.user = User(dict: userDict!)
}
class func mode2Object(dict: [[String: AnyObject]]) -> [Comments] {
var models = [Comments]()
for model in dict {
models.append(Comments(dict: model))
}
return models
}
}
| [
-1
] |
39c8fe944081186d8a522bf2ea081a0eff2751d9 | b9650a680ced64ace8fec2687fd0378355ea53a5 | /Tests/MQTTTests/RemainLengthTests.swift | 8ab2bd7b011df0cc8fb85c344fd13def8e8cca59 | [
"MIT"
] | permissive | emorydunn/swift-mqtt | 2da2141311e9af880db59aa51a52626648eeac8a | c0a21bc899bfa5b81f6bf5cd01a4b35d7f43ba70 | refs/heads/master | 2023-03-21T01:01:47.080184 | 2020-08-30T10:46:43 | 2020-08-30T10:46:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,656 | swift | @testable import MQTT
import XCTest
final class RemainLengthTests: XCTestCase {
func testEncodeRemainLen() {
XCTAssert(encodeRemainLen(0) == Data([0]))
XCTAssert(encodeRemainLen(127) == Data([0x7F]))
XCTAssert(encodeRemainLen(128) == Data([0x80, 0x01]))
XCTAssert(encodeRemainLen(16383) == Data([0xFF, 0x7F]))
XCTAssert(encodeRemainLen(16384) == Data([0x80, 0x80, 0x01]))
XCTAssert(encodeRemainLen(2_097_151) == Data([0xFF, 0xFF, 0x7F]))
XCTAssert(encodeRemainLen(2_097_152) == Data([0x80, 0x80, 0x80, 0x01]))
XCTAssert(encodeRemainLen(268_435_455) == Data([0xFF, 0xFF, 0xFF, 0x7F]))
}
func testDecodeRemainingLength() {
var data = Data([0x00])
XCTAssert(try decodeRemainLen(data: &data) == 0)
data = Data([0x7F])
XCTAssert(try decodeRemainLen(data: &data) == 127)
data = Data([0x80, 0x01])
XCTAssert(try decodeRemainLen(data: &data) == 128)
data = Data([0xFF, 0x7F])
XCTAssert(try decodeRemainLen(data: &data) == 16383)
data = Data([0x80, 0x80, 0x01])
XCTAssert(try decodeRemainLen(data: &data) == 16384)
data = Data([0xFF, 0xFF, 0x7F])
XCTAssert(try decodeRemainLen(data: &data) == 2_097_151)
data = Data([0x80, 0x80, 0x80, 0x01])
XCTAssert(try decodeRemainLen(data: &data) == 2_097_152)
data = Data([0xFF, 0xFF, 0xFF, 0x7F])
XCTAssert(try decodeRemainLen(data: &data) == 268_435_455)
}
static var allTests = [
("testEncodeRemainLen", testEncodeRemainLen),
("testDecodeRemainingLength", testDecodeRemainingLength),
]
}
| [
-1
] |
0c3405defa6b2cb62861f47c2cbd05eef373fb2f | 22f1d607c7b9a12368e715ad133243a15682e5dd | /Customer/Extensions/Double+round.swift | c560003a182e60d4d276725f9b9ffb59e697158f | [] | no_license | AnilVarghese/customer | c4d5b5fc68c13954d2741752aef83dcaee79c19d | 40b07f80009c6fe7894a3a27e2a2934fd1f8a57b | refs/heads/master | 2020-04-26T12:09:15.444762 | 2019-03-03T10:28:32 | 2019-03-03T11:03:26 | 173,540,050 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 336 | swift | //
// Double+round.swift
// Customer
//
// Created by Anil Varghese on 03/03/19.
// Copyright © 2019 Anil Varghese. All rights reserved.
//
import Foundation
public extension Double {
func rounded(toDecimalPlace: Double) -> Double {
return (self * pow(10, toDecimalPlace)).rounded() / pow(10, toDecimalPlace)
}
}
| [
-1
] |
c693ea76657c552070ead44e9cbcafe4a1ab3d89 | 92f16a78784d3bf410604c2a7c329f7d250608ea | /ios/AwnCore/Classes/models/NotificationIntervalModel.swift | f02532cb49750fc3db0a2b147a70af72c8e64dcc | [
"Apache-2.0"
] | permissive | BrianTV98/awesome_notifications | a512648dd5206d2a31511fb58f5fd54e5758d87a | 4ffe0d49bbbe679e9ae5b7ffdfe9d4b4fc3c6bcc | refs/heads/master | 2023-06-28T22:13:32.177510 | 2023-06-13T03:52:59 | 2023-06-13T03:52:59 | 359,664,021 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,897 | swift | //
// NotificationIntervalModel.swift
// awesome_notifications
//
// Created by Rafael Setragni on 09/03/21.
//
import Foundation
public class NotificationIntervalModel : NotificationScheduleModel {
static let TAG = "NotificationIntervalModel"
var _createdDate:RealDateTime?
var _timeZone:TimeZone?
/// Initial reference date from schedule
public var createdDate:RealDateTime? { get{
return _createdDate
} set(newValue){
_createdDate = newValue
}}
/// Time zone reference date from schedule (abbreviation)
public var timeZone:TimeZone? { get{
return _timeZone
} set(newValue){
_timeZone = newValue
}}
/// Field number for get and set indicating the year.
var interval:Int?
/// Specify false to deliver the notification one time. Specify true to reschedule the notification request each time the notification is delivered.
var repeats:Bool?
public init(){}
public func fromMap(arguments: [String : Any?]?) -> AbstractModel? {
self._timeZone = MapUtils<TimeZone>.getValueOrDefault(reference: Definitions.NOTIFICATION_SCHEDULE_TIMEZONE, arguments: arguments)
self.createdDate = MapUtils<RealDateTime>.getRealDateOrDefault(reference: Definitions.NOTIFICATION_SCHEDULE_INITIAL_DATE, arguments: arguments, defaultTimeZone: RealDateTime.utcTimeZone)
self.interval = MapUtils<Int>.getValueOrDefault(reference: Definitions.NOTIFICATION_SCHEDULE_INTERVAL, arguments: arguments)
self.repeats = MapUtils<Bool>.getValueOrDefault(reference: Definitions.NOTIFICATION_SCHEDULE_REPEATS, arguments: arguments)
return self
}
public func toMap() -> [String : Any?] {
var mapData:[String: Any?] = [:]
if(_timeZone != nil) {mapData[Definitions.NOTIFICATION_SCHEDULE_TIMEZONE] = TimeZoneUtils.shared.timeZoneToString(timeZone: self._timeZone)}
if(createdDate != nil) {mapData[Definitions.NOTIFICATION_SCHEDULE_INITIAL_DATE] = self.createdDate!.description}
if(interval != nil) {mapData[Definitions.NOTIFICATION_SCHEDULE_INTERVAL] = self.interval}
if(repeats != nil) {mapData[Definitions.NOTIFICATION_SCHEDULE_REPEATS] = self.repeats}
return mapData
}
public func validate() throws {
if(IntUtils.isNullOrEmpty(interval) || interval! <= 5){
throw ExceptionFactory
.shared
.createNewAwesomeException(
className: NotificationIntervalModel.TAG,
code: ExceptionCode.CODE_INVALID_ARGUMENTS,
message: "Interval is required and must be greater than 5",
detailedCode: ExceptionCode.DETAILED_INVALID_ARGUMENTS+".notificationInterval.interval")
}
if((repeats ?? false) && interval! < 60){
throw ExceptionFactory
.shared
.createNewAwesomeException(
className: NotificationIntervalModel.TAG,
code: ExceptionCode.CODE_INVALID_ARGUMENTS,
message: "time interval must be at least 60 if repeating",
detailedCode: ExceptionCode.DETAILED_INVALID_ARGUMENTS+".notificationInterval.interval")
}
}
public func getUNNotificationTrigger() -> UNNotificationTrigger? {
do {
try validate();
let trigger = UNTimeIntervalNotificationTrigger( timeInterval: Double(interval!), repeats: repeats! )
return trigger
} catch {
Logger.e("NotificationIntervalModel", error.localizedDescription)
}
return nil
}
public func getNextValidDate() -> RealDateTime? {
let timeZone:TimeZone = self.timeZone ?? TimeZone.current
let referenceDate:RealDateTime =
(self.repeats ?? true) ?
RealDateTime(fromTimeZone: timeZone) :
createdDate ?? RealDateTime(fromTimeZone: timeZone)
guard let nextValidDate:Date =
DateUtils
.shared
.getNextValidDate(
fromScheduleModel: self,
withReferenceDate: referenceDate)
else { return nil }
return RealDateTime.init(
fromDate: nextValidDate,
inTimeZone: timeZone)
}
public func hasNextValidDate() -> Bool {
let timeZone:TimeZone = self.timeZone ?? TimeZone.current
let nowDate:RealDateTime? = RealDateTime(fromTimeZone: timeZone)
let nextValidDate:RealDateTime? = getNextValidDate()
return
nil != nextValidDate &&
nil != nowDate &&
nextValidDate! > nowDate!
}
}
| [
-1
] |
138987e7f014c80c981530b5bf9e4a9f511020a7 | 139c2a3508237be059dbf2f04592ee39bfd060f9 | /Wotspot Mobile/Extensions/String+isLink.swift | 72fc69f21478c85b0b55cc45a3c41a4f4706a59a | [
"MIT"
] | permissive | GrantJEmerson/Wotspot | 718dc1105e8130f3daf3c668e0975b713ddacffd | 039276ab342e1d06dba6d2cf2f0eb81d2bdcac36 | refs/heads/master | 2021-03-27T16:15:58.820233 | 2018-05-21T02:52:30 | 2018-05-21T02:52:30 | 115,978,224 | 2 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 615 | swift | //
// String+Links.swift
// Wotspot
//
// Created by Grant Emerson on 1/4/18.
// Copyright © 2018 Grant Emerson. All rights reserved.
//
import Foundation
extension String {
var isLink: Bool {
let types: NSTextCheckingResult.CheckingType = [.link]
let detector = try? NSDataDetector(types: types.rawValue)
guard (detector != nil && self.count > 0) else { return false }
if detector!.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) > 0 {
return true
}
return false
}
}
| [
-1
] |
4a292d27aa6f9b6283e43c11843231acc0837469 | be178ebf3f68881c2fe3c2df59b67a7754973401 | /iWallet/Views/ButtonWithRoundedCorner.swift | 5493863451c6aef736916dab510068b2192c6321 | [] | no_license | munibsiddiqui/iWallet | 338f782b951403d382eb7c5665c6f3a30e4c061c | 834306288e4d71ccaeca32fb0c3a819ae76a1394 | refs/heads/master | 2021-04-01T01:38:17.325091 | 2018-05-24T10:05:37 | 2018-05-24T10:05:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 466 | swift | //
// ButtonWithRoundedCorner.swift
// iWallet
//
// Created by Sergey Guznin on 5/15/18.
// Copyright © 2018 Sergey Guznin. All rights reserved.
//
import UIKit
class ButtonWithRoundedCorner: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = 10
clipsToBounds = true
layer.borderWidth = 1
layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
}
| [
-1
] |
8b19679099c4eb7a05bcfa51617ddb3343b1b8a7 | 031aa70fb25b8f810a7855bafc05a63198651e05 | /bk1ch04p158classInitializers2/bk1ch04p158classInitializers2/MyTableViewController.swift | 9c4da2e7153ff8d9560ded7ba53d419dad3977f2 | [] | no_license | CaiJianWeiAndLiuHua/Programming-iOS-Book-Examples-master | c73e9130e43c7335f418965f82cb2adac1d871e7 | 4a6483414e35c5163e94341514d9c3e40c640fc5 | refs/heads/master | 2021-01-17T10:52:28.126237 | 2016-06-22T06:43:52 | 2016-06-22T06:43:52 | 61,695,392 | 3 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,014 | swift |
import UIKit
class MyTableViewController: UITableViewController {
let greeting : String
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(greeting:String) {
self.greeting = greeting
super.init(style: .Plain)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
cell.textLabel?.text = self.greeting
return cell
}
}
| [
-1
] |
a8bf9bf11e491a1541812ec8424103a2a6a948ab | 95f715a96e15bd7bfc6bc8a4ce0576e122ba6de2 | /TiLcher/Service/Persistense/RealmObjectConvertable.swift | ff51c8b9c4d1a467c8b5d7a60c1c6b2b50deef8b | [] | no_license | kondranton/tilcher | a5d4438a0d965c1cab3bc7903a536fef57fc8aa4 | aa559040319d79854644696bfd6632ebd2fd75b4 | refs/heads/master | 2023-04-13T14:30:34.709353 | 2019-09-20T07:51:03 | 2019-09-20T07:51:03 | 204,576,592 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 201 | swift | import Foundation
import RealmSwift
protocol RealmObjectConvertable {
associatedtype RealmObjectType: Object
init(realmObject: RealmObjectType)
var realmObject: RealmObjectType { get }
}
| [
-1
] |
0055b89910fac043d1c75b4f4fcb493257a052aa | fe73b0024a20ca04830e40ad761388aff41e739a | /src/ui/osx/TogglDesktop/Features/AutoComplete/GenericAutoComplete/Storage/TagStorage.swift | f13d538f82dc977019dc9d26dea72fa0ad47291d | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | toggl-open-source/toggldesktop | c5075d194edfe0c936a851e6a7753c0b63a537c6 | 013038304ee8e9154db4a45fb642716956cf153b | refs/heads/master | 2023-08-30T14:58:53.807850 | 2023-06-22T11:38:35 | 2023-06-22T11:38:35 | 16,703,726 | 712 | 124 | BSD-3-Clause | 2022-08-31T10:06:31 | 2014-02-10T17:50:41 | C++ | UTF-8 | Swift | false | false | 1,245 | swift | //
// TagStorage.swift
// TogglDesktop
//
// Created by Nghia Tran on 4/5/19.
// Copyright © 2019 Alari. All rights reserved.
//
import Foundation
extension Notification.Name {
static let TagStorageChangedNotification = Notification.Name("TagStorageChangedNotification")
}
@objcMembers final class TagStorage: NSObject {
static let shared = TagStorage()
// MARK: Variables
private(set) var tags: [Tag] = []
// MARK: Public
func update(with viewItems: [ViewItem]) {
build(from: viewItems) {[weak self] tags in
guard let strongSelf = self else { return }
strongSelf.tags = tags
NotificationCenter.default.post(name: .TagStorageChangedNotification, object: tags)
}
}
func filter(with text: String) -> [Tag] {
let filters = tags.filter { $0.name.lowercased().contains(text.lowercased()) }
if filters.isEmpty {
return [Tag.noMatching]
}
return filters
}
func addNewTag(_ tag: Tag) {
tags.append(tag)
}
}
extension TagStorage {
fileprivate func build(from viewItems: [ViewItem], complete: @escaping ([Tag]) -> Void) {
complete(viewItems.map { Tag(viewItem: $0) })
}
}
| [
-1
] |
70e38534aaa097f1899f7b1e79e2189493a41329 | 4edd890178ba8a94c9ddc16cd652e3568e10ca62 | /Tests iOS/Tests_iOS.swift | df2c05e4be5f0a822abe9694d03878f59bba3663 | [] | no_license | H37kouya/swift-practice | 6817f10d41f224e20052f3e9643568d1de565556 | 33d7cd36d5faabfc0f64ef6341ee26b265513d28 | refs/heads/main | 2023-07-21T03:49:06.924556 | 2021-09-04T03:46:45 | 2021-09-04T03:46:45 | 402,362,060 | 0 | 0 | null | 2021-09-04T03:46:46 | 2021-09-02T09:24:35 | Swift | UTF-8 | Swift | false | false | 1,414 | swift | //
// Tests_iOS.swift
// Tests iOS
//
// Created by 樋口航也 on 2021/09/02.
//
import XCTest
class Tests_iOS: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| [
360463,
376853,
344106,
253996,
163894,
385078,
352314,
376892,
32829,
352324,
352327,
385095,
163916,
368717,
254039,
426074,
368732,
180317,
32871,
352359,
221292,
385135,
376945,
385147,
426124,
196758,
49308,
65698,
49317,
377008,
377010,
377025,
377033,
164043,
417996,
254157,
368849,
368850,
139478,
385240,
254171,
147679,
147680,
205034,
254189,
254193,
344312,
336121,
262403,
147716,
385291,
368908,
180494,
262419,
254228,
368915,
377116,
254250,
418095,
336177,
368949,
180534,
155968,
270663,
368969,
254285,
180559,
377168,
344402,
368982,
270703,
385407,
385409,
106893,
270733,
385423,
385433,
213402,
385437,
254373,
385448,
385449,
115116,
385463,
336319,
336323,
188870,
262619,
377309,
377310,
369121,
369124,
270823,
319976,
213486,
360945,
139766,
393719,
377337,
254459,
410108,
410109,
262657,
377346,
410126,
393745,
385554,
254487,
410138,
188957,
385569,
385578,
377388,
197166,
393775,
418352,
33339,
352831,
33344,
385603,
385612,
426575,
385620,
369236,
270938,
352885,
352886,
344697,
369285,
385669,
344714,
377487,
426646,
180886,
352921,
377499,
344737,
352938,
418479,
164532,
336565,
377531,
377534,
377536,
385737,
385745,
369365,
369366,
385751,
361178,
352989,
352990,
418529,
295649,
385763,
369383,
361194,
418550,
344829,
197377,
434956,
418579,
426772,
197398,
426777,
344864,
197412,
336678,
189229,
197424,
197428,
336693,
377656,
426809,
197433,
377669,
197451,
369488,
385878,
385880,
197467,
435038,
385895,
197479,
385901,
197489,
164730,
254851,
369541,
172936,
426894,
377754,
140203,
172971,
377778,
377789,
345034,
418774,
386007,
418781,
386016,
123880,
418793,
435185,
222193,
271351,
435195,
328701,
386049,
328705,
418819,
410629,
377863,
189448,
361487,
435216,
386068,
254997,
336928,
336930,
410665,
345137,
361522,
386108,
410687,
377927,
361547,
156763,
361570,
214116,
214119,
402538,
173168,
377974,
66684,
377986,
402568,
140426,
386191,
410772,
222364,
418975,
124073,
402618,
402632,
402641,
419028,
222441,
386288,
66802,
271607,
386296,
369913,
419066,
369912,
386300,
386304,
369929,
419097,
115997,
222496,
369964,
353581,
116014,
66863,
345397,
345398,
386363,
345418,
337226,
353612,
337228,
353611,
353617,
378201,
337280,
353672,
263561,
370066,
9618,
411028,
370072,
148900,
361928,
337359,
329168,
329170,
353751,
361958,
271850,
271853,
329198,
411119,
116209,
386551,
271880,
198155,
329231,
370200,
157219,
157220,
394793,
353875,
271980,
206447,
403057,
42616,
337533,
370307,
419462,
149127,
149128,
419464,
214667,
411275,
345753,
255651,
337590,
370359,
403149,
345813,
370390,
272087,
345817,
337638,
181992,
345832,
345835,
141037,
173828,
395018,
395019,
395026,
435993,
345882,
411417,
255781,
362281,
378666,
403248,
378673,
345910,
182070,
182071,
436029,
337734,
272207,
272208,
337746,
345942,
362326,
345950,
370526,
362336,
255844,
214894,
362351,
214896,
182145,
337816,
329627,
354210,
436130,
436135,
10153,
362411,
370604,
362418,
362442,
346066,
354268,
436189,
403421,
329696,
354273,
403425,
354279,
436199,
174058,
354283,
247787,
329707,
337899,
436209,
346117,
182277,
403463,
354311,
354312,
354310,
43016,
436235,
419857,
436248,
346153,
272432,
403507,
378933,
378934,
436283,
403524,
436293,
436304,
329812,
411738,
272477,
395373,
346237,
436372,
362658,
436388,
133313,
395458,
338118,
436429,
346319,
379102,
387299,
18661,
379110,
149743,
379120,
436466,
411892,
395511,
436471,
436480,
272644,
338187,
338188,
395536,
338196,
272661,
379157,
338217,
362809,
379193,
395591,
272730,
436570,
215395,
362864,
272755,
354678,
436609,
395653,
436613,
395660,
264591,
272784,
420241,
436644,
272815,
436659,
338359,
436677,
256476,
420326,
166403,
420374,
330291,
322119,
191065,
436831,
420461,
346739,
346741,
420473,
166533,
346771,
363155,
264855,
363161,
436897,
355006,
363228,
436957,
436960,
264929,
338658,
346859,
330476,
35584,
133889,
346889,
207639,
363295,
355117,
191285,
355129,
273209,
273211,
355136,
355138,
420680,
355147,
355148,
355153,
387927,
363353,
363354,
420702,
363361,
363362,
412516,
355173,
355174,
207724,
355182,
207728,
420722,
330627,
387977,
396171,
355216,
224146,
224149,
256918,
256919,
256920,
256934,
273336,
273341,
330688,
379845,
363462,
273353,
207839,
347104,
134124,
412653,
257007,
248815,
347122,
437245,
257023,
125953,
396292,
330759,
347150,
330766,
330789,
248871,
412725,
257093,
404550,
339031,
257126,
404582,
265318,
396395,
265323,
404589,
273523,
363643,
248960,
363658,
404622,
224400,
347286,
265366,
429209,
339101,
429216,
265381,
380069,
421050,
339131,
265410,
183492,
273616,
339167,
421102,
363769,
52473,
52476,
412926,
437504,
322826,
380178,
429332,
412963,
257323,
273713,
208179,
159033,
347451,
257353,
257354,
109899,
437585,
331091,
150868,
372064,
429410,
437602,
388458,
265579,
421240,
388488,
314765,
396697,
396709,
380335,
355761,
421302,
134586,
380348,
380350,
216511,
216510,
200136,
273865,
339403,
372172,
413138,
437726,
429540,
3557,
3559,
265720,
216575,
372226,
437766,
208397,
413202,
388630,
413206,
175640,
216610,
372261,
347693,
323120,
396850,
200245,
323126,
134715,
421437,
396865,
413255,
265800,
273992,
421452,
265809,
396885,
265816,
396889,
388699,
396896,
388712,
388713,
339579,
396927,
224907,
396942,
405140,
274071,
208547,
208548,
405157,
388775,
364202,
421556,
224951,
224952,
224985,
159462,
372458,
397040,
12017,
274170,
175874,
249606,
372497,
397076,
421657,
339746,
257831,
167720,
421680,
274234,
339782,
339799,
274288,
372592,
274296,
372625,
118693,
438186,
151492,
380874,
372699,
380910,
380922,
380923,
274432,
372736,
430120,
102446,
430127,
405552,
241717,
249912,
225347,
421958,
176209,
381013,
53334,
200795,
356446,
438374,
176231,
438378,
422000,
249976,
266361,
422020,
381061,
168070,
168069,
381071,
430231,
200856,
422044,
192670,
192671,
258213,
266427,
356550,
372943,
266447,
258263,
356575,
438512,
372979,
389364,
381173,
135416,
356603,
266504,
61720,
381210,
389406,
438575,
266547,
332084,
397620,
438583,
127292,
438592,
397650,
348499,
250196,
348501,
389465,
332128,
110955,
160111,
250227,
438653,
266628,
340356,
242059,
225684,
373141,
373144,
389534,
397732,
373196,
184799,
324098,
340489,
397841,
258584,
397855,
348709,
348710,
397872,
340539,
266812,
438850,
348741,
381515,
348748,
430681,
332379,
242274,
184938,
373357,
184942,
176751,
389744,
356983,
356984,
209529,
356990,
422529,
373377,
152196,
201348,
356998,
356999,
348807,
275102,
340645,
176805,
422567,
176810,
160441,
422591,
135888,
373485,
373486,
21239,
275193,
348921,
430853,
430860,
62222,
430880,
152372,
160569,
430909,
160576,
348999,
381791,
127840,
357219,
439145,
381811,
201590,
398205,
340865,
349066,
349068,
381840,
390034,
430999,
381856,
185252,
398244,
422825,
381872,
398268,
349122,
398275,
373705,
127945,
340960,
398305,
340967,
398313,
127990,
349176,
201721,
349179,
357380,
398370,
357413,
357420,
398405,
218187,
250955,
250965,
439391,
250982,
398444,
62574,
357487,
119925,
349304,
349315,
349317,
373902,
373937,
373939,
324790,
218301,
259275,
259285,
357594,
414956,
251124,
439550,
439563,
414989,
349458,
259346,
259347,
382243,
382257,
382264,
333115,
193853,
251212,
406862,
259408,
374110,
382329,
259449,
357758,
357763,
112019,
398740,
374189,
251314,
259513,
54719,
259569,
251379,
398844,
210429,
366081,
153115,
431646,
349727,
431662,
374327,
210489,
235069,
128589,
333389,
333394,
349780,
415334,
54895,
366198,
210558,
210559,
415360,
415369,
431754,
210569,
415376,
259741,
153252,
399014,
210601,
202413,
415419,
259780,
333508,
267978,
333522,
325345,
333543,
431861,
161539,
366358,
169751,
431901,
341791,
399148,
202541,
431918,
153392,
431935,
415555,
325444,
325449,
341837,
415566,
431955,
325460,
341846,
259937,
382820,
415592,
325491,
341878,
276343,
333687,
350072,
112510,
325508,
333700,
243590,
325514,
350091,
350092,
350102,
350108,
333727,
128955,
219102,
6116,
432114,
415740,
268286,
415744,
399372,
153618,
358418,
178215,
358455,
399433,
333902,
104534,
260206,
432241,
374913,
374914,
415883,
333968,
333990,
104633,
260285,
268479,
374984,
334049,
268515,
383208,
260337,
260338,
432373,
375040,
432387,
260355,
375052,
194832,
325904,
391448,
268570,
178459,
186660,
268581,
334121,
358698,
325930,
260396,
358707,
432435,
178485,
358710,
14654,
268609,
383309,
383327,
366948,
416101,
383338,
432503,
432511,
252309,
39323,
375211,
334259,
129461,
342454,
358844,
326083,
416201,
129484,
154061,
416206,
432608,
391654,
432616,
334315,
375281,
334345,
342537,
342549,
416288,
342560,
350758,
350759,
358952,
358951,
219694,
219695,
432694,
375369,
375373,
416334,
416340,
326229,
244311,
416353,
260705,
375396,
268901,
244345,
375438,
326288,
383668,
342714,
39616,
383708,
269036,
432883,
203511,
342775,
383740,
416509,
359166,
162559,
375552,
432894,
383755,
326413,
326428,
342827,
391980,
416577,
244569,
375644,
252766,
342888,
392057,
211835,
392065,
260995,
392071,
424842,
236427,
252812,
400271,
392080,
400282,
7070,
211871,
359332,
359333,
326571,
252848,
326580,
261045,
261046,
326586,
359365,
211913,
326602,
342990,
252878,
433104,
359380,
433112,
433116,
359391,
187372,
343020,
383980,
383994,
171009,
384004,
433166,
384015,
433173,
326684,
252959,
384031,
375848,
261191,
375902,
375903,
392288,
253028,
351343,
187505,
138354,
392317,
343166,
384127,
392320,
253074,
326803,
359574,
351389,
367791,
367792,
367798,
343230,
367809,
253124,
113863,
351445,
253168,
351475,
351489,
367897,
367898,
130347,
261426,
212282,
359747,
359748,
146763,
114022,
253288,
425327,
327023,
425331,
163190,
327030,
384379,
253316,
384391,
253339,
253340,
343457,
245160,
359860,
359861,
343480,
425417,
327122,
425434,
253431,
359931,
187900,
343552,
245249,
409095,
359949,
253456,
253462,
146976,
245290,
245291,
343606,
163385,
425534,
138817,
147011,
147020,
196184,
179800,
343646,
155238,
204394,
138862,
188021,
425624,
245413,
384693,
376502,
409277,
409289,
425682,
245471,
155360,
212721,
163575,
360194,
409355,
155408,
417556,
384826,
409404,
360253,
409416,
376661,
368471,
368486,
384871,
409446,
40809,
368489,
425832,
417648,
417658,
360315,
253828,
425875,
253851,
376733,
253868,
188349,
311238,
212947,
212953,
360416,
253930,
385011
] |
60d27878f6cde00a10037a5837b78ce4ea91bb5b | f34f2fc66da9058ff3d2d4e97f11b2cacd544152 | /Demo/DataControllers/Protocols/PostsNetworkDataControllerProtocol.swift | 7653a3baa315003ba75087b083755c0240c26478 | [] | no_license | sunshinejr/Demo | 3a100ed40f5df278a60e78ba6f6cc08f70a47b89 | 7fd352af14ef7751ff674dea66a76927fb8934a1 | refs/heads/master | 2021-07-09T17:12:55.840032 | 2019-06-04T20:34:09 | 2019-06-04T20:34:09 | 102,480,410 | 8 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 451 | swift | //
// PostsNetworkDataControllerProtocol.swift
// Demo
//
// Created by Lukasz Mroz on 05.09.2017.
// Copyright © 2017 Łukasz Mróz. All rights reserved.
//
import Result
import RxSwift
protocol PostsNetworkDataControllerProtocol {
func getPosts() -> Observable<Result<[Post], DemoError>>
func getAuthor(post: Post) -> Observable<Result<User, DemoError>>
func getComments(post: Post) -> Observable<Result<[Comment], DemoError>>
}
| [
-1
] |
fd266adbf7f42d1de0590b3d21f9e24ae17a0809 | 8afed433cb278973288eb95f58ad3e3daf528708 | /Swahn-Project/Swahn-Project/SelectWarehouseViewController.swift | 6010dbbf27144f2ecdd18ff559978cdf48b58d4d | [] | no_license | leodegeus7/LogisticDashboard | b2e360d95e709a8086fb16a572241c479db5ac6a | 4ba4af70332c9a0658b0a116d55b710a64131dc2 | refs/heads/master | 2020-04-27T15:16:53.876036 | 2019-03-08T00:54:46 | 2019-03-08T00:54:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 8,392 | swift | //
// SelectWarehouseViewController.swift
// Swahn-Project
//
// Created by Leonardo Geus on 31/07/2018.
// Copyright © 2018 Leonardo Geus. All rights reserved.
//
import UIKit
class SelectWarehouseViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var selectWarehouseLabel: UILabel!
@IBOutlet weak var viewBottomX: UIView!
@IBOutlet weak var warehouseCollectionView: UICollectionView!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var backTop: UIView!
var selectedItems = [Int]()
var license = ""
var warehouses = [Warehouse]()
var actualJourney:Journey!
override func viewDidLoad() {
super.viewDidLoad()
activityindicator(on: true)
FirestoreDatabase.shared.getWarehouses { (warehouses) in
self.activityindicator(on: false)
if let whouses = warehouses,whouses.count > 0 {
var newWh = whouses
newWh.removeAll(where: {$0.name == "Initial" || $0.name == "Final" || $0.name == "Line"})
self.warehouses = newWh
self.warehouseCollectionView.reloadData()
}
}
self.warehouseCollectionView.delegate = self
self.warehouseCollectionView.dataSource = self
self.warehouseCollectionView.backgroundColor = UIColor(red: 1/255, green: 53/255, blue: 101/255, alpha: 1)
nextButton.setTitleColor(UIColor.white, for: .normal)
nextButton.backgroundColor = UIColor(red: 0/255, green: 130/255, blue: 250/255, alpha: 1)
viewBottomX.backgroundColor = UIColor(red: 0/255, green: 130/255, blue: 250/255, alpha: 1)
selectWarehouseLabel.textColor = UIColor.white
backTop.backgroundColor = UIColor(red: 0/255, green: 65/255, blue: 124/255, alpha: 1)
self.view.backgroundColor = UIColor(red: 0/255, green: 65/255, blue: 124/255, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return warehouses.count
}
var buttonClicked = false
@IBAction func nextButtonTap(_ sender: Any) {
if !buttonClicked {
buttonClicked = true
if selectedItems.count > 0 {
self.createAlert(msg: "Entregue o dispositivo para o caminhoneiro e clique no botão iniciar.", cancel: false, cancelAction: { (alert) in
self.buttonClicked = false
}) { (bool) in
let warehouses = self.getWarehousesWithSelectedItems()
let truck = Truck(license: self.license, actualJourney: Journey(way: warehouses))
self.activityindicator(on: true)
FirestoreDatabase.shared.updateTruck(truck: truck) { (journey) in
self.activityindicator(on: false)
if let _ = journey {
FirestoreDatabase.shared.getNextPoint(truck: truck, completionHandler: { (lastWarehouse,nextWarehouse) in
self.nextWarehouse = FirestoreDatabase.shared.findWarehouse(withName: nextWarehouse!)!
self.lastWarehouse = FirestoreDatabase.shared.findWarehouse(withName: lastWarehouse!)!
self.truck = truck
self.actualJourney = journey
self.performSegue(withIdentifier: "showNavigation", sender: self)
})
} else {
self.createAlert(msg: "Problema ao adquirir sua rota, porfavor, contate um administrador", cancel: true, cancelAction: nil, completionHandler: { (bool) in
})
self.buttonClicked = false
}
}
}
}
}
}
func removeData() {
}
var nextWarehouse:Warehouse!
var lastWarehouse:Warehouse!
var truck:Truck!
func createAlert(msg:String,cancel:Bool,cancelAction:((UIAlertAction) -> Void)?,completionHandler: @escaping (Bool) -> Void) {
let alert = UIAlertController(title: "", message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancelar", style: .destructive, handler: cancelAction))
if !cancel {
alert.addAction(UIAlertAction(title: "Iniciar", style: .default, handler: { (alert) in
completionHandler(true)
}))
}
self.present(alert, animated: true)
}
var activityIndicator:UIActivityIndicatorView!
func activityindicator(on:Bool) {
if let _ = activityIndicator {
} else {
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
activityIndicator.color = UIColor.black
activityIndicator.center = self.view.center
activityIndicator.startAnimating()
}
if on {
self.view.addSubview(activityIndicator)
self.view.isUserInteractionEnabled = false
} else {
activityIndicator.removeFromSuperview()
self.view.isUserInteractionEnabled = true
}
}
func getWarehousesWithSelectedItems() -> [Warehouse] {
var ware = [Warehouse]()
for int in selectedItems {
ware.append(warehouses[int-1])
}
return ware
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showNavigation" {
var labels = [String]()
for item in selectedItems {
labels.append(warehouses[item - 1].name)
}
let controller = segue.destination as? MainViewController
controller!.actualJourney = actualJourney
controller?.nextWarehouse = nextWarehouse
controller?.lastWarehouse = lastWarehouse
controller?.truck = truck
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WarehouseCell", for: indexPath) as? SelectWarehouseCollectionViewCell
cell?.numberWarehouseLabel.text = warehouses[indexPath.row].name
cell?.backView.backgroundColor = UIColor(red: 17/255, green: 65/255, blue: 113/255, alpha: 1)
cell?.numberWarehouseLabel.textColor = UIColor.white
cell?.warehouseLabel.textColor = UIColor.white
return cell!
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.size.width)
let height:CGFloat = 100.0
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? SelectWarehouseCollectionViewCell
if selectedItems.contains(indexPath.row + 1) {
cell?.backView.backgroundColor = UIColor(red: 17/255, green: 65/255, blue: 113/255, alpha: 1)
selectedItems.remove(at: findIndexOf(indexPath.row + 1))
} else {
cell?.backView.backgroundColor = UIColor(red: 111/255, green: 159/255, blue: 193/255, alpha: 1)
selectedItems.append(indexPath.row + 1)
}
}
func findIndexOf(_ int:Int) -> Int {
var count = 0
for item in selectedItems {
if int == item {
break
}
count = count + 1
}
return count
}
}
| [
-1
] |
e9d16bfbc5b72aae1ac01b18cfcea86506f1826c | 8fd6661d37e31f1e0c040cec76930f5cca1afc57 | /iOS/三方库使用/Alamofire源码分析/Alamofire_Usage/Pods/Alamofire/Source/Request.swift | 56b75563132511888f177c706ab6dbb6a7e5245c | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lionsom/XiOS | f7d0182e73693f949e9f24bbc9caaed7d86b05fe | df6b127a156ad6da50f582213fdbcea18f23a0f7 | refs/heads/master | 2023-07-06T01:04:35.379824 | 2023-06-29T17:29:30 | 2023-06-29T17:29:30 | 192,576,052 | 20 | 3 | null | null | null | null | UTF-8 | Swift | false | false | 79,642 | swift | //
// Request.swift
//
// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
/// handling.
public class Request {
/// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
/// `cancel()` on the `Request`.
public enum State {
/// Initial state of the `Request`.
case initialized
/// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
/// them in this state.
case resumed
/// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
/// them in this state.
case suspended
/// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
/// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
/// to any other state.
case cancelled
/// `State` set when all response serialization completion closures have been cleared on the `Request` and
/// enqueued on their respective queues.
case finished
/// Determines whether `self` can be transitioned to the provided `State`.
func canTransitionTo(_ state: State) -> Bool {
switch (self, state) {
case (.initialized, _):
return true
case (_, .initialized), (.cancelled, _), (.finished, _):
return false
case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
return true
case (.suspended, .suspended), (.resumed, .resumed):
return false
case (_, .finished):
return true
}
}
}
// MARK: - Initial State
/// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
public let id: UUID
/// The serial queue for all internal async actions.
public let underlyingQueue: DispatchQueue
/// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
public let serializationQueue: DispatchQueue
/// `EventMonitor` used for event callbacks.
public let eventMonitor: EventMonitor?
/// The `Request`'s interceptor.
public let interceptor: RequestInterceptor?
/// The `Request`'s delegate.
public private(set) weak var delegate: RequestDelegate?
// MARK: - Mutable State
/// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
struct MutableState {
/// State of the `Request`.
var state: State = .initialized
/// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
/// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
/// `RedirectHandler` provided for to handle request redirection.
var redirectHandler: RedirectHandler?
/// `CachedResponseHandler` provided to handle response caching.
var cachedResponseHandler: CachedResponseHandler?
/// Queue and closure called when the `Request` is able to create a cURL description of itself.
var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)?
/// Queue and closure called when the `Request` creates a `URLRequest`.
var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)?
/// Queue and closure called when the `Request` creates a `URLSessionTask`.
var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)?
/// Response serialization closures that handle response parsing.
var responseSerializers: [() -> Void] = []
/// Response serialization completion closures executed once all response serializers are complete.
var responseSerializerCompletions: [() -> Void] = []
/// Whether response serializer processing is finished.
var responseSerializerProcessingFinished = false
/// `URLCredential` used for authentication challenges.
var credential: URLCredential?
/// All `URLRequest`s created by Alamofire on behalf of the `Request`.
var requests: [URLRequest] = []
/// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
var tasks: [URLSessionTask] = []
/// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
/// exactly the the `tasks` created.
var metrics: [URLSessionTaskMetrics] = []
/// Number of times any retriers provided retried the `Request`.
var retryCount = 0
/// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
var error: AFError?
/// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
/// representation in the state machine in the future.
var isFinishing = false
/// Actions to run when requests are finished. Use for concurrency support.
var finishHandlers: [() -> Void] = []
}
/// Protected `MutableState` value that provides thread-safe access to state values.
@Protected
fileprivate var mutableState = MutableState()
/// `State` of the `Request`.
public var state: State { $mutableState.state }
/// Returns whether `state` is `.initialized`.
public var isInitialized: Bool { state == .initialized }
/// Returns whether `state is `.resumed`.
public var isResumed: Bool { state == .resumed }
/// Returns whether `state` is `.suspended`.
public var isSuspended: Bool { state == .suspended }
/// Returns whether `state` is `.cancelled`.
public var isCancelled: Bool { state == .cancelled }
/// Returns whether `state` is `.finished`.
public var isFinished: Bool { state == .finished }
// MARK: Progress
/// Closure type executed when monitoring the upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
/// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
public let uploadProgress = Progress(totalUnitCount: 0)
/// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
public let downloadProgress = Progress(totalUnitCount: 0)
/// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
get { $mutableState.uploadProgressHandler }
set { $mutableState.uploadProgressHandler = newValue }
}
/// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
get { $mutableState.downloadProgressHandler }
set { $mutableState.downloadProgressHandler = newValue }
}
// MARK: Redirect Handling
/// `RedirectHandler` set on the instance.
public private(set) var redirectHandler: RedirectHandler? {
get { $mutableState.redirectHandler }
set { $mutableState.redirectHandler = newValue }
}
// MARK: Cached Response Handling
/// `CachedResponseHandler` set on the instance.
public private(set) var cachedResponseHandler: CachedResponseHandler? {
get { $mutableState.cachedResponseHandler }
set { $mutableState.cachedResponseHandler = newValue }
}
// MARK: URLCredential
/// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
public private(set) var credential: URLCredential? {
get { $mutableState.credential }
set { $mutableState.credential = newValue }
}
// MARK: Validators
/// `Validator` callback closures that store the validation calls enqueued.
@Protected
fileprivate var validators: [() -> Void] = []
// MARK: URLRequests
/// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
public var requests: [URLRequest] { $mutableState.requests }
/// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
public var firstRequest: URLRequest? { requests.first }
/// Last `URLRequest` created on behalf of the `Request`.
public var lastRequest: URLRequest? { requests.last }
/// Current `URLRequest` created on behalf of the `Request`.
public var request: URLRequest? { lastRequest }
/// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
/// `requests` due to `URLSession` manipulation.
public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap(\.currentRequest) } }
// MARK: HTTPURLResponse
/// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
/// last `URLSessionTask`.
public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
// MARK: Tasks
/// All `URLSessionTask`s created on behalf of the `Request`.
public var tasks: [URLSessionTask] { $mutableState.tasks }
/// First `URLSessionTask` created on behalf of the `Request`.
public var firstTask: URLSessionTask? { tasks.first }
/// Last `URLSessionTask` crated on behalf of the `Request`.
public var lastTask: URLSessionTask? { tasks.last }
/// Current `URLSessionTask` created on behalf of the `Request`.
public var task: URLSessionTask? { lastTask }
// MARK: Metrics
/// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
public var allMetrics: [URLSessionTaskMetrics] { $mutableState.metrics }
/// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first }
/// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last }
/// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var metrics: URLSessionTaskMetrics? { lastMetrics }
// MARK: Retry Count
/// Number of times the `Request` has been retried.
public var retryCount: Int { $mutableState.retryCount }
// MARK: Error
/// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
public fileprivate(set) var error: AFError? {
get { $mutableState.error }
set { $mutableState.error = newValue }
}
/// Default initializer for the `Request` superclass.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate)
{
self.id = id
self.underlyingQueue = underlyingQueue
self.serializationQueue = serializationQueue
self.eventMonitor = eventMonitor
self.interceptor = interceptor
self.delegate = delegate
}
// MARK: - Internal Event API
// All API must be called from underlyingQueue.
/// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
/// the `URLRequest` will be adapted before being issued.
///
/// - Parameter request: The `URLRequest` created.
func didCreateInitialURLRequest(_ request: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.requests.append(request) }
eventMonitor?.request(self, didCreateInitialURLRequest: request)
}
/// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
///
/// - Note: Triggers retry.
///
/// - Parameter error: `AFError` thrown from the failed creation.
func didFailToCreateURLRequest(with error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
callCURLHandlerIfNecessary()
retryOrFinish(error: error)
}
/// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
///
/// - Parameters:
/// - initialRequest: The `URLRequest` that was adapted.
/// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.requests.append(adaptedRequest) }
eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
}
/// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
///
/// - Note: Triggers retry.
///
/// - Parameters:
/// - request: The `URLRequest` the adapter was called with.
/// - error: The `AFError` returned by the `RequestAdapter`.
func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
callCURLHandlerIfNecessary()
retryOrFinish(error: error)
}
/// Final `URLRequest` has been created for the instance.
///
/// - Parameter request: The `URLRequest` created.
func didCreateURLRequest(_ request: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.read { state in
state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) }
}
eventMonitor?.request(self, didCreateURLRequest: request)
callCURLHandlerIfNecessary()
}
/// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
private func callCURLHandlerIfNecessary() {
$mutableState.write { mutableState in
guard let cURLHandler = mutableState.cURLHandler else { return }
cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
mutableState.cURLHandler = nil
}
}
/// Called when a `URLSessionTask` is created on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` created.
func didCreateTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { state in
state.tasks.append(task)
guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
}
eventMonitor?.request(self, didCreateTask: task)
}
/// Called when resumption is completed.
func didResume() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.requestDidResume(self)
}
/// Called when a `URLSessionTask` is resumed on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` resumed.
func didResumeTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didResumeTask: task)
}
/// Called when suspension is completed.
func didSuspend() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.requestDidSuspend(self)
}
/// Called when a `URLSessionTask` is suspended on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` suspended.
func didSuspendTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didSuspendTask: task)
}
/// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
func didCancel() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
error = error ?? AFError.explicitlyCancelled
eventMonitor?.requestDidCancel(self)
}
/// Called when a `URLSessionTask` is cancelled on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` cancelled.
func didCancelTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didCancelTask: task)
}
/// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
///
/// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.metrics.append(metrics) }
eventMonitor?.request(self, didGatherMetrics: metrics)
}
/// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
///
/// - Parameters:
/// - task: The `URLSessionTask` which failed.
/// - error: The early failure `AFError`.
func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
// Task will still complete, so didCompleteTask(_:with:) will handle retry.
eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
}
/// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
///
/// - Note: Response validation is synchronously triggered in this step.
///
/// - Parameters:
/// - task: The `URLSessionTask` which completed.
/// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
/// value is ignored.
func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = self.error ?? error
validators.forEach { $0() }
eventMonitor?.request(self, didCompleteTask: task, with: error)
retryOrFinish(error: self.error)
}
/// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
func prepareForRetry() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.retryCount += 1 }
reset()
eventMonitor?.requestIsRetrying(self)
}
/// Called to determine whether retry will be triggered for the particular error, or whether the instance should
/// call `finish()`.
///
/// - Parameter error: The possible `AFError` which may trigger retry.
func retryOrFinish(error: AFError?) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
guard !isCancelled, let error = error, let delegate = delegate else { finish(); return }
delegate.retryResult(for: self, dueTo: error) { retryResult in
switch retryResult {
case .doNotRetry:
self.finish()
case let .doNotRetryWithError(retryError):
self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
case .retry, .retryWithDelay:
delegate.retryRequest(self, withDelay: retryResult.delay)
}
}
}
/// Finishes this `Request` and starts the response serializers.
///
/// - Parameter error: The possible `Error` with which the instance will finish.
func finish(error: AFError? = nil) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
guard !$mutableState.isFinishing else { return }
$mutableState.isFinishing = true
if let error = error { self.error = error }
// Start response handlers
processNextResponseSerializer()
eventMonitor?.requestDidFinish(self)
}
/// Appends the response serialization closure to the instance.
///
/// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
///
/// - Parameter closure: The closure containing the response serialization call.
func appendResponseSerializer(_ closure: @escaping () -> Void) {
$mutableState.write { mutableState in
mutableState.responseSerializers.append(closure)
if mutableState.state == .finished {
mutableState.state = .resumed
}
if mutableState.responseSerializerProcessingFinished {
underlyingQueue.async { self.processNextResponseSerializer() }
}
if mutableState.state.canTransitionTo(.resumed) {
underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
}
}
}
/// Returns the next response serializer closure to execute if there's one left.
///
/// - Returns: The next response serialization closure, if there is one.
func nextResponseSerializer() -> (() -> Void)? {
var responseSerializer: (() -> Void)?
$mutableState.write { mutableState in
let responseSerializerIndex = mutableState.responseSerializerCompletions.count
if responseSerializerIndex < mutableState.responseSerializers.count {
responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
}
}
return responseSerializer
}
/// Processes the next response serializer and calls all completions if response serialization is complete.
func processNextResponseSerializer() {
guard let responseSerializer = nextResponseSerializer() else {
// Execute all response serializer completions and clear them
var completions: [() -> Void] = []
$mutableState.write { mutableState in
completions = mutableState.responseSerializerCompletions
// Clear out all response serializers and response serializer completions in mutable state since the
// request is complete. It's important to do this prior to calling the completion closures in case
// the completions call back into the request triggering a re-processing of the response serializers.
// An example of how this can happen is by calling cancel inside a response completion closure.
mutableState.responseSerializers.removeAll()
mutableState.responseSerializerCompletions.removeAll()
if mutableState.state.canTransitionTo(.finished) {
mutableState.state = .finished
}
mutableState.responseSerializerProcessingFinished = true
mutableState.isFinishing = false
}
completions.forEach { $0() }
// Cleanup the request
cleanup()
return
}
serializationQueue.async { responseSerializer() }
}
/// Notifies the `Request` that the response serializer is complete.
///
/// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
/// are complete.
func responseSerializerDidComplete(completion: @escaping () -> Void) {
$mutableState.write { $0.responseSerializerCompletions.append(completion) }
processNextResponseSerializer()
}
/// Resets all task and response serializer related state for retry.
func reset() {
error = nil
uploadProgress.totalUnitCount = 0
uploadProgress.completedUnitCount = 0
downloadProgress.totalUnitCount = 0
downloadProgress.completedUnitCount = 0
$mutableState.write { state in
state.isFinishing = false
state.responseSerializerCompletions = []
}
}
/// Called when updating the upload progress.
///
/// - Parameters:
/// - totalBytesSent: Total bytes sent so far.
/// - totalBytesExpectedToSend: Total bytes expected to send.
func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
}
/// Perform a closure on the current `state` while locked.
///
/// - Parameter perform: The closure to perform.
func withState(perform: (State) -> Void) {
$mutableState.withState(perform: perform)
}
// MARK: Task Creation
/// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
///
/// - Parameters:
/// - request: `URLRequest` to use to create the `URLSessionTask`.
/// - session: `URLSession` which creates the `URLSessionTask`.
///
/// - Returns: The `URLSessionTask` created.
func task(for _: URLRequest, using _: URLSession) -> URLSessionTask {
fatalError("Subclasses must override.")
}
// MARK: - Public API
// These APIs are callable from any queue.
// MARK: State
/// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
///
/// - Returns: The instance.
@discardableResult
public func cancel() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.cancelled) else { return }
mutableState.state = .cancelled
underlyingQueue.async { self.didCancel() }
guard let task = mutableState.tasks.last, task.state != .completed else {
underlyingQueue.async { self.finish() }
return
}
// Resume to ensure metrics are gathered.
task.resume()
task.cancel()
underlyingQueue.async { self.didCancelTask(task) }
}
return self
}
/// Suspends the instance.
///
/// - Returns: The instance.
@discardableResult
public func suspend() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.suspended) else { return }
mutableState.state = .suspended
underlyingQueue.async { self.didSuspend() }
guard let task = mutableState.tasks.last, task.state != .completed else { return }
task.suspend()
underlyingQueue.async { self.didSuspendTask(task) }
}
return self
}
/// Resumes the instance.
///
/// - Returns: The instance.
@discardableResult
public func resume() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.resumed) else { return }
mutableState.state = .resumed
underlyingQueue.async { self.didResume() }
guard let task = mutableState.tasks.last, task.state != .completed else { return }
task.resume()
underlyingQueue.async { self.didResumeTask(task) }
}
return self
}
// MARK: - Closure API
/// Associates a credential using the provided values with the instance.
///
/// - Parameters:
/// - username: The username.
/// - password: The password.
/// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
///
/// - Returns: The instance.
@discardableResult
public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
let credential = URLCredential(user: username, password: password, persistence: persistence)
return authenticate(with: credential)
}
/// Associates the provided credential with the instance.
///
/// - Parameter credential: The `URLCredential`.
///
/// - Returns: The instance.
@discardableResult
public func authenticate(with credential: URLCredential) -> Self {
$mutableState.credential = credential
return self
}
/// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
///
/// - Note: Only the last closure provided is used.
///
/// - Parameters:
/// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
/// - closure: The closure to be executed periodically as data is read from the server.
///
/// - Returns: The instance.
@discardableResult
public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
$mutableState.downloadProgressHandler = (handler: closure, queue: queue)
return self
}
/// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
///
/// - Note: Only the last closure provided is used.
///
/// - Parameters:
/// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
/// - closure: The closure to be executed periodically as data is sent to the server.
///
/// - Returns: The instance.
@discardableResult
public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
$mutableState.uploadProgressHandler = (handler: closure, queue: queue)
return self
}
// MARK: Redirects
/// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
///
/// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
///
/// - Parameter handler: The `RedirectHandler`.
///
/// - Returns: The instance.
@discardableResult
public func redirect(using handler: RedirectHandler) -> Self {
$mutableState.write { mutableState in
precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
mutableState.redirectHandler = handler
}
return self
}
// MARK: Cached Responses
/// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
///
/// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
///
/// - Parameter handler: The `CachedResponseHandler`.
///
/// - Returns: The instance.
@discardableResult
public func cacheResponse(using handler: CachedResponseHandler) -> Self {
$mutableState.write { mutableState in
precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
mutableState.cachedResponseHandler = handler
}
return self
}
// MARK: - Lifetime APIs
/// Sets a handler to be called when the cURL description of the request is available.
///
/// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which `handler` will be called.
/// - handler: Closure to be called when the cURL description is available.
///
/// - Returns: The instance.
@discardableResult
public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self {
$mutableState.write { mutableState in
if mutableState.requests.last != nil {
queue.async { handler(self.cURLDescription()) }
} else {
mutableState.cURLHandler = (queue, handler)
}
}
return self
}
/// Sets a handler to be called when the cURL description of the request is available.
///
/// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
///
/// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
/// `underlyingQueue` by default.
///
/// - Returns: The instance.
@discardableResult
public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
$mutableState.write { mutableState in
if mutableState.requests.last != nil {
underlyingQueue.async { handler(self.cURLDescription()) }
} else {
mutableState.cURLHandler = (underlyingQueue, handler)
}
}
return self
}
/// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
///
/// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
/// - handler: Closure to be called when a `URLRequest` is available.
///
/// - Returns: The instance.
@discardableResult
public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
$mutableState.write { state in
if let request = state.requests.last {
queue.async { handler(request) }
}
state.urlRequestHandler = (queue, handler)
}
return self
}
/// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
///
/// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
/// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
/// Additionally, this closure may be called multiple times if the instance is retried.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
/// - handler: Closure to be called when the `URLSessionTask` is available.
///
/// - Returns: The instance.
@discardableResult
public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
$mutableState.write { state in
if let task = state.tasks.last {
queue.async { handler(task) }
}
state.urlSessionTaskHandler = (queue, handler)
}
return self
}
// MARK: Cleanup
/// Adds a `finishHandler` closure to be called when the request completes.
///
/// - Parameter closure: Closure to be called when the request finishes.
func onFinish(perform finishHandler: @escaping () -> Void) {
guard !isFinished else { finishHandler(); return }
$mutableState.write { state in
state.finishHandlers.append(finishHandler)
}
}
/// Final cleanup step executed when the instance finishes response serialization.
func cleanup() {
delegate?.cleanup(after: self)
let handlers = $mutableState.finishHandlers
handlers.forEach { $0() }
$mutableState.write { state in
state.finishHandlers.removeAll()
}
}
}
// MARK: - Protocol Conformances
extension Request: Equatable {
public static func == (lhs: Request, rhs: Request) -> Bool {
lhs.id == rhs.id
}
}
extension Request: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension Request: CustomStringConvertible {
/// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
/// created, as well as the response status code, if a response has been received.
public var description: String {
guard let request = performedRequests.last ?? lastRequest,
let url = request.url,
let method = request.httpMethod else { return "No request created yet." }
let requestDescription = "\(method) \(url.absoluteString)"
return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
}
}
public extension Request {
/// cURL representation of the instance.
///
/// - Returns: The cURL equivalent of the instance.
func cURLDescription() -> String {
guard
let request = lastRequest,
let url = request.url,
let host = url.host,
let method = request.httpMethod else { return "$ curl command could not be created" }
var components = ["$ curl -v"]
components.append("-X \(method)")
if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
if
let cookieStorage = configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
components.append("-b \"\(allCookies)\"")
}
}
var headers = HTTPHeaders()
if let sessionHeaders = delegate?.sessionConfiguration.headers {
for header in sessionHeaders where header.name != "Cookie" {
headers[header.name] = header.value
}
}
for header in request.headers where header.name != "Cookie" {
headers[header.name] = header.value
}
for header in headers {
let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(header.name): \(escapedValue)\"")
}
if let httpBodyData = request.httpBody {
let httpBody = String(decoding: httpBodyData, as: UTF8.self)
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
public protocol RequestDelegate: AnyObject {
/// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
var sessionConfiguration: URLSessionConfiguration { get }
/// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
var startImmediately: Bool { get }
/// Notifies the delegate the `Request` has reached a point where it needs cleanup.
///
/// - Parameter request: The `Request` to cleanup after.
func cleanup(after request: Request)
/// Asynchronously ask the delegate whether a `Request` will be retried.
///
/// - Parameters:
/// - request: `Request` which failed.
/// - error: `Error` which produced the failure.
/// - completion: Closure taking the `RetryResult` for evaluation.
func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
/// Asynchronously retry the `Request`.
///
/// - Parameters:
/// - request: `Request` which will be retried.
/// - timeDelay: `TimeInterval` after which the retry will be triggered.
func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
}
// MARK: - Subclasses
// MARK: - DataRequest
/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
public class DataRequest: Request {
/// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
public let convertible: URLRequestConvertible
/// `Data` read from the server so far.
public var data: Data? { mutableData }
/// Protected storage for the `Data` read by the instance.
@Protected
private var mutableData: Data? = nil
/// Creates a `DataRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
convertible: URLRequestConvertible,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate)
{
self.convertible = convertible
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func reset() {
super.reset()
mutableData = nil
}
/// Called when `Data` is received by this instance.
///
/// - Note: Also calls `updateDownloadProgress`.
///
/// - Parameter data: The `Data` received.
func didReceive(data: Data) {
if self.data == nil {
mutableData = data
} else {
$mutableData.write { $0?.append(data) }
}
updateDownloadProgress()
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
let copiedRequest = request
return session.dataTask(with: copiedRequest)
}
/// Called to update the `downloadProgress` of the instance.
func updateDownloadProgress() {
let totalBytesReceived = Int64(data?.count ?? 0)
let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
downloadProgress.totalUnitCount = totalBytesExpected
downloadProgress.completedUnitCount = totalBytesReceived
downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
}
/// Validates the request, using the specified closure.
///
/// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter validation: `Validation` closure used to validate the response.
///
/// - Returns: The instance.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response, self.data)
if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
data: self.data,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
}
// MARK: - DataStreamRequest
/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
public final class DataStreamRequest: Request {
/// Closure type handling `DataStreamRequest.Stream` values.
public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
/// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
/// to stop the stream at any time.
public struct Stream<Success, Failure: Error> {
/// Latest `Event` from the stream.
public let event: Event<Success, Failure>
/// Token used to cancel the stream.
public let token: CancellationToken
/// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
public func cancel() {
token.cancel()
}
}
/// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
/// `Data` or the completion of the stream.
public enum Event<Success, Failure: Error> {
/// Output produced every time the instance receives additional `Data`. The associated value contains the
/// `Result` of processing the incoming `Data`.
case stream(Result<Success, Failure>)
/// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
/// Associated `Completion` value contains the final state.
case complete(Completion)
}
/// Value containing the state of a `DataStreamRequest` when the stream was completed.
public struct Completion {
/// Last `URLRequest` issued by the instance.
public let request: URLRequest?
/// Last `HTTPURLResponse` received by the instance.
public let response: HTTPURLResponse?
/// Last `URLSessionTaskMetrics` produced for the instance.
public let metrics: URLSessionTaskMetrics?
/// `AFError` produced for the instance, if any.
public let error: AFError?
}
/// Type used to cancel an ongoing stream.
public struct CancellationToken {
weak var request: DataStreamRequest?
init(_ request: DataStreamRequest) {
self.request = request
}
/// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
public func cancel() {
request?.cancel()
}
}
/// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
public let convertible: URLRequestConvertible
/// Whether or not the instance will be cancelled if stream parsing encounters an error.
public let automaticallyCancelOnStreamError: Bool
/// Internal mutable state specific to this type.
struct StreamMutableState {
/// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
var outputStream: OutputStream?
/// Stream closures called as `Data` is received.
var streams: [(_ data: Data) -> Void] = []
/// Number of currently executing streams. Used to ensure completions are only fired after all streams are
/// enqueued.
var numberOfExecutingStreams = 0
/// Completion calls enqueued while streams are still executing.
var enqueuedCompletionEvents: [() -> Void] = []
}
@Protected
var streamMutableState = StreamMutableState()
/// Creates a `DataStreamRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
/// by default.
/// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
/// instance.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
/// is thrown while serializing stream `Data`.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
/// targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by
/// the `Request`.
init(id: UUID = UUID(),
convertible: URLRequestConvertible,
automaticallyCancelOnStreamError: Bool,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate)
{
self.convertible = convertible
self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
let copiedRequest = request
return session.dataTask(with: copiedRequest)
}
override func finish(error: AFError? = nil) {
$streamMutableState.write { state in
state.outputStream?.close()
}
super.finish(error: error)
}
func didReceive(data: Data) {
$streamMutableState.write { state in
#if !(os(Linux) || os(Windows))
if let stream = state.outputStream {
underlyingQueue.async {
var bytes = Array(data)
stream.write(&bytes, maxLength: bytes.count)
}
}
#endif
state.numberOfExecutingStreams += state.streams.count
let localState = state
underlyingQueue.async { localState.streams.forEach { $0(data) } }
}
}
/// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
///
/// - Parameter validation: `Validation` closure used to validate the request and response.
///
/// - Returns: The `DataStreamRequest`.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response)
if case let .failure(error) = result {
self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
}
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
#if !(os(Linux) || os(Windows))
/// Produces an `InputStream` that receives the `Data` received by the instance.
///
/// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
/// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
/// not the creating session has `startRequestsImmediately` set to `true`.
///
/// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
///
/// - Returns: The `InputStream` bound to the internal `OutboundStream`.
public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
defer { resume() }
var inputStream: InputStream?
$streamMutableState.write { state in
Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
inputStream: &inputStream,
outputStream: &state.outputStream)
state.outputStream?.open()
}
return inputStream
}
#endif
func capturingError(from closure: () throws -> Void) {
do {
try closure()
} catch {
self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
cancel()
}
}
func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
stream: @escaping Handler<Success, Failure>)
{
appendResponseSerializer {
self.underlyingQueue.async {
self.responseSerializerDidComplete {
self.$streamMutableState.write { state in
guard state.numberOfExecutingStreams == 0 else {
state.enqueuedCompletionEvents.append {
self.enqueueCompletion(on: queue, stream: stream)
}
return
}
self.enqueueCompletion(on: queue, stream: stream)
}
}
}
}
}
func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
stream: @escaping Handler<Success, Failure>)
{
queue.async {
do {
let completion = Completion(request: self.request,
response: self.response,
metrics: self.metrics,
error: self.error)
try stream(.init(event: .complete(completion), token: .init(self)))
} catch {
// Ignore error, as errors on Completion can't be handled anyway.
}
}
}
}
public extension DataStreamRequest.Stream {
/// Incoming `Result` values from `Event.stream`.
var result: Result<Success, Failure>? {
guard case let .stream(result) = event else { return nil }
return result
}
/// `Success` value of the instance, if any.
var value: Success? {
guard case let .success(value) = result else { return nil }
return value
}
/// `Failure` value of the instance, if any.
var error: Failure? {
guard case let .failure(error) = result else { return nil }
return error
}
/// `Completion` value of the instance, if any.
var completion: DataStreamRequest.Completion? {
guard case let .complete(completion) = event else { return nil }
return completion
}
}
// MARK: - DownloadRequest
/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
public class DownloadRequest: Request {
/// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
/// `URL`.
public struct Options: OptionSet {
/// Specifies that intermediate directories for the destination URL should be created.
public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
/// Specifies that any previous file at the destination `URL` should be removed.
public static let removePreviousFile = Options(rawValue: 1 << 1)
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
// MARK: Destination
/// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
///
/// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
/// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
public typealias Destination = (_ temporaryURL: URL,
_ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - Parameters:
/// - directory: The search path directory. `.documentDirectory` by default.
/// - domain: The search path domain mask. `.userDomainMask` by default.
/// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
/// default.
/// - Returns: The `Destination` closure.
public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask,
options: Options = []) -> Destination
{
{ temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
return (url, options)
}
}
/// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
/// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
/// with this destination must be additionally moved if they should survive the system reclamation of temporary
/// space.
static let defaultDestination: Destination = { url, _ in
(defaultDestinationURL(url), [])
}
/// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
/// provided file name.
static let defaultDestinationURL: (URL) -> URL = { url in
let filename = "Alamofire_\(url.lastPathComponent)"
let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
return destination
}
// MARK: Downloadable
/// Type describing the source used to create the underlying `URLSessionDownloadTask`.
public enum Downloadable {
/// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
case request(URLRequestConvertible)
/// Download should be started from the associated resume `Data` value.
case resumeData(Data)
}
// MARK: Mutable State
/// Type containing all mutable state for `DownloadRequest` instances.
private struct DownloadRequestMutableState {
/// Possible resume `Data` produced when cancelling the instance.
var resumeData: Data?
/// `URL` to which `Data` is being downloaded.
var fileURL: URL?
}
/// Protected mutable state specific to `DownloadRequest`.
@Protected
private var mutableDownloadState = DownloadRequestMutableState()
/// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
/// using the `download(resumingWith data:)` API.
///
/// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
public var resumeData: Data? {
#if !(os(Linux) || os(Windows))
return $mutableDownloadState.resumeData ?? error?.downloadResumeData
#else
return $mutableDownloadState.resumeData
#endif
}
/// If the download is successful, the `URL` where the file was downloaded.
public var fileURL: URL? { $mutableDownloadState.fileURL }
// MARK: Initial State
/// `Downloadable` value used for this instance.
public let downloadable: Downloadable
/// The `Destination` to which the downloaded file is moved.
let destination: Destination
/// Creates a `DownloadRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
/// - destination: `Destination` closure used to move the downloaded file to its final location.
init(id: UUID = UUID(),
downloadable: Downloadable,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate,
destination: @escaping Destination)
{
self.downloadable = downloadable
self.destination = destination
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func reset() {
super.reset()
$mutableDownloadState.write {
$0.resumeData = nil
$0.fileURL = nil
}
}
/// Called when a download has finished.
///
/// - Parameters:
/// - task: `URLSessionTask` that finished the download.
/// - result: `Result` of the automatic move to `destination`.
func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
switch result {
case let .success(url): $mutableDownloadState.fileURL = url
case let .failure(error): self.error = error
}
}
/// Updates the `downloadProgress` using the provided values.
///
/// - Parameters:
/// - bytesWritten: Total bytes written so far.
/// - totalBytesExpectedToWrite: Total bytes expected to write.
func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
downloadProgress.totalUnitCount = totalBytesExpectedToWrite
downloadProgress.completedUnitCount += bytesWritten
downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
session.downloadTask(with: request)
}
/// Creates a `URLSessionTask` from the provided resume data.
///
/// - Parameters:
/// - data: `Data` used to resume the download.
/// - session: `URLSession` used to create the `URLSessionTask`.
///
/// - Returns: The `URLSessionTask` created.
public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
session.downloadTask(withResumeData: data)
}
/// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
///
/// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
/// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
///
/// - Returns: The instance.
@discardableResult
override public func cancel() -> Self {
cancel(producingResumeData: false)
}
/// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
/// resumed or suspended.
///
/// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
/// available.
///
/// - Returns: The instance.
@discardableResult
public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
}
/// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
/// or suspended.
///
/// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
/// property.
///
/// - Parameter completionHandler: The completion handler that is called when the download has been successfully
/// cancelled. It is not guaranteed to be called on a particular queue, so you may
/// want use an appropriate queue to perform your work.
///
/// - Returns: The instance.
@discardableResult
public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
cancel(optionallyProducingResumeData: completionHandler)
}
/// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
/// cancellation is performed without producing resume data.
///
/// - Parameter completionHandler: Optional resume data handler.
///
/// - Returns: The instance.
private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.cancelled) else { return }
mutableState.state = .cancelled
underlyingQueue.async { self.didCancel() }
guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
underlyingQueue.async { self.finish() }
return
}
if let completionHandler = completionHandler {
// Resume to ensure metrics are gathered.
task.resume()
task.cancel { resumeData in
self.$mutableDownloadState.resumeData = resumeData
self.underlyingQueue.async { self.didCancelTask(task) }
completionHandler(resumeData)
}
} else {
// Resume to ensure metrics are gathered.
task.resume()
task.cancel()
self.underlyingQueue.async { self.didCancelTask(task) }
}
}
return self
}
/// Validates the request, using the specified closure.
///
/// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter validation: `Validation` closure to validate the response.
///
/// - Returns: The instance.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response, self.fileURL)
if case let .failure(error) = result {
self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
}
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
fileURL: self.fileURL,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
}
// MARK: - UploadRequest
/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
public class UploadRequest: DataRequest {
/// Type describing the origin of the upload, whether `Data`, file, or stream.
public enum Uploadable {
/// Upload from the provided `Data` value.
case data(Data)
/// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
/// automatically removed once uploaded.
case file(URL, shouldRemove: Bool)
/// Upload from the provided `InputStream`.
case stream(InputStream)
}
// MARK: Initial State
/// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
public let upload: UploadableConvertible
/// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
/// to disk.
public let fileManager: FileManager
// MARK: Mutable State
/// `Uploadable` value used by the instance.
public var uploadable: Uploadable?
/// Creates an `UploadRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
/// encoded payloads written to disk.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
convertible: UploadConvertible,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
fileManager: FileManager,
delegate: RequestDelegate)
{
upload = convertible
self.fileManager = fileManager
super.init(id: id,
convertible: convertible,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
/// Called when the `Uploadable` value has been created from the `UploadConvertible`.
///
/// - Parameter uploadable: The `Uploadable` that was created.
func didCreateUploadable(_ uploadable: Uploadable) {
self.uploadable = uploadable
eventMonitor?.request(self, didCreateUploadable: uploadable)
}
/// Called when the `Uploadable` value could not be created.
///
/// - Parameter error: `AFError` produced by the failure.
func didFailToCreateUploadable(with error: AFError) {
self.error = error
eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
retryOrFinish(error: error)
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
guard let uploadable = uploadable else {
fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
}
switch uploadable {
case let .data(data): return session.uploadTask(with: request, from: data)
case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
case .stream: return session.uploadTask(withStreamedRequest: request)
}
}
override func reset() {
// Uploadable must be recreated on every retry.
uploadable = nil
super.reset()
}
/// Produces the `InputStream` from `uploadable`, if it can.
///
/// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
///
/// - Returns: The `InputStream`.
func inputStream() -> InputStream {
guard let uploadable = uploadable else {
fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
}
guard case let .stream(stream) = uploadable else {
fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
}
eventMonitor?.request(self, didProvideInputStream: stream)
return stream
}
override public func cleanup() {
defer { super.cleanup() }
guard
let uploadable = uploadable,
case let .file(url, shouldRemove) = uploadable,
shouldRemove
else { return }
try? fileManager.removeItem(at: url)
}
}
/// A type that can produce an `UploadRequest.Uploadable` value.
public protocol UploadableConvertible {
/// Produces an `UploadRequest.Uploadable` value from the instance.
///
/// - Returns: The `UploadRequest.Uploadable`.
/// - Throws: Any `Error` produced during creation.
func createUploadable() throws -> UploadRequest.Uploadable
}
extension UploadRequest.Uploadable: UploadableConvertible {
public func createUploadable() throws -> UploadRequest.Uploadable {
self
}
}
/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}
| [
111360,
116610,
52868,
172422,
125457,
248979,
173467,
322089,
213422,
59449,
184262,
263756,
206,
245075,
64852,
35044,
171368,
223083,
433136
] |
86b7b0fd769e322ef71248f37e708134fff52e1b | 50aa78d22fd05f68cc321bb2eafe5834ba0fa2d7 | /CoreDataSampleApp/customview.swift | bb667ac803af5d979786a091c970d78d5e2f1709 | [] | no_license | imdinesh58/Custom-Views-using-Xib..-Live-Rendering | 8cfcdace35e5e902add859bc1cfcf08bfcd8b48a | 8f92b0cbadf4a5380062adba336d28ebfe63ec10 | refs/heads/master | 2021-09-01T18:55:14.948319 | 2017-12-28T10:09:09 | 2017-12-28T10:09:09 | 115,611,026 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 980 | swift | //
// customview.swift
// CoreDataSampleApp
//
// Created by Apple-1 on 11/20/17.
// Copyright © 2017 Apple-1. All rights reserved.
//
import UIKit
@IBDesignable
class customview: UIView {
@IBOutlet weak var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
contentView = loadViewFromNib()
contentView.frame = bounds
contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(contentView)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
| [
-1
] |
5f47707623d7a945583e6a0df57c9eba163e3f74 | 4c2ffc427afa25efb41de3b91f98a02496800236 | /eds/Utilities/EDSResourceUtility.swift | 0cf5b5c1a044923875bbbbbf5461c5633f38086d | [] | no_license | hawesome512/edsForIOS | 738968c537c5c4a821859ca06fb43b2953d07f09 | f152b091f99c6e1a839ccccfb257172ffa20b465 | refs/heads/master | 2021-08-07T04:41:04.831837 | 2021-07-05T05:36:01 | 2021-07-05T05:36:01 | 219,401,576 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,136 | swift | //
// EDSResourceUtility.swift
// eds
//
// Created by 厦门士林电机有限公司 on 2020/5/5.
// Copyright © 2020 厦门士林电机有限公司. All rights reserved.
// EDS服务后台资源列表
import Foundation
import RxCocoa
class EDSResourceUtility {
static let sharedInstance = EDSResourceUtility()
private(set) var helpList = [Help]()
private(set) var successfulLoadedHelpList = BehaviorRelay<Bool>(value: false)
private init() { }
func loadHelpList() {
guard helpList.count == 0 else {
return
}
DispatchQueue.global().async {
let path = EDSConfig.servicePath + ":8443/EDSServlet/upload/help/helplist.txt"
if let list = try? String(contentsOf: URL(string: path)!) {
self.helpList = list.components(separatedBy: "\r\n").filter { !$0.isEmpty }.map { Help($0) }
self.successfulLoadedHelpList.accept(true)
print("loaded project help list")
}
}
}
func clearResource(){
helpList.removeAll()
successfulLoadedHelpList.accept(false)
}
}
| [
-1
] |
46253bb4ee3e34d1f8fb68853c57fe233d927259 | 35cd79658d488f1c62115cd9e7e9278f0a279bdb | /SearchBarController/SearchBarController/ViewController.swift | 6f5960ae00eef61c371f918365bd35628c5da60d | [] | no_license | semihozsoy/Trendyol-Homeworks | daf2ad04a6a05f684633871f420975beec79959c | e4ce168a6b442864ed638ba6c16d022680c59d4a | refs/heads/master | 2023-05-03T07:37:34.129500 | 2021-05-22T18:38:05 | 2021-05-22T18:38:05 | 358,977,773 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 289 | swift | //
// ViewController.swift
// SearchBarController
//
// Created by Semih Özsoy on 4.05.2021.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| [
262528,
385282,
398203,
275714,
436489,
317194,
361595,
384145,
158612,
393749,
409238,
319899,
370299,
155424,
262561,
324512,
345378,
396707,
436128,
187937,
333223,
391456,
354729,
242346,
125227,
356652,
384300,
273710,
380334,
370352,
372017,
381618,
262453,
383797,
354108,
397117,
266816,
351170,
262471,
323016,
326600,
349130,
359368,
421962,
437582,
340943,
330960,
265807,
199251,
324564,
257750,
377048,
354654,
362847,
354144,
359390,
165087,
425824,
398308,
399201,
437220,
155493,
253928,
155623,
318568,
350187,
352876,
56046,
349297,
124914,
349174,
351481,
381179
] |
86621ad7941e3933d4ea1b67e50fbdc74dbbfcf6 | 0c65f306924b85052ba2f1f05268c29e27b54a4b | /ui/tabs/favorites/FavoritesTab.swift | e6676504ff22a52b7ea724a1150a536743e3fa78 | [
"Apache-2.0"
] | permissive | beingRD/SpaceAidExplorer | c4268e86c3f27ceca022084ec0bd061a30697742 | c7f98bfb6f4929c8a191f77e0714e25ac28a92f5 | refs/heads/main | 2023-08-30T19:46:02.896643 | 2021-11-16T10:32:39 | 2021-11-16T10:32:39 | 428,589,897 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 681 | swift | //
// FavoritesTab.swift
// SpaceAidExplorer
//
// Created by SpaceAid group on 13/11/21.
//
import SwiftUI
struct FavoritesTab: View {
var body: some View {
if places.filter({ place in
place.isFavorite
}).count == 0 {
Text("Click the \(Image(systemName: "heart")) to add a place to the favorites")
.font(.headline)
.foregroundColor(.gray)
} else {
List {
ForEach(places, id: \.self.id) { place in
if place.isFavorite {
PlaceListItem(place: place)
}
}
}
}
}
}
| [
-1
] |
5c9c1f9582d888828aea003d7bb2145bc3baaf6b | 409a42ee70d96363badd6f179ddca15074ce0e01 | /RxDataSourcesExample/TapCellTableViewController.swift | 39c833617279c73f287e8f36ca305d79e6d8aa2e | [
"MIT"
] | permissive | hongdong/rx-sample-code | 176e084fc758a967718a9a02e392c974e965ff3b | 0109d6301739ce8f56890cc16719133ee7e8b9b4 | refs/heads/master | 2021-01-20T09:02:24.661462 | 2017-07-31T08:06:31 | 2017-07-31T08:06:31 | 90,214,022 | 1 | 0 | null | 2017-05-04T02:41:44 | 2017-05-04T02:41:44 | null | UTF-8 | Swift | false | false | 5,198 | swift | //
// TapCellTableViewController.swift
// RxDataSourcesExample
//
// Created by DianQK on 04/10/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import RxExtensions
class TapCellTableViewController: UITableViewController {
let dataSource = RxTableViewSectionedReloadDataSource<TitleSectionModel>()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = nil
tableView.delegate = nil
do {
tableView.register(HeaderView.self, forHeaderFooterViewReuseIdentifier: "HeaderView")
tableView.rx.setDelegate(self).disposed(by: rx.disposeBag)
}
do {
dataSource.configureCell = { dataSource, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicCell", for: indexPath)
cell.textLabel?.text = item
return cell
}
}
do {
let sections = Observable.just([
TitleSectionModel(model: "Section 1", items: ["Item 1", "Item 2", "Item 3"]),
TitleSectionModel(model: "Section 2", items: ["Item 1", "Item 2"]),
TitleSectionModel(model: "Section 3", items: ["Item 1", "Item 2", "Item 3", "Item 4"]),
])
sections
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: rx.disposeBag)
}
do {
// tableView.rx.modelSelected(String.self)
// .subscribe(onNext: { [unowned self] value in
// let alert = UIAlertController(title: "你点击了", message: value, preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "好", style: .default, handler: nil))
// self.showDetailViewController(alert, sender: nil)
// })
// .disposed(by: rx.disposeBag)
// tableView.rx.itemSelected
// .subscribe(onNext: { [unowned self] indexPath in
// self.tableView.deselectRow(at: indexPath, animated: true)
// })
// .disposed(by: rx.disposeBag)
// tableView.rx.itemSelected
// .map { (at: $0, animated: true) }
// .subscribe(onNext: tableView.deselectRow)
// .disposed(by: rx.disposeBag)
// tableView.rx.itemSelected
// .subscribe(onNext: { [unowned self] indexPath in
// let message = self.dataSource[indexPath]
// let title = "你点击了"
// let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "好", style: .default, handler: { _ in
// self.tableView.deselectRow(at: indexPath, animated: true)
// }))
// self.showDetailViewController(alert, sender: nil)
// })
// .disposed(by: rx.disposeBag)
tableView.rx.itemSelected
.flatMap { [unowned self] indexPath -> Observable<IndexPath> in
let message = self.dataSource[indexPath]
let title = "你点击了"
return showEnsureAlert(title: title, message: message)
.map { indexPath }
}
.map { (at: $0, animated: true) }
.subscribe(onNext: tableView.deselectRow)
.disposed(by: rx.disposeBag)
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderView") as! HeaderView
header.title = dataSource[section].model
return header
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
}
func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
func showEnsureAlert(title: String?, message: String?) -> Observable<Void> {
return Observable.create { observer in
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "好", style: .default, handler: { _ in
observer.on(.next(()))
observer.on(.completed)
}))
topViewController()?.showDetailViewController(alert, sender: nil)
return Disposables.create {
alert.dismiss(animated: true, completion: nil)
}
}
}
| [
-1
] |
9f4c6c39af38f019b7b31ddd8130f4a29e6a5557 | 0104e91a989ba5ffa5323b81b3274d3dee3c9832 | /Intervals/TimerViewController.swift | 4a6be2f1b58eb486bc44be440196b41b22d17b1d | [] | no_license | entrision/intervals-ios | 0ebe1c6f4c733278fe689870c122e44fbd782a83 | 7bc3a7d21ec5cd3cc50acb11090b4d751442b4d9 | refs/heads/master | 2020-12-25T22:31:48.426827 | 2015-12-23T20:18:19 | 2015-12-23T20:18:19 | 34,000,054 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 8,342 | swift | //
// TimerViewController.swift
// Intervals
//
// Created by Hunter Whittle on 4/29/15.
// Copyright (c) 2015 Hunter Whittle. All rights reserved.
//
import UIKit
import CoreData
class TimerViewController: BaseViewController {
@IBOutlet weak var sequenceNameLabel: UILabel!
@IBOutlet weak var intervalNameLabel: UILabel!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var pauseButton: UIButton!
var sequenceID: NSManagedObjectID = NSManagedObjectID()
var intervalArray = NSArray()
var currentIntervalIndex: Int = 0
var timer = NSTimer()
var secondsLeft: Int = 0
var toBackgroundDate = NSDate()
var timeElapsedInBackground: Int = 0
var delayed = false
var ticking = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.startButton.layer.cornerRadius = 51.0
self.pauseButton.layer.cornerRadius = 51.0
self.sequenceNameLabel.text = getSequence().name
self.intervalArray = getSequence().intervals.sortedArrayUsingDescriptors([NSSortDescriptor(key: "position", ascending: true)]) as NSArray
loadIntervals()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().idleTimerDisabled = true
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: Selector("applicationDidEnterBackground:"), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().idleTimerDisabled = false
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self)
if self.isMovingFromParentViewController() {
self.timer.invalidate()
UIApplication.sharedApplication().cancelAllLocalNotifications()
}
}
@IBAction func startButtonTapped(sender: AnyObject) {
if ticking {
startButton.setTitle("Start", forState: UIControlState.Normal)
startButton.setTitleColor(Colors.intervalsGreen, forState: UIControlState.Normal)
pauseButton.enabled = false
timer.invalidate()
UIApplication.sharedApplication().cancelAllLocalNotifications()
loadIntervals()
ticking = false
}
else {
startButton.setTitle("Stop", forState: UIControlState.Normal)
startButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
pauseButton.enabled = true
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateCountdown"), userInfo: nil, repeats: true)
ticking = true
}
}
@IBAction func pauseButtonTapped(sender: AnyObject) {
pauseTimer()
}
func updateCountdown() {
var minutes: Int
var seconds: Int
if self.secondsLeft > 0 {
if UIApplication.sharedApplication().scheduledLocalNotifications!.count < 1 {
if self.currentIntervalIndex < self.intervalArray.count - 1 && !delayed {
let upcomingInterval = intervalArray[self.currentIntervalIndex + 1] as! HWInterval
self.scheduleLocalNotification(self.secondsLeft, alertText: upcomingInterval.title)
}
}
let currentInterval = intervalArray[self.currentIntervalIndex] as! HWInterval
intervalNameLabel.text = currentInterval.title
let text = "\(intervalArray.indexOfObject(currentInterval)+1)"
progressLabel.text = "\(text) of \(intervalArray.count)"
self.secondsLeft--;
minutes = (self.secondsLeft % 3600) / 60;
seconds = (self.secondsLeft % 3600) % 60;
let formatString = delayed ? "-%01d:%02d" : "%01d:%02d"
self.timerLabel.text = String(NSString(format: formatString, minutes, seconds))
}
else {
if getSequence().delay.integerValue > 0 {
if delayed {
let currentInterval = intervalArray[currentIntervalIndex] as! HWInterval
secondsLeft = currentInterval.duration.integerValue
intervalNameLabel.textColor = Colors.intervalsLightBlue
delayed = false
}
else {
if currentIntervalIndex < intervalArray.count - 1 {
nextInterval()
secondsLeft = getSequence().delay.integerValue
intervalNameLabel.textColor = Colors.intervalsGreen
delayed = true
}
else {
finished()
}
}
}
else {
if currentIntervalIndex < intervalArray.count - 1 {
nextInterval()
}
else {
finished()
}
}
}
}
func nextInterval() {
self.currentIntervalIndex++
let nextInterval = self.intervalArray[self.currentIntervalIndex] as! HWInterval
self.intervalNameLabel.text = nextInterval.title
self.secondsLeft = nextInterval.duration.integerValue
let text = "\(self.intervalArray.indexOfObject(nextInterval)+1)"
self.progressLabel.text = "\(text) of \(self.intervalArray.count)"
}
func pauseTimer() {
startButton.setTitle("Start", forState: UIControlState.Normal)
startButton.setTitleColor(Colors.intervalsGreen, forState: UIControlState.Normal)
pauseButton.enabled = false
timer.invalidate()
UIApplication.sharedApplication().cancelAllLocalNotifications()
ticking = false
}
func finished() {
self.scheduleLocalNotification(0, alertText: "Complete")
self.timer.invalidate()
pauseButton.enabled = false
currentIntervalIndex = 0
startButton.setTitle("Reset", forState: UIControlState.Normal)
startButton.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
self.intervalNameLabel.text = "Complete"
}
func scheduleLocalNotification(timeUntil: Int, alertText: String) {
let localNotif = UILocalNotification()
let date = NSDate(timeIntervalSinceNow: NSTimeInterval(timeUntil))
localNotif.fireDate = date
localNotif.soundName = "interval_effect.m4a"
UIApplication.sharedApplication().scheduleLocalNotification(localNotif)
}
//MARK: Notifications
func applicationDidEnterBackground(notification: NSNotification) {
UIApplication.sharedApplication().cancelAllLocalNotifications()
if ticking {
pauseTimer()
}
}
func loadIntervals() {
let firstInterval = intervalArray[0] as! HWInterval
intervalNameLabel.text = firstInterval.title
let text = "\(intervalArray.indexOfObject(firstInterval)+1)"
progressLabel.text = "\(text) of \(intervalArray.count)"
let minutes = firstInterval.minutes.integerValue
let seconds = firstInterval.seconds.integerValue
let timerString = NSString(format: "%d:%02d", minutes, seconds)
timerLabel.text = String(timerString)
secondsLeft = firstInterval.duration.integerValue
}
func getSequence() -> HWSequence {
do {
let sequence = try self.managedObjectContext.existingObjectWithID(self.sequenceID) as! HWSequence
return sequence
} catch {
return HWSequence()
}
}
}
| [
-1
] |
1aa085f771310c9ccceff6aec3d2efd86d473b96 | e61673963f92faf79e72d73c54f99b9a2eb1daa5 | /ws-mobile-swift-main/PingSDK.playground/Contents.swift | efe9300a0154cdd85a9e8682ef9de069165d0740 | [] | no_license | ishupassi90/DemoTest | 7bd258af0163834646f81257bbb489373a4a6f54 | e445746935398cbd4e40b288275b3749931b34be | refs/heads/main | 2023-03-20T16:45:21.090097 | 2021-03-07T05:17:30 | 2021-03-07T05:17:30 | 345,264,556 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 158 | swift | @testable import PingSDK_Sources
log(
api: "https://httpbin.org/post",
lat: 10.0,
lon: 10.0,
callback: { data in
print(data)
}
)
| [
-1
] |
83062d9e4eb8b54b627b63c4eb721f37c4092564 | ba2e4b30ae893e26a4f261224aa70c6ccab610ce | /MadridEvent/Model/Interactors/CacheInteractors/SaveAllActivitiesInteractor.swift | fb83e41309465a11f24358fec76a3cad8f21428c | [] | no_license | manuelcolmenero/MadridEvent | 1e860fd9d0122a08fe7fc4754afe4378ef4cec28 | bf0bcb6005a46eb64deeff9fe0f410756c06f3dd | refs/heads/master | 2021-07-08T07:07:27.174706 | 2017-10-01T14:41:07 | 2017-10-01T14:41:07 | 103,853,225 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 570 | swift | //
// SaveAllActivitiesInteractor.swift
// MadridEvent
//
// Created by Manuel Colmenero Navarro on 24/9/17.
// Copyright © 2017 Manuel Colmenero Navarro. All rights reserved.
//
import Foundation
import CoreData
protocol SaveAllActivitiesInteractor {
// execute: all activities. Return on the main thread
func execute(activities: Activities, context: NSManagedObjectContext, onSuccess: @escaping activitiesClosure, onError: errorClosure)
func execute(activities: Activities, context: NSManagedObjectContext, onSuccess: @escaping activitiesClosure)
}
| [
-1
] |
470af2b7ad3d80607a7c92d99e09fa8186b8d836 | 6713351dc2cbda761384120ee40af99a1eef84bd | /LazyPomodoro/DesignSystem/CustomUIComponents/Buttons/LazyPlayButton.swift | 9bb7e19678eb4cfd537c00a6fd0184adcddf028a | [] | no_license | msaveleva/lazy-pomodoro-ios | 0c44ff27904855a34e5981dd0c6b7727e14664fc | aa25288c95f21883e779b9503413044dc203bd49 | refs/heads/develop | 2022-10-15T13:38:37.775381 | 2020-07-14T19:05:24 | 2020-07-14T19:05:24 | 173,540,130 | 4 | 2 | null | 2022-10-06T10:31:44 | 2019-03-03T06:35:48 | Swift | UTF-8 | Swift | false | false | 1,301 | swift | //
// LazyPlayButton.swift
// LazyPomodoro
//
// Created by Maria Saveleva on 12.4.2020.
// Copyright © 2020 Maria Saveleva. All rights reserved.
//
import UIKit
import SnapKit
class LazyPlayButton: UIButton {
private static let playImage = UIImage(asset: IconAsset.playButton)
private static let pauseImage = UIImage(asset: IconAsset.pauseButton)
var isPlaying: Bool = false {
didSet {
var image: UIImage?
if isPlaying {
image = LazyPlayButton.pauseImage
} else {
image = LazyPlayButton.playImage
}
setImage(image, for: .normal)
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 72, height: 72)
}
class func createLazyPlayButton() -> LazyPlayButton {
let button = LazyPlayButton.init(type: .custom)
button.setImage(LazyPlayButton.playImage, for: .normal)
return button
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.width / 2
if lp_getGradientLayer() == nil {
lp_fillWithDefaultGradient()
lp_getGradientLayer()?.cornerRadius = frame.width / 2
}
}
}
| [
-1
] |
6478b15b0b4a617e3348818fe93f4660125f4656 | f673ddc0e470a526978b9d5ab0b11533ab1fc847 | /PayPro/Source/Modules/Send/Interactor/SendInteractor.swift | 48360f81d3d82ffba52e39058c3ba7dfc1453baa | [] | no_license | webmaster-infinitapp/infiniti-iOS | 3aed6e7b7e87d1ed7a18f52cc2790dc7073c48f2 | 106b255947af585bfcebff8259d8a4b57f4d9a50 | refs/heads/master | 2022-04-02T15:17:26.448594 | 2020-02-13T17:34:07 | 2020-02-13T17:34:07 | 240,317,058 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 2,655 | swift | //
// SendInteractor.swift
// PayPro
//
// Created by jtordesillas on 05/11/2018.
// Copyright © 2018 VectorMobile. All rights reserved.
//
import Foundation
import Contacts
class SendInteractor: SendInteractorProtocol {
var dataSource: SendDataSourceProtocol?
var presenter: SendPresenterProtocol?
var contactStore = CNContactStore()
}
extension SendInteractor {
func getContacts() -> [CNContact] {
let allContacts = getAllContactsFromAddressBook()
let contactsWithPhoneNumber = filterContactsWithPhoneNumber(from: allContacts)
//dataSource... Enviar todos nuestros contactos y elaborar listas de los que tienen la App, los que no...
return contactsWithPhoneNumber
}
private func getAllContactsFromAddressBook() -> [CNContact] {
let keysToFetch = [
CNContactGivenNameKey as CNKeyDescriptor,
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor,
CNContactThumbnailImageDataKey as CNKeyDescriptor]
var results: [CNContact] = []
let contactsContainers = getContactsContainers()
results = retrieveContactsFromContainers(containers: contactsContainers, keysToFetch: keysToFetch)
return results
}
private func getContactsContainers() -> [CNContainer] {
let contactStore = CNContactStore()
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containers(matching: nil)
} catch {}
return allContainers
}
private func retrieveContactsFromContainers(containers: [CNContainer], keysToFetch: [CNKeyDescriptor]) -> [CNContact] {
var contacts: [CNContact] = []
for container in containers {
let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)
do {
let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch)
contacts.append(contentsOf: containerResults)
} catch {}
}
return contacts
}
private func filterContactsWithPhoneNumber(from contacts: [CNContact]) -> [CNContact] {
var filteredContacts: [CNContact] = []
for contact in contacts where !contact.phoneNumbers.isEmpty {
filteredContacts.append(contact)
}
return filteredContacts
}
}
| [
-1
] |
440cee49e968e8043cda99be1ed996a25012eb20 | f7d8f5e2ce439b51989c7786367a822d975fffdf | /Beatface_iOS/BeatFace/VierwControllers/Appointments/AppointmentsTableCell.swift | f8fa510ad615af6d2bd66a6e98c49cd402bb1386 | [] | no_license | beatfaceadmin/Beatface | 4d0925c90e80f0c8f23694f39b28691e4476ea60 | 49d40976849944c7d88a84a6f1c9122461685c7b | refs/heads/master | 2020-04-13T21:20:09.417095 | 2018-12-28T22:08:15 | 2018-12-28T22:08:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,325 | swift | //
// AppointmentsTableCell.swift
// BeatFace
//
// Created by Gurpreet Gulati on 11/01/18.
// Copyright © 2018 Gurpreet Gulati. All rights reserved.
//
import UIKit
class AppointmentsTableCell: UITableViewCell {
// Outlets for table in MyBfAppointmentsVc (Customer)
@IBOutlet weak var bNameLbl: UILabel!
@IBOutlet weak var bAddressLbl: UILabel!
@IBOutlet weak var bArtistImg: UIImageView!
@IBOutlet weak var bCell2View: UIView!
@IBOutlet weak var mArtistName: UILabel!
@IBOutlet weak var mTimeLbl: UILabel!
// Outlets for table in YourBfAppointmentsVc (Artist)
@IBOutlet weak var bNameLabel2: UILabel!
@IBOutlet weak var bAddressLbl2: UILabel!
@IBOutlet weak var bArtistImg2: UIImageView!
let obj = GenFuncs()
override func awakeFromNib() {
super.awakeFromNib()
self.bArtistImg?.layer.cornerRadius = (self.bArtistImg?.frame.height)! / 2
self.bArtistImg2?.layer.cornerRadius = (self.bArtistImg2?.frame.height)! / 2
self.bCell2View?.layer.cornerRadius = 10
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| [
-1
] |
21de2aea68e96ba126538f730f06afcc080b35f8 | 0a7d30523820a54271bb552deb708a10f0efb661 | /CompleteiOSAWSDeveloper/Resource/AppDelegate.swift | 3e519c9fb121d3834156b0a91248cb6a94659a07 | [] | no_license | GuilhermeDalosto/AWSAmplify-Project | 2c92724bf7c8ba048d3b4631b437e5a01f701478 | b760c899622fb2dce6907fd8d431cf19c45f2a45 | refs/heads/main | 2023-05-14T01:27:34.905987 | 2021-05-26T18:58:06 | 2021-05-26T18:58:06 | 370,796,097 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,431 | swift | //
// AppDelegate.swift
// CompleteiOSAWSDeveloper
//
// Created by Guilherme Martins Dalosto de Oliveira on 25/05/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
AmplifyInteractor.configureAmplify()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| [
393222,
393224,
393230,
393250,
344102,
393261,
393266,
213048,
385081,
376889,
393275,
376905,
254030,
286800,
368727,
180313,
368735,
180320,
376931,
286831,
368752,
286844,
417924,
262283,
286879,
286888,
377012,
327871,
180416,
377036,
180431,
377046,
377060,
327914,
205036,
393456,
393460,
336123,
418043,
336128,
385280,
262404,
180490,
368911,
262422,
377117,
262436,
336180,
262454,
393538,
262472,
344403,
213332,
65880,
262496,
418144,
262499,
213352,
262507,
246123,
262510,
213372,
385419,
393612,
262550,
262552,
385440,
385443,
385451,
262573,
393647,
385458,
262586,
344511,
262592,
360916,
369118,
328177,
328179,
328182,
328189,
328192,
164361,
410128,
393747,
254490,
188958,
385570,
33316,
197159,
377383,
352821,
188987,
418363,
369223,
385609,
385616,
352864,
369253,
262760,
352874,
352887,
254587,
377472,
148105,
377484,
352918,
98968,
344744,
361129,
385713,
434867,
164534,
336567,
328378,
164538,
328386,
352968,
344776,
418507,
352971,
352973,
385742,
385748,
361179,
369381,
361195,
418553,
344831,
336643,
344835,
344841,
361230,
336659,
418580,
418585,
434970,
369435,
418589,
262942,
418593,
336675,
328484,
418598,
418605,
336696,
361273,
328515,
336708,
328519,
336711,
361288,
328522,
426841,
197468,
254812,
361309,
361315,
361322,
328573,
377729,
369542,
361360,
222128,
345035,
345043,
386003,
386011,
386018,
386022,
435187,
328714,
361489,
386069,
336921,
386073,
336925,
345118,
377887,
345133,
345138,
386101,
361536,
189520,
345169,
156761,
361567,
148578,
345199,
386167,
361593,
410745,
361598,
214149,
345222,
386186,
337047,
345246,
214175,
337071,
337075,
345267,
386258,
328924,
66782,
222437,
386285,
328941,
386291,
345376,
345379,
410917,
345399,
378169,
369978,
337222,
337229,
337234,
263508,
402791,
345448,
271730,
378227,
271745,
181638,
353673,
181643,
181654,
230809,
181670,
181673,
181678,
181681,
181684,
181690,
361917,
181696,
337349,
181703,
271839,
329191,
361960,
116210,
337398,
337415,
329226,
419339,
419343,
419349,
419355,
370205,
419359,
419362,
394786,
370213,
419368,
419376,
206395,
214593,
419400,
419402,
353867,
419406,
419410,
345701,
394853,
222830,
370297,
403070,
353919,
403075,
345736,
198280,
403091,
345749,
345762,
419491,
345765,
419497,
419501,
370350,
419506,
419509,
337592,
419512,
419517,
337599,
419527,
419530,
419535,
272081,
394966,
419542,
419544,
181977,
345818,
419547,
419550,
419559,
337642,
419563,
337645,
370415,
337659,
337668,
362247,
395021,
362255,
116509,
345887,
378663,
345905,
354106,
354111,
247617,
354117,
329544,
345930,
370509,
354130,
247637,
337750,
370519,
313180,
345964,
345967,
345970,
345974,
403320,
354172,
247691,
337808,
247700,
436126,
436132,
337844,
346057,
346063,
329697,
354277,
190439,
247789,
354313,
436289,
378954,
395339,
338004,
100453,
329832,
329855,
329885,
346272,
362660,
100524,
387249,
379066,
387260,
256191,
395466,
346316,
411861,
411864,
411868,
411873,
379107,
411876,
387301,
346343,
338152,
387306,
387312,
436473,
321786,
379134,
411903,
411916,
379152,
395538,
387349,
338199,
387352,
182558,
338211,
248111,
362822,
436555,
190796,
379233,
354673,
248186,
420236,
379278,
272786,
354727,
338352,
338381,
330189,
338386,
256472,
338403,
338409,
248308,
199164,
330252,
199186,
420376,
330267,
354855,
10828,
199249,
346721,
174695,
248425,
191084,
338543,
191092,
346742,
330383,
354974,
150183,
174774,
248504,
174777,
223934,
355024,
273108,
355028,
264918,
183005,
256734,
436962,
338660,
338664,
264941,
207619,
338700,
256786,
199452,
363293,
396066,
346916,
396069,
215853,
355122,
355131,
355140,
355143,
338763,
355150,
330580,
355166,
265055,
265058,
355175,
387944,
355179,
330610,
330642,
355218,
412599,
207808,
379848,
396245,
330710,
248792,
248798,
347105,
257008,
183282,
265207,
330748,
265214,
330760,
330768,
248862,
396328,
158761,
396336,
199728,
330800,
396339,
339001,
388154,
388161,
347205,
248904,
330826,
248914,
339036,
412764,
257120,
265320,
248951,
420984,
330889,
339097,
248985,
44197,
380070,
339112,
249014,
330965,
265436,
388319,
388347,
175375,
159005,
175396,
208166,
273708,
372015,
347441,
372018,
199988,
44342,
175415,
396600,
437566,
175423,
437570,
437575,
437583,
331088,
437587,
331093,
396633,
175450,
437595,
175457,
208227,
175460,
175463,
437620,
175477,
249208,
175483,
175486,
249214,
175489,
249218,
249224,
249227,
249234,
175513,
175516,
396705,
175522,
355748,
380332,
396722,
208311,
388542,
372163,
216517,
380360,
216522,
339404,
372176,
208337,
339412,
413141,
339417,
249308,
339420,
249312,
339424,
339428,
339434,
249328,
69113,
372228,
208398,
380432,
175635,
265778,
265795,
396872,
265805,
224853,
224857,
257633,
224870,
372327,
257646,
372337,
224884,
224887,
224890,
224894,
224897,
372353,
216707,
126596,
224904,
11918,
159374,
224913,
126610,
224916,
224919,
126616,
208538,
224922,
224926,
224929,
224932,
224936,
257704,
224942,
257712,
224947,
257716,
257720,
257724,
257732,
224969,
339662,
257747,
224981,
224986,
224993,
257761,
224999,
339695,
225012,
257787,
225020,
339710,
257790,
225025,
257794,
339721,
257801,
257804,
225038,
257807,
372499,
167700,
225043,
225048,
257819,
225053,
184094,
225058,
257833,
225066,
257836,
413484,
225070,
225073,
372532,
257845,
397112,
225082,
397115,
225087,
225092,
257868,
257871,
225103,
397139,
225108,
225112,
257883,
257886,
225119,
225127,
257896,
274280,
257901,
225137,
257908,
225141,
257912,
257916,
225148,
257920,
225155,
339844,
225165,
397200,
225170,
380822,
225175,
225180,
118691,
184244,
372664,
372702,
372706,
356335,
380918,
405533,
430129,
266294,
266297,
421960,
356439,
421990,
266350,
266362,
381068,
225423,
250002,
250004,
225429,
356506,
225437,
135327,
225441,
438433,
225444,
438436,
225447,
438440,
225450,
258222,
225455,
430256,
225458,
225461,
225466,
389307,
225470,
381120,
372929,
430274,
225475,
389320,
225484,
225487,
225490,
266453,
225493,
225496,
225499,
225502,
225505,
356578,
225510,
217318,
225514,
225518,
372976,
381176,
397571,
389380,
61722,
356637,
356640,
356643,
356646,
266536,
356649,
356655,
332080,
340275,
356660,
397622,
332090,
225597,
332097,
201028,
348488,
348502,
250199,
250202,
332125,
250210,
348522,
348525,
348527,
332152,
250238,
389502,
356740,
373145,
340379,
389550,
324030,
266687,
160234,
127471,
340472,
324094,
266754,
324111,
340500,
381481,
356907,
324142,
356916,
324149,
324155,
348733,
324164,
356934,
348743,
381512,
324173,
324176,
389723,
332380,
373343,
381545,
340627,
373398,
184982,
258721,
332453,
332459,
389805,
332463,
381617,
332471,
332483,
332486,
373449,
357069,
332493,
357073,
332511,
332520,
340718,
332533,
348924,
373510,
389926,
152370,
340789,
348982,
398139,
127814,
357201,
357206,
389978,
357211,
430939,
357214,
201579,
201582,
349040,
340849,
430965,
381813,
324472,
398201,
119674,
324475,
340858,
340861,
324478,
430972,
324481,
373634,
398211,
324484,
324487,
381833,
324492,
324495,
324498,
430995,
324501,
324510,
422816,
324513,
398245,
324524,
340909,
324533,
324538,
324541,
398279,
340939,
340941,
209873,
340957,
431072,
398306,
340963,
209895,
201711,
349172,
381946,
349180,
439294,
431106,
209943,
250914,
357410,
185380,
357418,
209965,
209971,
209975,
209979,
209987,
209990,
341071,
349267,
250967,
210010,
341091,
210025,
210030,
210036,
210039,
349308,
210044,
160895,
152703,
349311,
210052,
210055,
349319,
210067,
210077,
210080,
251044,
210084,
185511,
210095,
210098,
210107,
210115,
332997,
210127,
333009,
210131,
333014,
210138,
210143,
218354,
218360,
251128,
275706,
275712,
275715,
275721,
349459,
333078,
251160,
349484,
349491,
415033,
357708,
210260,
259421,
333154,
251235,
374117,
333162,
234866,
390516,
333175,
357755,
136590,
112020,
349590,
357792,
259515,
415166,
415185,
366034,
366038,
415191,
415193,
415196,
415199,
423392,
333284,
415207,
366056,
366061,
415216,
210420,
415224,
423423,
415257,
415263,
366117,
415270,
144939,
415278,
415281,
415285,
210487,
415290,
415293,
349761,
415300,
333386,
366172,
333413,
423528,
423532,
210544,
415353,
333439,
415361,
267909,
153227,
333498,
210631,
333511,
259788,
358099,
153302,
333534,
366311,
431851,
366318,
210672,
366321,
366325,
210695,
268041,
210698,
366348,
210706,
399128,
210719,
358191,
210739,
366387,
399159,
358200,
325440,
366401,
341829,
325446,
46920,
341834,
341838,
341843,
415573,
358234,
341851,
350045,
399199,
259938,
399206,
268143,
358255,
399215,
358259,
341876,
333689,
243579,
325504,
333698,
333708,
333724,
382890,
350146,
358371,
350189,
350193,
350202,
350206,
350213,
268298,
350224,
350231,
333850,
350237,
350240,
350244,
350248,
178218,
350251,
350256,
350259,
350271,
243781,
350285,
374864,
342111,
374902,
432271,
334011,
260289,
260298,
350410,
350416,
350422,
211160,
350425,
268507,
334045,
350445,
375026,
358644,
350458,
350461,
350464,
350467,
350475,
375053,
268559,
350480,
432405,
350486,
325914,
350490,
325917,
350493,
350498,
350504,
358700,
350509,
391468,
358704,
358713,
358716,
383306,
334161,
383321,
383330,
383333,
391530,
383341,
334203,
268668,
194941,
391563,
366990,
416157,
268701,
342430,
375208,
375216,
334262,
334275,
326084,
358856,
195039,
334304,
334311,
375277,
334321,
350723,
186897,
334358,
342550,
342554,
334363,
358941,
350761,
252461,
383536,
358961,
334384,
334394,
252482,
219718,
334407,
350822,
375400,
334465,
334468,
162445,
326290,
342679,
342683,
260766,
342710,
244409,
260797,
260801,
350917,
391894,
154328,
416473,
64230,
342766,
375535,
203506,
342776,
391937,
391948,
375568,
326416,
375571,
162591,
326441,
326451,
326454,
244540,
326460,
375612,
326467,
244551,
326473,
326477,
326485,
416597,
326490,
326502,
375656,
433000,
326507,
326510,
211825,
211831,
351097,
392060,
359295,
351104,
342915,
236430,
342930,
252822,
392091,
400285,
252836,
359334,
400306,
351168,
359361,
359366,
326598,
359382,
359388,
383967,
343015,
359407,
261108,
244726,
261111,
383997,
261129,
359451,
261147,
211998,
261153,
261159,
359470,
359476,
343131,
384098,
384101,
367723,
384107,
187502,
384114,
343154,
212094,
351364,
384135,
384139,
384143,
384160,
384168,
367794,
384181,
367800,
351423,
384191,
384198,
326855,
244937,
253130,
343244,
146642,
359649,
343270,
351466,
351479,
384249,
343306,
261389,
359694,
253200,
261393,
384275,
245020,
245029,
171302,
351534,
376110,
245040,
384314,
425276,
384323,
212291,
343365,
212303,
367965,
343393,
343398,
367980,
425328,
343409,
154999,
253303,
343417,
327034,
245127,
384397,
245136,
245142,
245145,
343450,
245148,
245151,
245154,
245157,
245162,
327084,
359865,
384443,
146876,
327107,
384453,
327110,
327115,
327117,
359886,
359890,
343507,
368092,
343534,
343539,
368119,
343544,
368122,
409091,
359947,
359955,
359983,
343630,
327275,
245357,
138864,
155254,
155273,
368288,
425638,
425649,
155322,
425662,
155327,
155351,
155354,
212699,
155363,
245475,
245483,
155371,
409335,
155393,
155403,
155422,
360223,
155438,
155442,
155447,
155461,
360261,
376663,
155482,
261981,
425822,
376671,
155487,
155490,
155491,
327531,
261996,
376685,
261999,
262002,
327539,
425845,
262005,
147317,
262008,
262011,
155516,
155521,
155525,
360326,
376714,
155531,
262027,
262030,
262033,
262036,
262039,
262042,
155549,
262045,
262048,
262051,
327589,
155559,
155562,
155565,
393150,
393169,
384977,
155611,
155619,
253923,
155621,
253926,
204784,
393203,
360438,
253943,
393206,
393212,
155646
] |
48a239aa38f47c5e19f61565ec0851f549cd59be | b356742b399cc171ab3ef971c0a69915712880be | /ClientSide/Worker/Worker/AppDelegate.swift | f1713136b9da8aa53aa3b5cda05c255a91c2f449 | [] | no_license | tonybragin/VacationHelper | 7fcf5d45a88b32d7b9ac5965e5a35b1db5c30b24 | 2562d9d1b969518f1b8666607b8f3783cd56a450 | refs/heads/master | 2020-03-21T19:51:38.416591 | 2018-06-28T06:07:24 | 2018-06-28T06:07:24 | 138,973,820 | 2 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,584 | swift | //
// AppDelegate.swift
// Worker
//
// Created by TONY on 19/02/2018.
// Copyright © 2018 TONY COMPANY. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Worker")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| [
294405,
243717,
163848,
313353,
320008,
320014,
313360,
288275,
322580,
289300,
290326,
329747,
139803,
103964,
322080,
306721,
229408,
296483,
322083,
229411,
306726,
309287,
308266,
292907,
217132,
322092,
40495,
316465,
288306,
322102,
324663,
164408,
308281,
322109,
286783,
315457,
313409,
313413,
349765,
320582,
309832,
288329,
242250,
215117,
196177,
241746,
344661,
231000,
212571,
300124,
287323,
309342,
325220,
306790,
310378,
296043,
311914,
152685,
334446,
239726,
307310,
322666,
292466,
314995,
307315,
314487,
291450,
314491,
222846,
288383,
318599,
312970,
239252,
311444,
294038,
311449,
323739,
300194,
298662,
233638,
233644,
313005,
286896,
295600,
300208,
286389,
294070,
125111,
234677,
309439,
235200,
284352,
296641,
242371,
302787,
284360,
321228,
319181,
298709,
284374,
189654,
182486,
320730,
241371,
311516,
357083,
179420,
317665,
298210,
311525,
288489,
290025,
229098,
307436,
304365,
323310,
125167,
313073,
286455,
306424,
322299,
319228,
302332,
319231,
184576,
309505,
241410,
311043,
366339,
309509,
318728,
125194,
234763,
321806,
125201,
296218,
313116,
237858,
326434,
295716,
313125,
300836,
289577,
125226,
133421,
317233,
241971,
316726,
318264,
201530,
313660,
159549,
287038,
292159,
218943,
182079,
288578,
301893,
234828,
292172,
300882,
379218,
321364,
243032,
201051,
230748,
258397,
294238,
298844,
291169,
199020,
293741,
266606,
319342,
292212,
313205,
244598,
316788,
124796,
196988,
305022,
317821,
243072,
314241,
303999,
313215,
242050,
325509,
293767,
316300,
306576,
322448,
308114,
319900,
298910,
313250,
308132,
316327,
306605,
316334,
324015,
324017,
200625,
300979,
316339,
322998,
67000,
316345,
296888,
300987,
319932,
310718,
292288,
317888,
323520,
312772,
298950,
306632,
310733,
289744,
310740,
235994,
286174,
315359,
240098,
323555,
236008,
319465,
248299,
311789,
326640,
188913,
203761,
320498,
314357,
288246,
309243,
300540,
310782
] |
0a3b404928901406d225f6efba1e9b0e1764d443 | 7906821b83aec6e543c02e7adc142487ea8357ea | /Atter/Shared/Delegates/AppDelegate.swift | 91d3d4740252cbf1d5884f3a8d7f3e795c785751 | [] | no_license | onion-ninjas/atter-ios | 53957857461f93901bc98ac3e649063cc7c9d609 | 227e89442867baa61d2a0499e1b312e51b467fa7 | refs/heads/master | 2020-06-22T14:23:27.027584 | 2019-07-31T10:48:04 | 2019-07-31T10:48:04 | 197,729,264 | 2 | 0 | null | 2019-07-30T14:23:58 | 2019-07-19T07:59:31 | Swift | UTF-8 | Swift | false | false | 656 | swift | //
// AppDelegate.swift
// Atter
//
// Created by Patryk Mieszała on 19/07/2019.
// Copyright © 2019 Patryk Mieszała. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var rootRouter: RootRouter?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let window = UIWindow()
window.makeKeyAndVisible()
let router = RootRouter(window: window)
router.navigateToTabBar()
self.rootRouter = router
return true
}
}
| [
-1
] |
f94968d3cbbbf5772c1987a92de450a63e84a4ee | 8c0f0d6db8ea0b2f2fd3a849c0853a56cd9b8fd9 | /BouncyButt/GameScene.swift | 5a37eab3b588b6d8602985d737097c19ec88e635 | [] | no_license | dbloo/Bouncy-Butt | e3adfa141379847f5fef6fc258454dcce6be64ec | 2d80746bbbec2cf78d774ea3983c6bc66386ff37 | refs/heads/master | 2021-01-19T13:06:03.447365 | 2017-08-19T20:49:46 | 2017-08-19T20:49:46 | 100,820,492 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 25,693 | swift | //
// GameScene.swift
// BouncyButt
//
// Created by Dominic Bloomfield on 4/12/17.
// Copyright © 2017 Dominic Bloomfield. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var player: SKSpriteNode!// player
var pillarArray = ["pillar1"]// an array of pillar.png representing pillar node
var badPillarArray = ["badpillar1"]
var backgroundArray = ["background"]
var foregroundArray = ["foreground"]
var pillar : SKSpriteNode!
var dummyPillar: SKSpriteNode!
var badPillar : SKSpriteNode!
var background: SKSpriteNode!
var foreground: SKSpriteNode!
var ground: SKSpriteNode!
var pillarRestitution = 0.7
var backgroundFrame: SKSpriteNode!
var backgroundTimer: Timer!
var frameCollisionBox: SKSpriteNode!
var foregroundTimer: Timer!
var pauseButton: SKSpriteNode!
var timerIsRunning: Bool = false
var resumeButton: SKSpriteNode!
var tutorialScreen: SKSpriteNode!
var pillarTimer: Timer!// timer for interval between pillars
var badPillarTimer: Timer!
var interval: TimeInterval!
var time : GKRandomDistribution!
var duration: Double = 4
var durationTimer: Timer!
var gameOver: Bool = false
var scoreLabel : SKLabelNode!
public var score : Int = 0{
didSet {
scoreLabel.text = "\(score)"
}
}
var pausedTimerLabel: SKLabelNode!
var pausedTimer: Timer!
var timer : Int = 3
var pausedLabel: SKLabelNode!
var playerBitMask : UInt32 = 0b001
var pillarBitMask : UInt32 = 0b0010
var badPillarBitMask : UInt32 = 0b00100
var frameCollisionBitMask: UInt32 = 0b001000
let swipeUP = UISwipeGestureRecognizer()
var swipeCounter : Int = 4
var playerDidCollideWithPillar = false
var fartAnimation : SKTextureAtlas!
var fartTextureArray: [SKTexture]!
var tapAnimation : SKTextureAtlas!
var tapTextureArray : [SKTexture]!
var tapNode : SKSpriteNode!
var playerAnimation : SKTextureAtlas!
var playerTextureArray: [SKTexture]!
var pillarAnimation: SKTextureAtlas!
var pillarTextureArray: [SKTexture]!
var badpillarAnimation: SKTextureAtlas!
var badpillarTextureArray: [SKTexture]!
var canSpawn = false
var tutorialButton: SKSpriteNode!
var getReadyLabel: SKLabelNode!
var getreadylabelTimer: Timer!
var animArray = [SKAction]()
var transitionNode: SKSpriteNode!
var hasCollided = false
let flapSound = SKAction.playSoundFileNamed("hatflap.wav", waitForCompletion: false)
let collisionSound = SKAction.playSoundFileNamed("pillarHit.wav", waitForCompletion: false)
let gameOverSound = SKAction.playSoundFileNamed("endGameMusic.wav", waitForCompletion: false)
// main method
override func didMove(to view: SKView){
self.scaleMode = .aspectFill
backgroundFrame = self.childNode(withName: "frame") as! SKSpriteNode
pauseButton = self.childNode(withName: "pauseButton") as! SKSpriteNode
getReadyLabel = self.childNode(withName: "getReadyLabel") as! SKLabelNode
getReadyLabel.run(animateGetReadyLabel())
addBackground()
transitionNode = SKSpriteNode(color: UIColor.white, size: self.frame.size)
transitionNode.zPosition = 6
self.addChild(transitionNode)
transitionNode.run(SKAction.fadeOut(withDuration: 0.3))
self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.81)
if(self.view?.isPaused == true){isPaused = true}
self.isUserInteractionEnabled = true
swipeUP.addTarget(self, action: #selector(GameScene.fart))
swipeUP.direction = .up
self.view?.addGestureRecognizer(swipeUP)
dummyPillar = SKSpriteNode(imageNamed: "pillar1")
dummyPillar.physicsBody = SKPhysicsBody(rectangleOf: dummyPillar.size )
dummyPillar.physicsBody?.isDynamic = false;
dummyPillar.physicsBody?.categoryBitMask = pillarBitMask
dummyPillar.physicsBody?.collisionBitMask = playerBitMask
dummyPillar.physicsBody?.contactTestBitMask = playerBitMask
dummyPillar.zPosition = ground.zPosition + 1
dummyPillar.physicsBody?.restitution = CGFloat(pillarRestitution)
dummyPillar.position = CGPoint(x: 0, y: (ground.position.y + (dummyPillar.size.height - 40)))
self.addChild(dummyPillar)
pillarAnimation = SKTextureAtlas(named: "pillars")
pillarTextureArray = [SKTexture]()
badpillarAnimation = SKTextureAtlas(named: "badpillars")
badpillarTextureArray = [SKTexture]()
for i in 1...pillarAnimation.textureNames.count{
pillarTextureArray.append(SKTexture(imageNamed: "pillar\(i)"))
badpillarTextureArray.append(SKTexture(imageNamed: "badpillar\(i)"))
}
dummyPillar.texture = SKTexture(imageNamed: pillarAnimation.textureNames[0])
dummyPillar.run(SKAction.repeatForever(SKAction.animate(with: pillarTextureArray, timePerFrame: 0.6)))
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
physicsWorld.contactDelegate = self
player = self.childNode(withName: "player") as! SKSpriteNode
player.position = CGPoint(x: 0 , y: self.frame.size.width / 2)
player.physicsBody = SKPhysicsBody(circleOfRadius: (player.size.width / 2) + 5)
player.physicsBody?.isDynamic = true ;
player.physicsBody?.mass = 6
player.physicsBody?.categoryBitMask = playerBitMask;
player.physicsBody?.collisionBitMask = pillarBitMask
player.physicsBody?.contactTestBitMask = pillarBitMask
player.physicsBody?.usesPreciseCollisionDetection = true;
player.physicsBody?.allowsRotation = false
player.physicsBody?.affectedByGravity = false
player.constraints = [SKConstraint.positionX(SKRange(constantValue: 0))]
frameCollisionBox = self.childNode(withName: "frameCollisionBox") as! SKSpriteNode
frameCollisionBox.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: frameCollisionBox.size.width, height: frameCollisionBox.size.height + 45))
frameCollisionBox.physicsBody?.isDynamic = false
frameCollisionBox.physicsBody?.affectedByGravity = false
frameCollisionBox.physicsBody?.categoryBitMask = frameCollisionBitMask
frameCollisionBox.physicsBody?.contactTestBitMask = playerBitMask
frameCollisionBox.physicsBody?.collisionBitMask = playerBitMask
frameCollisionBox.zPosition = player.zPosition
tapAnimation = SKTextureAtlas(named: "tapToBegin")
tapTextureArray = [SKTexture]()
for i in 1...tapAnimation.textureNames.count {
tapTextureArray.append(SKTexture(imageNamed: "tap\(i)"))
}
if self.view?.isPaused == true {
resumeGame()
}
tapNode = self.childNode(withName: "tap1") as! SKSpriteNode!
tapNode.texture = SKTexture(imageNamed: tapAnimation.textureNames[0])
tapNode.position = CGPoint(x: 0 , y: 0)
tapNode.zPosition = player.zPosition
tapNode.run(SKAction.repeatForever(SKAction.animate(with: tapTextureArray, timePerFrame: 0.6)))
scoreLabel = SKLabelNode(text: "0")
scoreLabel = SKLabelNode(fontNamed: "Fipps-Regular")
scoreLabel.fontSize = 32
scoreLabel.fontColor = SKColor.black
scoreLabel.position = CGPoint(x: 0.5, y: player.position.y + 40)
scoreLabel.zPosition = 1
score = 0
self.addChild(scoreLabel)
pillarTimer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(addPillar), userInfo: nil, repeats: true)
if score > 0 {
pillarTimer.fire()
}
durationTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector (decrementDuration), userInfo: nil, repeats: true)
durationTimer.fire()
if(self.view?.isPaused == true){
resumeGame()
}
if(UIApplication.isFirstLaunch()){
}
}
func animateGetReadyLabel() -> SKAction{
let blinkAction = SKAction.sequence([SKAction.fadeOut(withDuration: 0.3), SKAction.fadeIn(withDuration: 0.3)])
return SKAction.repeatForever(blinkAction)
}
func pauseGame(){
resumeButton = SKSpriteNode(imageNamed: "resumeButton(gba)")
resumeButton.position = CGPoint(x: pauseButton.position.x , y: pauseButton.position.y)
resumeButton.zPosition = pauseButton.zPosition + 1
resumeButton.size = pauseButton.size
resumeButton.name = "resumeButton"
pausedLabel = SKLabelNode(fontNamed: "Fipps-Regular")
pausedLabel.text = "Paused"
pausedLabel.fontColor = SKColor.black
pausedLabel.position = CGPoint(x: 0, y: 0)
pausedLabel.zPosition = resumeButton.zPosition
pausedLabel.fontSize = 32
pausedLabel.name = "pausedLabel"
self.addChild(pausedLabel)
self.addChild(resumeButton)
durationTimer.invalidate()
pauseButton.removeFromParent()
let pauseAction = SKAction.run {
self.timerIsRunning = true
self.physicsWorld.speed = 0
self.player.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
self.isPaused = true
}
self.run(pauseAction)
}
func pauseTimer(){
timer -= 1
pausedTimerLabel.text = "\(timer)"
timerIsRunning = pausedTimer.isValid
if timer == 0{
pausedTimerLabel.removeFromParent()
self.physicsWorld.speed = 1
self.player.physicsBody?.velocity = CGVector(dx: 0, dy: -5)
self.addChild(pauseButton)
timer = 3
pausedTimer.invalidate()
timerIsRunning = false
isPaused = false
pausedTimerLabel.removeFromParent()
}
}
func resumeGame(){
pausedTimerLabel = SKLabelNode(text: "3")
pausedTimerLabel.fontName = "Fipps-Regular"
pausedTimerLabel.fontSize = 32
pausedTimerLabel.position = CGPoint(x: 0.5, y: 0.5)
pausedTimerLabel.fontColor = SKColor.black
pausedTimerLabel.name = "pausedTimerLabel"
pausedTimerLabel.zPosition = 5
self.addChild(pausedTimerLabel)
pausedTimer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector (pauseTimer), userInfo: nil, repeats: true)
resumeButton.removeFromParent()
pausedLabel.removeFromParent()
durationTimer.fire()
}
// function to add pillars to scene based on random time interval
func addPillar(){
pillarRestitution = 0.7
pillar = SKSpriteNode(imageNamed: pillarArray[0])
badPillar = SKSpriteNode(imageNamed: badPillarArray[0])
var animArray = [SKAction]()
pillar = SKSpriteNode(imageNamed: "pillar1")
pillar.physicsBody = SKPhysicsBody(rectangleOf: pillar.size )
pillar.physicsBody?.isDynamic = false;
pillar.physicsBody?.categoryBitMask = pillarBitMask
pillar.physicsBody?.collisionBitMask = playerBitMask
pillar.physicsBody?.contactTestBitMask = playerBitMask
pillar.zPosition = ground.zPosition + 1
pillar.physicsBody?.restitution = CGFloat(pillarRestitution)
badPillar = SKSpriteNode(imageNamed: "badpillar1")
badPillar.physicsBody = SKPhysicsBody(rectangleOf: badPillar.size)
badPillar.physicsBody?.isDynamic = false;
badPillar.physicsBody?.categoryBitMask = badPillarBitMask
badPillar.physicsBody?.collisionBitMask = playerBitMask
badPillar.physicsBody?.contactTestBitMask = playerBitMask
badPillar.zPosition = ground.zPosition + 1
pillar.zPosition = player.zPosition
pillarAnimation = SKTextureAtlas(named: "pillars")
pillarTextureArray = [SKTexture]()
badpillarAnimation = SKTextureAtlas(named: "badpillars")
badpillarTextureArray = [SKTexture]()
for i in 1...pillarAnimation.textureNames.count{
pillarTextureArray.append(SKTexture(imageNamed: "pillar\(i)"))
badpillarTextureArray.append(SKTexture(imageNamed: "badpillar\(i)"))
}
pillar.texture = SKTexture(imageNamed: pillarAnimation.textureNames[0])
pillar.run(SKAction.repeatForever(SKAction.animate(with: pillarTextureArray, timePerFrame: 0.6)))
badPillar.texture = SKTexture(imageNamed: pillarAnimation.textureNames[0])
badPillar.run(SKAction.repeatForever(SKAction.animate(with: badpillarTextureArray, timePerFrame: 0.6)))
pillar.position = CGPoint(x: backgroundFrame.size.width, y: (ground.position.y + (pillar.size.height - 40)))
// set pillar physics body
badPillar.position = CGPoint(x: backgroundFrame.size.width - pillar.size.width, y: (pillar.position.y))
let max = Double(UInt32.max)
let spawnRate = ((Double(arc4random()) / max) + 0.4) * 0.5
var upperBounds = 0.65
var lowerBounds = 0.6
if((spawnRate > lowerBounds && spawnRate < upperBounds)){
if timerIsRunning == false && isPaused == false && canSpawn == true{
pillarArray.insert(contentsOf: badPillarArray, at: 0)
self.addChild(badPillar)
canSpawn = false
SKAction.run {
upperBounds += 0.05
lowerBounds -= 0.05
if upperBounds == 0.95 {
upperBounds = 0.95
}else if lowerBounds == 0.3 {
lowerBounds = 0.3
}
}
}else if isPaused == true{
animArray.append(SKAction.stop())
}
} else if(!(spawnRate > upperBounds && spawnRate < lowerBounds)){
if timerIsRunning == false && isPaused == false {
self.addChild(pillar)
canSpawn = true
}
}
for i in 1...pillarAnimation.textureNames.count{
pillarTextureArray.append(SKTexture(imageNamed: "pillar\(i)"))
badpillarTextureArray.append(SKTexture(imageNamed: "badpillar\(i)"))
}
pillar.texture = SKTexture(imageNamed: pillarAnimation.textureNames[0])
pillar.run(SKAction.repeatForever(SKAction.animate(with: pillarTextureArray, timePerFrame: 0.6)))
badPillar.texture = SKTexture(imageNamed: pillarAnimation.textureNames[0])
badPillar.run(SKAction.repeatForever(SKAction.animate(with: badpillarTextureArray, timePerFrame: 0.6)))
let randomInterval = ((Double(arc4random()) / max) + 0.5) * 0.2
if (score > 0 ){
animArray.append(SKAction.wait(forDuration: TimeInterval(Double(randomInterval))))
}
animArray.append(SKAction.move(to: CGPoint(x: -self.frame.size.width, y: pillar.position.y), duration: Double(duration)))
animArray.append(SKAction.removeFromParent())
pillar.run(SKAction.sequence(animArray), completion: endGame)
badPillar.run(SKAction.sequence(animArray))
}
func decrementDuration() {
duration -= 0.2
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.isPaused == false{
dropPlayer()
tapNode.removeFromParent()
getReadyLabel.run(SKAction.fadeOut(withDuration: 0.5), completion: getReadyLabel.removeFromParent)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let location = touch?.location(in: self){
let nodeArray = self.nodes(at: location)
if(nodeArray.first?.name == "pauseButton"){
pauseGame()
}
if(nodeArray.first?.name == "resumeButton"){
resumeGame()
}
}
}
func runPlayerAnimation(){
playerAnimation = SKTextureAtlas(named: "playerjiggle")
playerTextureArray = [SKTexture]()
for i in 1...playerAnimation.textureNames.count {
playerTextureArray.append(SKTexture(imageNamed: "player\(i)"))
}
player.texture = SKTexture(imageNamed: playerAnimation.textureNames[0])
player.run(SKAction.animate(with: playerTextureArray, timePerFrame: 0.2), completion: {
self.player.texture = SKTexture(imageNamed: "player1")
})
}
func fart(){
if(swipeCounter < 4){
player.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 2500))
swipeCounter += 1
run(flapSound)
self.player.texture = SKTexture(imageNamed: "player1")
}else if(swipeCounter == 4){
}
}
func dropPlayer(){
pillarRestitution -= 0.5
player.physicsBody?.affectedByGravity = true
player.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: -6000))
player.texture = SKTexture(imageNamed: "player2")
}
func didBegin(_ contact: SKPhysicsContact){
var firstBody : SKPhysicsBody
var secondBody: SKPhysicsBody
if(contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
firstBody = contact.bodyA
secondBody = contact.bodyB
}else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if((firstBody.categoryBitMask & playerBitMask) != 0 && (secondBody.categoryBitMask & pillarBitMask) != 0){
run(collisionSound)
playerDidCollideWithPillar(player: firstBody.node as! SKSpriteNode, pillar: secondBody.node as! SKSpriteNode)
score+=1
swipeCounter = 0
}else if ((firstBody.categoryBitMask & playerBitMask) != 0 && (secondBody.categoryBitMask & badPillarBitMask) != 0){
playerDidCollideWithBadPillar(player: firstBody.node as! SKSpriteNode, badPillar: secondBody.node as! SKSpriteNode)
}else if ((firstBody.categoryBitMask & playerBitMask) != 0 && (secondBody.categoryBitMask & frameCollisionBitMask) != 0){
playerDidCollideWithBottomOfScreen(player: firstBody.node as! SKSpriteNode, frame: secondBody.node as! SKSpriteNode)
}else {
}
}
func playerDidCollideWithPillar(player: SKSpriteNode, pillar: SKSpriteNode){
hasCollided = true
player.texture = SKTexture(imageNamed: "player1")
if score == 0 {
pillarTimer.fire()
}
pillar.physicsBody?.collisionBitMask = 0
pillar.physicsBody?.contactTestBitMask = 0
pillar.physicsBody?.categoryBitMask = 0
pillar.physicsBody = nil
let xConstraint = SKConstraint.positionX(SKRange(constantValue: pillar.position.x))
pillar.constraints = [xConstraint]
pillar.run(SKAction.moveTo(y: -self.frame.size.height , duration: 0.6), completion: pillar.removeFromParent)
}
func playerDidCollideWithBadPillar(player: SKSpriteNode, badPillar: SKSpriteNode){
endGame()
}
func playerDidCollideWithBottomOfScreen(player: SKSpriteNode, frame: SKSpriteNode){
endGame()
}
func endGame(){
let endGameScene = SKScene(fileNamed: "EndGameScene" ) as! EndGameScene
endGameScene.score = score
if (score > endGameScene.highestscore){
endGameScene.saveHighscore()
}
endGameScene.scaleMode = .aspectFill
//let transition = SKTransition.push(with: SKTransitionDirection.right, duration: 0.5)
self.view?.presentScene(endGameScene)
transitionNode = SKSpriteNode(color: UIColor.white, size: self.frame.size)
transitionNode.zPosition = 6
self.addChild(transitionNode)
transitionNode.run(SKAction.fadeIn(withDuration: 0.3))
run(gameOverSound)
//pillarTimer.invalidate()
durationTimer.invalidate()
gameOver = true
}
func addBackground(){
for i in 0...2 {
background = SKSpriteNode(imageNamed: "background")
background.name = "background"
background.size = CGSize(width: self.frame.size.width, height: self.frame.size.height / 2)
background.anchorPoint = CGPoint(x: 0.5, y: 0.5)
background.position = CGPoint(x: CGFloat(i) * background.size.width, y: backgroundFrame.size.height - (background.size.height + 170))
background.zPosition = -1
self.addChild(background)
foreground = SKSpriteNode(imageNamed: "foreground")
foreground.name = "foreground"
foreground.size = CGSize(width: self.frame.size.width , height: self.frame.size.height)
foreground.anchorPoint = CGPoint(x: 0.5, y: 0.5)
foreground.position = CGPoint(x: CGFloat(i) * foreground.size.width, y: 0)
foreground.zPosition = 0
self.addChild(foreground)
ground = SKSpriteNode(imageNamed: "ground")
ground.name = "ground"
ground.size = CGSize(width: ground.size.width, height: ground.size.height)
ground.anchorPoint = CGPoint(x: 0.5, y: 0.5)
ground.position = CGPoint(x: CGFloat(i) * ground.size.width, y: foreground.position.y - (foreground.size.height / 2) + ground.size.height - 12)
//ground.xScale *= -1
ground.zPosition = 1
self.addChild(ground)
}
}
func moveScenery(){
self.enumerateChildNodes(withName: "background", using: ({
(node, error) in
node.position.x -= 0.5
if(node.position.x < -(self.frame.size.width)){
node.position.x += self.frame.width * 2
}
}))
self.enumerateChildNodes(withName: "foreground", using: ({
(node, error) in
node.position.x -= 1
if(node.position.x < -(self.frame.size.width)){
node.position.x += self.frame.width * 2
}
}))
self.enumerateChildNodes(withName: "ground", using: ({
(node, error) in
node.position.x -= 3
if(node.position.x < -(self.frame.size.width)){
node.position.x += self.frame.width * 2
}
}))
}
deinit {
self.removeAllChildren()
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
if hasCollided {
moveScenery()
}
let playerVelocity = player.physicsBody!.velocity.dy
if playerVelocity < 0 {
player.texture = SKTexture(imageNamed: "player2")
}
}
}
| [
-1
] |
c70521896bb46e2567514a0c36cb9f42a4d0813c | 2cfe20bfdbf4e3d527f3f79d2540fda7ca258632 | /Bitmark/Flows/AppDetailsFlow.swift | 1f4a9f8ae9eae557b7dcaf337c624bc71258aaff | [] | no_license | bitmark-inc/bitmark-mobile-ios | 6b3af4aab161b7e5065686e1c558e804201be91b | 3643f10ea936552e447f3bb099ec6b2a37e900ed | refs/heads/master | 2021-06-17T04:10:43.599700 | 2021-04-01T04:11:38 | 2021-04-01T04:11:38 | 189,129,332 | 0 | 0 | null | 2019-09-25T10:27:30 | 2019-05-29T01:34:06 | Swift | UTF-8 | Swift | false | false | 2,275 | swift | //
// AppDetailsFlow.swift
// Bitmark
//
// Created by Thuyen Truong on 8/20/19.
// Copyright © 2019 Bitmark Inc. All rights reserved.
//
import Foundation
import RxFlow
class AppDetailsFlow: Flow {
var root: Presentable {
return self.rootViewController
}
var rootViewController: UINavigationController
init(rootViewController: UINavigationController) {
self.rootViewController = rootViewController
}
func navigate(to step: Step) -> FlowContributors {
guard let step = step as? BitmarkStep else { return .none }
switch step {
case .viewAppDetails:
return navigateToAppDetailsScreen()
case .viewTermsOfService:
return navigateToViewTermsOfServiceScreen()
case .viewPrivacyPolicy:
return navigateToViewPrivacyPolicyScreen()
case .viewReleaseNotes:
return navigateToViewReleaseNotesScreen()
case .viewReleaseNotesIsComplete:
rootViewController.popViewController(animated: true)
return .none
default:
return .none
}
}
fileprivate func navigateToAppDetailsScreen() -> FlowContributors {
let appDetailsVC = AppDetailViewController()
rootViewController.pushViewController(appDetailsVC)
return .one(flowContributor: .contribute(withNextPresentable: appDetailsVC, withNextStepper: appDetailsVC))
}
fileprivate func navigateToViewTermsOfServiceScreen() -> FlowContributors {
let appDetailContentVC = AppDetailContentViewController()
appDetailContentVC.appDetailContent = .termsOfService
rootViewController.pushViewController(appDetailContentVC)
return .none
}
fileprivate func navigateToViewPrivacyPolicyScreen() -> FlowContributors {
let appDetailContentVC = AppDetailContentViewController()
appDetailContentVC.appDetailContent = .privacyPolicy
rootViewController.pushViewController(appDetailContentVC)
return .none
}
fileprivate func navigateToViewReleaseNotesScreen() -> FlowContributors {
let releaseNotesContentVC = ReleaseNotesViewController()
releaseNotesContentVC.hidesBottomBarWhenPushed = true
rootViewController.pushViewController(releaseNotesContentVC)
return .one(flowContributor: .contribute(withNextPresentable: releaseNotesContentVC, withNextStepper: releaseNotesContentVC))
}
}
| [
-1
] |
7932a2807cb2bf1aada06ea2fe65ae02ae54ea8b | 0e1102ce339c9a0a887856e1b3a9663e1a3b5702 | /MemeMe/MemeEditorViewController.swift | 1d3810742b9fa73f1d38a848ec410c0da32d3b2c | [] | no_license | ariashary/MemeMe | 78e169e2bbf24e206da6135219e94bbd7580b417 | 9b214c0b508f0c035f0469cbe4e7d326fc36fb6a | refs/heads/master | 2020-07-12T17:42:47.360359 | 2019-09-10T14:13:21 | 2019-09-10T14:13:21 | 204,875,131 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 6,721 | swift | //
// ViewController.swift
// MemeMe
//
// Created by Muhammad Ashary on 28/08/19.
// Copyright © 2019 M. Ashary. All rights reserved.
//
import UIKit
class MemeEditorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet var imagePickerView: UIImageView!
@IBOutlet var cameraButton: UIBarButtonItem!
@IBOutlet var topTextField: UITextField!
@IBOutlet var bottomTextField: UITextField!
@IBOutlet var shareButton: UIBarButtonItem!
@IBOutlet var bottomBar: UIToolbar!
@IBOutlet var navigationBar: UINavigationBar!
let memeTextAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth: -3.6
]
// Mark: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
topTextField.delegate = self
bottomTextField.delegate = self
topTextField.text = "TOP"
bottomTextField.text = "BOTTOM"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
shareButton.isEnabled = imagePickerView.image != nil
topTextField.defaultTextAttributes = memeTextAttributes
bottomTextField.defaultTextAttributes = memeTextAttributes
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
// MARK: Keyboard Action
func textFieldDidBeginEditing(_ textField: UITextField) {
// Delete the default text when editing
if (textField == topTextField && topTextField.text == "TOP") {
topTextField.text = ""
} else if (textField == bottomTextField && bottomTextField.text == "BOTTOM") {
bottomTextField.text = ""
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// When clicking Done, hide the keyboard
textField.resignFirstResponder()
return true
}
// MARK: Pick Image
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
imagePickerView.image = image
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
// MARK: Keyboard Notification
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification:Notification) {
view.frame.origin.y -= getKeyboardHeight(notification)
}
@objc func keyboardWillHide(_ notofication: Notification) {
view.frame.origin.y = 0
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
// Mark: Create the Meme
func save() {
print("Saving success")
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imagePickerView.image!, memedImage: generateMemedImage())
// Add to the memes array in the Application Delegate
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
dismiss(animated: true, completion: nil)
}
func generateMemedImage() -> UIImage {
// TODO: Hide toolbar and navbar
bottomBar.isHidden = true
navigationBar.isHidden = true
// Render view to an image
UIGraphicsBeginImageContext(view.frame.size)
view.drawHierarchy(in: view.frame, afterScreenUpdates: true)
let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// TODO: Show toolbar and navbar
bottomBar.isHidden = false
navigationBar.isHidden = false
return memedImage
}
// MARK: Actions
@IBAction func pickAnImageFromAlbum(_ sender: UIBarButtonItem) {
let Imagepicker = UIImagePickerController()
Imagepicker.delegate = self
Imagepicker.sourceType = .photoLibrary
present(Imagepicker, animated: true, completion: nil)
}
@IBAction func pickAnImageFromCamera(_ sender: Any) {
let Imagepicker = UIImagePickerController()
Imagepicker.delegate = self
Imagepicker.sourceType = .camera
present(Imagepicker, animated: true, completion: nil)
}
@IBAction func shareImage(_ sender: UIBarButtonItem) {
let memedImage = generateMemedImage()
let activityView = UIActivityViewController(activityItems: [memedImage], applicationActivities: nil)
activityView.completionWithItemsHandler = { (activity, completed, items, error) in
if (completed) {
let _ = self.save()
}
}
self.present(activityView, animated: true, completion: nil)
}
@IBAction func resetButton(_ sender: UIBarButtonItem) {
imagePickerView.image = nil
topTextField.text = "TOP"
bottomTextField.text = "BOTTOM"
shareButton.isEnabled = false
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
}
| [
-1
] |
956c4bfb85cce7af92c6d718c7d4f1c3ee3b8109 | 457f154c6997e4aac769b4025c1c2eb16111ebd9 | /JSApp/Other/Main/Controller/BaseViewController.swift | 2285f643128ef45dea812a27d43997acf8ee6d4b | [] | no_license | yuheng5186/JW | 9e2ef5dd3b40e0b27c4bda07da0190b80e95318e | 084f8f46fdfb73484feb241c91cb0165bc07f6b7 | refs/heads/master | 2021-01-01T15:38:59.978419 | 2017-11-06T05:08:58 | 2017-11-06T05:08:58 | 97,667,464 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 6,001 | swift | //
// BaseViewController.swift
// JSApp
//
// Created by mac on 16/2/16.
// Copyright © 2016年 lufeng. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var errorView: NetworkErrorView!
var isShowLeftItem: Bool = true //默认是显示
var loadingCount: Int = 0 //请求服务器的次数,默认是0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(popActionWillExecute), name: NSNotification.Name(rawValue: popActionBeforPostNotification), object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !NetworkDetector.sharedInstance.isLinkNetwork {
NetworkIndicator().show("网络中断链接,请检查您的网络设置")
}
self.setNavigationBarBarButtonItem() //设置左边返回按钮和导航栏颜色
}
deinit {
NotificationCenter.default.removeObserver(self)
}
//切换界面将要被执行
func popActionWillExecute() {
}
//************************* 新增方法 *****************//
func setNavigationBarBarButtonItem() {
//显示左返回按钮
if self.self.isShowLeftItem == true {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_arrows"), style: .plain, target: self, action: nil)
} else { //隐藏返回按钮
self.navigationItem.leftBarButtonItem = nil
self.navigationItem.backBarButtonItem = nil
}
//判断navigationBar显示颜色
let navController = self.navigationController as? RootNavigationController
if self.barType == .green {
//重新设置颜色
if self.navigationItem.leftBarButtonItem != nil {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_arrows"), style: .plain, target: self, action: #selector(leftBarButtonItemAction))
}
navController?.setRedNavigationBar(self)
} else if self.barType == .picture{
//重新设置颜色
if self.navigationItem.leftBarButtonItem != nil {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_arrows"), style: .plain, target: self, action: #selector(leftBarButtonItemAction))
}
navController?.setPictureNavigationBar(self)
}else if self.barType == .white {
//重新设置颜色
if self.navigationItem.leftBarButtonItem != nil {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "返回.png"), style: .plain, target: self, action: #selector(leftBarButtonItemAction))
}
navController?.setWhiteNavigationBar(self)
}
}
//点击事件
func leftBarButtonItemAction() -> () {
let navController = self.navigationController as? RootNavigationController
navController?.popAction(true,popController: self)
}
//************************* 旧的方法 *****************//
func loadData() {
}
// 獲取数据成功后的結果
func hideErrorView() {
// 如果有网的时候,删除掉,所有的 NetworkErrorView(无网络处理视图)
for subView in view.subviews {
if subView.classForCoder == NetworkErrorView.classForCoder() {
subView.removeFromSuperview()
}
}
}
// 获取数据失败的处理操作
func loadDataError() {
//没有网络的时候添加 无网络视图 --- NetworkErrorView
self.errorView = Bundle.main.loadNibNamed("NetworkErrorView", owner: nil, options: nil)!.first as! NetworkErrorView
self.errorView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - TOP_HEIGHT)
self.errorView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(loadData)))
self.errorView.backgroundColor = DEFAULT_GRAYCOLOR
self.view.addSubview(self.errorView)
}
//第一次请求显示的loading界面
func loadFirstLoadingView() {
let loadingView = Bundle.main.loadNibNamed("JSLodingView", owner: nil, options: nil)!.first as! JSLodingView
loadingView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
loadingView.backgroundColor = DEFAULT_GRAYCOLOR
loadingView.indicatorView.startAnimating()
self.view.addSubview(loadingView)
}
//隐藏第一次请求的loading界面
func hideFristLoadingView() {
for view in self.view.subviews {
if view.isKind(of: JSLodingView.classForCoder()) {
view.removeFromSuperview()
}
}
}
//获取数据失败的处理操作
func loadDataErrorWithErrorString(_ errorString: String?) {
//没有网络的时候添加 无网络视图 --- NetworkErrorView
self.errorView = Bundle.main.loadNibNamed("NetworkErrorView", owner: nil, options: nil)!.first as! NetworkErrorView
self.errorView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
self.errorView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(loadData)))
self.errorView.backgroundColor = DEFAULT_GRAYCOLOR
self.view.addSubview(self.errorView)
if errorString != nil && errorString != "" {
self.errorView.errInoLB.text = errorString
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
-1
] |
8c9ddc8690b40913eea7977889e2631677b0f878 | 6da960cb2ba344875ff5a0e122c0299a07a3618b | /ToDoList/ToDoList/ProductFile/Apputility/SceneDelegate.swift | 46d172aaf928eb7383025bb827bac58b6a3e2841 | [] | no_license | dbagmar/TaskList | 9c64a8df505634d42e471e7fd6aa6f45a9146d44 | e1e2c502061238da1000b14f10d24eda97bc8d99 | refs/heads/main | 2023-05-05T12:08:54.995448 | 2021-05-12T11:34:01 | 2021-05-12T11:34:01 | 366,692,379 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,485 | swift | //
// SceneDelegate.swift
// ToDoList
//
// Created by Darshan Bagmar on 11/05/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
// Save changes in the application's managed object context when the application transitions to the background.
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
| [
393221,
163849,
393228,
393231,
393251,
352294,
344103,
393260,
393269,
213049,
376890,
385082,
393277,
376906,
327757,
254032,
368728,
180314,
254045,
180322,
376932,
286833,
286845,
286851,
417925,
262284,
360598,
286880,
377003,
377013,
164029,
327872,
180418,
377030,
377037,
377047,
418008,
418012,
377063,
327915,
205037,
393457,
393461,
393466,
418044,
385281,
336129,
262405,
180491,
336140,
164107,
262417,
368913,
262423,
377118,
377121,
262437,
254253,
336181,
262455,
393539,
262473,
344404,
213333,
418135,
270687,
262497,
418145,
262501,
213354,
246124,
262508,
262512,
213374,
385420,
393613,
262551,
262553,
385441,
385444,
262567,
385452,
262574,
393649,
385460,
262587,
344512,
262593,
360917,
369119,
328178,
328180,
328183,
328190,
254463,
328193,
164362,
328204,
328207,
410129,
393748,
262679,
377372,
188959,
385571,
377384,
197160,
33322,
352822,
270905,
197178,
418364,
188990,
369224,
270922,
385610,
352844,
385617,
352865,
262761,
352875,
344694,
352888,
336513,
377473,
385671,
148106,
213642,
377485,
352919,
98969,
344745,
361130,
336556,
434868,
164535,
336568,
164539,
328379,
328387,
352969,
344777,
418508,
385743,
385749,
139998,
189154,
369382,
361196,
418555,
344832,
336644,
344837,
344843,
328462,
361231,
394002,
336660,
418581,
418586,
434971,
369436,
262943,
369439,
418591,
418594,
336676,
418600,
418606,
369464,
361274,
328516,
336709,
328520,
336712,
361289,
328523,
336715,
361300,
213848,
426842,
361307,
197469,
361310,
254813,
361318,
344936,
361323,
361335,
328574,
369544,
361361,
222129,
345036,
386004,
345046,
386012,
386019,
386023,
328690,
435188,
328703,
328710,
418822,
377867,
328715,
361490,
386070,
336922,
345119,
377888,
214060,
345134,
345139,
361525,
386102,
361537,
377931,
345172,
189525,
156762,
402523,
361568,
148580,
345200,
361591,
386168,
361594,
410746,
214150,
345224,
386187,
345247,
361645,
345268,
402615,
361657,
337093,
402636,
328925,
165086,
66783,
165092,
328933,
222438,
328942,
386286,
386292,
206084,
328967,
345377,
345380,
353572,
345383,
263464,
337207,
345400,
378170,
369979,
386366,
337224,
337230,
337235,
263509,
353634,
337252,
402792,
271731,
378232,
337278,
271746,
181639,
353674,
181644,
361869,
181650,
181655,
230810,
181671,
181674,
181679,
181682,
337330,
181687,
370105,
181691,
181697,
361922,
337350,
181704,
337366,
271841,
329192,
361961,
329195,
116211,
337399,
402943,
337416,
329227,
419341,
419345,
329234,
419351,
345626,
419357,
345631,
419360,
370208,
394787,
419363,
370214,
419369,
394796,
419377,
419386,
206397,
214594,
419401,
353868,
419404,
173648,
419408,
214611,
419412,
403040,
345702,
222831,
370298,
353920,
403073,
403076,
345737,
198282,
403085,
403092,
345750,
419484,
345758,
345763,
419492,
345766,
419498,
419502,
370351,
419507,
337588,
419510,
419513,
337601,
403139,
337607,
419528,
419531,
272083,
394967,
419543,
419545,
345819,
419548,
419551,
345829,
419560,
337643,
419564,
337647,
370416,
337671,
362249,
362252,
395022,
362256,
321300,
345888,
362274,
378664,
354107,
345916,
354112,
370504,
329545,
345932,
370510,
354132,
247639,
337751,
370520,
313181,
182110,
354143,
354157,
345965,
345968,
345971,
345975,
403321,
1914,
354173,
395148,
247692,
337809,
247701,
329625,
436127,
436133,
247720,
337834,
362414,
337845,
190393,
346059,
247760,
346064,
346069,
419810,
329699,
354275,
190440,
354314,
346140,
436290,
395340,
378956,
436307,
338005,
329816,
100454,
329833,
329853,
329857,
329868,
411806,
346273,
362661,
100525,
387250,
379067,
387261,
256193,
395467,
346317,
411862,
411865,
411869,
411874,
379108,
411877,
387303,
395496,
346344,
338154,
387307,
346350,
338161,
387314,
436474,
321787,
379135,
411905,
411917,
379154,
395539,
387350,
387353,
338201,
182559,
338212,
248112,
362823,
436556,
321880,
362844,
379234,
354674,
321911,
420237,
379279,
272787,
354728,
338353,
338382,
272849,
248279,
256474,
182755,
338404,
330225,
248309,
248332,
330254,
199189,
420377,
330268,
191012,
412215,
330320,
199250,
191069,
346722,
248427,
191085,
338544,
346736,
191093,
346743,
346769,
150184,
248505,
363198,
223936,
355025,
273109,
355029,
264919,
338661,
264942,
363252,
338680,
264965,
338701,
363294,
199455,
396067,
346917,
396070,
215854,
355123,
355141,
355144,
338764,
355151,
330581,
387929,
330585,
355167,
265056,
265059,
355176,
355180,
355185,
412600,
207809,
379849,
347082,
396246,
330711,
248794,
437219,
257009,
265208,
265215,
199681,
379908,
338951,
330761,
330769,
330775,
248863,
158759,
396329,
347178,
404526,
396337,
330803,
396340,
339002,
388155,
339010,
347208,
248905,
330827,
248915,
183384,
339037,
412765,
257121,
322660,
265321,
248952,
420985,
330886,
330890,
347288,
248986,
44199,
380071,
339118,
249018,
339133,
126148,
322763,
330959,
330966,
265433,
265438,
388320,
363757,
388348,
339199,
396552,
175376,
175397,
273709,
372016,
437553,
347442,
199989,
175416,
396601,
208189,
437567,
175425,
437571,
126279,
437576,
437584,
331089,
437588,
331094,
396634,
175451,
437596,
429408,
175458,
175461,
175464,
265581,
331124,
175478,
249210,
175484,
175487,
249215,
175491,
249219,
249225,
249228,
249235,
175514,
175517,
396703,
396706,
175523,
355749,
396723,
388543,
380353,
380364,
339406,
372177,
339414,
249303,
413143,
339418,
339421,
249310,
339425,
249313,
339429,
339435,
249329,
69114,
372229,
208399,
175637,
405017,
134689,
339504,
265779,
421442,
413251,
265796,
265806,
224854,
224858,
339553,
257636,
224871,
372328,
257647,
372338,
224885,
224888,
224891,
224895,
126597,
421509,
224905,
11919,
224911,
224914,
126611,
224917,
224920,
126618,
208539,
224923,
224927,
224930,
224933,
257705,
224939,
224943,
257713,
224949,
257717,
257721,
224954,
257725,
224960,
257733,
224966,
224970,
257740,
224976,
257745,
339664,
257748,
224982,
257752,
224987,
257762,
224996,
225000,
225013,
257788,
225021,
339711,
257791,
225027,
257796,
339722,
257802,
257805,
225039,
257808,
249617,
225044,
167701,
372500,
257815,
225049,
257820,
225054,
184096,
397089,
257825,
225059,
339748,
225068,
257837,
413485,
225071,
225074,
257843,
225077,
257846,
225080,
397113,
225083,
397116,
257853,
225088,
225094,
225097,
257869,
257872,
225105,
397140,
225109,
225113,
257881,
257884,
257887,
225120,
257891,
413539,
225128,
257897,
339818,
225138,
339827,
257909,
225142,
372598,
257914,
257917,
225150,
257922,
380803,
225156,
339845,
257927,
225166,
397201,
225171,
380823,
225176,
225183,
372698,
372704,
372707,
356336,
380919,
393215,
372739,
405534,
266295,
266298,
217158,
421961,
200786,
356440,
217180,
430181,
266351,
356467,
266365,
192640,
266375,
381069,
225425,
250003,
225430,
250008,
356507,
250012,
225439,
135328,
192674,
225442,
438434,
225445,
225448,
438441,
356521,
225451,
258223,
225456,
430257,
225459,
225462,
225468,
389309,
225472,
372931,
225476,
389322,
225485,
225488,
225491,
266454,
225494,
225497,
225500,
225503,
225506,
356580,
225511,
217319,
225515,
225519,
381177,
397572,
389381,
381212,
356638,
356641,
356644,
356647,
266537,
389417,
356650,
356656,
332081,
307507,
340276,
356662,
397623,
332091,
225599,
201030,
348489,
332107,
151884,
430422,
348503,
250211,
340328,
250217,
348523,
348528,
332153,
356734,
389503,
332158,
438657,
250239,
389507,
348548,
356741,
332175,
160152,
373146,
340380,
373149,
70048,
356783,
373169,
266688,
201158,
127473,
217590,
340473,
324095,
324100,
324103,
324112,
340501,
324118,
324122,
340512,
332325,
324134,
381483,
356908,
324141,
324143,
356917,
324150,
324156,
168509,
348734,
324161,
324165,
356935,
348745,
381513,
324171,
324174,
324177,
389724,
332381,
373344,
340580,
348777,
381546,
119432,
340628,
184983,
373399,
258723,
332455,
332460,
332464,
332473,
381626,
332484,
332487,
332494,
357070,
357074,
332512,
332521,
340724,
332534,
348926,
389927,
348979,
152371,
348983,
340792,
398141,
357202,
389971,
357208,
389979,
430940,
357212,
357215,
439138,
201580,
201583,
349041,
340850,
381815,
430967,
324473,
398202,
340859,
324476,
430973,
119675,
324479,
340863,
324482,
373635,
324485,
324488,
185226,
381834,
324493,
324496,
324499,
430996,
324502,
324511,
422817,
324514,
201638,
373672,
324525,
111539,
324534,
324539,
324542,
398280,
349129,
340940,
340942,
209874,
340958,
431073,
398307,
340964,
209896,
201712,
209904,
349173,
381947,
201724,
349181,
431100,
431107,
349203,
209944,
209948,
357411,
250915,
250917,
169002,
357419,
209966,
209969,
209973,
209976,
209980,
209988,
209991,
431180,
209996,
341072,
349268,
177238,
250968,
210011,
373853,
341094,
210026,
210028,
210032,
349296,
210037,
210042,
210045,
349309,
152704,
349313,
160896,
210053,
210056,
349320,
259217,
373905,
210068,
210072,
210078,
210081,
210085,
210089,
210096,
210100,
324792,
210108,
357571,
210116,
210128,
210132,
333016,
210139,
210144,
218355,
218361,
275709,
128254,
275713,
242947,
275717,
275723,
333075,
349460,
333079,
251161,
349486,
349492,
415034,
210261,
365912,
259423,
374113,
251236,
374118,
333164,
234867,
390518,
357756,
374161,
112021,
349591,
357793,
333222,
259516,
415168,
366035,
415187,
366039,
415192,
415194,
415197,
415200,
333285,
415208,
366057,
366064,
415217,
415225,
423424,
415258,
415264,
366118,
415271,
382503,
349739,
144940,
415279,
415282,
349748,
415286,
210488,
415291,
415295,
349762,
333396,
374359,
333400,
366173,
423529,
423533,
210547,
415354,
333440,
267910,
267929,
333512,
259789,
366301,
333535,
153311,
366308,
366312,
431852,
399086,
366319,
210673,
366322,
399092,
366326,
333566,
268042,
210700,
366349,
210707,
399129,
333595,
210720,
366384,
358192,
210740,
366388,
358201,
325441,
366403,
325447,
341831,
341835,
341839,
341844,
415574,
341852,
350046,
399200,
399208,
268144,
358256,
358260,
341877,
399222,
325494,
333690,
325505,
333699,
399244,
333709,
333725,
333737,
382891,
350153,
358348,
333777,
219094,
399318,
358372,
350190,
350194,
333819,
350204,
350207,
325633,
325637,
350214,
219144,
268299,
333838,
350225,
186388,
350232,
350238,
350241,
374819,
350245,
350249,
350252,
178221,
350257,
350260,
350272,
243782,
350281,
350286,
374865,
342113,
252021,
342134,
374904,
268435,
333998,
334012,
260299,
350411,
350417,
350423,
350426,
350449,
375027,
358645,
350459,
350462,
350465,
350469,
268553,
350477,
268560,
350481,
432406,
350487,
325915,
350491,
325918,
350494,
325920,
350500,
194854,
350505,
358701,
391469,
350510,
358705,
358714,
358717,
383307,
358738,
334162,
383331,
383334,
391531,
383342,
334204,
268669,
194942,
391564,
366991,
268702,
342431,
375209,
375220,
334263,
326087,
358857,
195041,
334312,
104940,
375279,
416255,
350724,
186898,
342546,
350740,
342551,
334359,
342555,
334364,
416294,
350762,
252463,
358962,
334386,
334397,
358973,
252483,
219719,
399957,
334425,
326240,
375401,
334466,
334469,
162446,
326291,
342680,
342685,
260767,
342711,
244410,
260798,
334530,
260802,
350918,
154318,
342737,
391895,
154329,
416476,
64231,
113389,
342769,
203508,
375541,
342777,
391938,
391949,
375569,
326417,
375572,
375575,
375580,
162592,
334633,
326444,
383794,
326452,
326455,
375613,
244542,
326463,
375616,
326468,
342857,
326474,
326479,
326486,
416599,
342875,
244572,
326494,
433001,
400238,
326511,
211826,
211832,
392061,
351102,
359296,
252801,
260993,
351105,
400260,
211846,
342921,
342931,
252823,
400279,
392092,
400286,
252838,
359335,
211885,
252846,
400307,
351169,
359362,
351172,
170950,
187335,
326599,
359367,
359383,
359389,
383968,
343018,
359411,
261109,
261112,
244728,
383999,
261130,
261148,
359452,
211999,
261155,
261160,
261166,
359471,
375868,
343132,
384099,
384102,
384108,
367724,
187503,
343155,
384115,
212095,
351366,
384136,
384140,
384144,
384152,
384158,
384161,
351399,
384169,
367795,
384182,
367801,
384189,
384192,
343232,
351424,
367817,
244938,
384202,
253132,
326858,
384209,
146644,
351450,
384225,
359650,
343272,
351467,
359660,
384247,
351480,
384250,
351483,
351492,
343307,
384270,
359695,
261391,
253202,
261395,
384276,
384284,
245021,
384290,
253218,
245032,
171304,
384299,
351535,
376111,
245042,
326970,
384324,
343366,
212296,
212304,
367966,
343394,
367981,
343410,
155000,
327035,
245121,
245128,
253321,
155021,
384398,
245137,
245143,
245146,
245149,
343453,
245152,
245155,
155045,
245158,
40358,
245163,
114093,
327090,
343478,
359867,
384444,
146878,
327108,
327112,
384457,
359887,
359891,
368093,
155103,
343535,
343540,
368120,
343545,
409092,
253445,
359948,
359951,
245295,
359984,
343610,
400977,
400982,
179803,
245358,
155255,
155274,
368289,
245410,
425639,
425652,
425663,
155328,
245463,
155352,
155356,
212700,
155364,
245477,
155372,
245487,
212723,
409336,
155394,
155404,
245528,
155423,
360224,
155439,
204592,
155444,
155448,
417596,
384829,
384831,
360262,
155463,
155477,
376665,
155484,
261982,
425823,
155488,
376672,
155492,
327532,
261997,
376686,
262000,
262003,
425846,
262006,
147319,
262009,
327542,
262012,
155517,
155523,
155526,
360327,
376715,
155532,
262028,
262031,
262034,
262037,
262040,
262043,
155550,
262046,
253854,
262049,
262052,
327590,
155560,
155563,
155566,
327613,
393152,
311244,
393170,
155604,
155620,
253924,
155622,
253927,
327655,
360432,
393204,
360439,
253944,
393209,
155647
] |
0ec56d74b92c296eeb2d0b7115582efd1a1a3205 | 2869808c9f4fdb820281a8521a62208766a0aa43 | /LoveSwiftLeetcode/96.不同的二叉搜索树.swift | 9ed9321f15ef230684bb472c1db5f5fcb1aaf88f | [] | no_license | BaoziSwifter/MyPythonLeetCode | 03dcfa0705ad87a1b727fe2f924fabb7184c4ca1 | 0e8f0d902a379c07c386aedc6d10d7a2aa6d1b4a | refs/heads/master | 2023-01-09T08:15:23.154464 | 2022-12-25T02:35:16 | 2022-12-25T02:35:16 | 220,202,819 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 439 | swift | /*
* @lc app=leetcode.cn id=96 lang=swift
*
* [96] 不同的二叉搜索树
*/
// @lc code=start
class Solution {
func numTrees(_ n: Int) -> Int {
if n <= 1 { return 1 }
var dp = [Int](repeating: 0, count: n + 1)
dp[0] = 1
dp[1] = 1
for i in 2...n {
for j in 1...i {
dp[i] += dp[j-1]*dp[i-j]
}
}
return dp[n]
}
}
// @lc code=end
| [
-1
] |
3607aae425008a4fff6d2ec260f8a0c7438019bf | 9821898f57e43b12021826609d04629133f93c1e | /WBooks/Book/Service/BookAPIService.swift | 7d44dfc6f51ceea5fff754c4dd8ab32c3790f720 | [] | no_license | gmazzei/WBooks-MVC | 3e0bafd828a379043ad7829f83d0b2d3af769a03 | ae186bc48c485daae7de625e504386ef77b7442a | refs/heads/master | 2023-02-28T06:47:05.268121 | 2021-01-04T18:39:44 | 2021-01-04T18:39:44 | 322,376,547 | 0 | 0 | null | 2021-01-04T18:39:45 | 2020-12-17T18:15:26 | Swift | UTF-8 | Swift | false | false | 619 | swift | //
// BookAPIService.swift
// WBooks
//
// Created by Gabriel Mazzei on 15/12/2020.
//
import Foundation
import UIKit
final class BookAPIService: BookService {
weak var delegate: BookServiceDelegate?
func loadCover(path: String) {
guard let url = URL(string: path), let delegate = delegate else { return }
DispatchQueue.global().async {
guard let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return }
DispatchQueue.main.async {
delegate.didLoadImage(image)
}
}
}
}
| [
-1
] |
39c543f1ece6b955d8eca873c34cad7841c83235 | 5fc5093bc0e29c33ed1b2418c97b03ca9b76c4a9 | /Sources/AWSOrganizations/Models/PolicyTargetSummary.swift | 085ac720e540fc110e1651a36bdfe465aefa9c5b | [] | no_license | opsroll/AWSOrganizations | d4b9a038add670ce72184f0cb7018eda84f1ac23 | bc54d2c977d81e518cddb7d08c33c3a42b553872 | refs/heads/master | 2021-07-23T08:37:50.027410 | 2018-05-11T18:53:13 | 2018-05-11T18:53:13 | 133,081,547 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,078 | swift | //
// PolicyTargetSummary.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Contains information about a root, OU, or account that a policy is attached to. */
open class PolicyTargetSummary: Codable {
/** <p>The Amazon Resource Name (ARN) of the policy target.</p> <p>For more information about ARNs in Organizations, see <a href=\"http://docs.aws.amazon.com/organizations/latest/userguide/orgs_permissions.html#orgs-permissions-arns\">ARN Formats Supported by Organizations</a> in the <i>AWS Organizations User Guide</i>.</p> */
public var arn: GenericArn?
/** <p>The friendly name of the policy target.</p> <p>The <a href=\"http://wikipedia.org/wiki/regex\">regex pattern</a> that is used to validate this parameter is a string of any of the characters in the ASCII character range.</p> */
public var name: TargetName?
/** <p>The unique identifier (ID) of the policy target.</p> <p>The <a href=\"http://wikipedia.org/wiki/regex\">regex pattern</a> for a target ID string requires one of the following:</p> <ul> <li> <p>Root: a string that begins with \"r-\" followed by from 4 to 32 lower-case letters or digits.</p> </li> <li> <p>Account: a string that consists of exactly 12 digits.</p> </li> <li> <p>Organizational unit (OU): a string that begins with \"ou-\" followed by from 4 to 32 lower-case letters or digits (the ID of the root that the OU is in) followed by a second \"-\" dash and from 8 to 32 additional lower-case letters or digits.</p> </li> </ul> */
public var targetId: PolicyTargetId?
/** The type of the policy target. */
public var type: TargetType?
public init(arn: GenericArn?, name: TargetName?, targetId: PolicyTargetId?, type: TargetType?) {
self.arn = arn
self.name = name
self.targetId = targetId
self.type = type
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: String.self)
try container.encodeIfPresent(arn, forKey: "Arn")
try container.encodeIfPresent(name, forKey: "Name")
try container.encodeIfPresent(targetId, forKey: "TargetId")
try container.encodeIfPresent(type, forKey: "Type")
}
// Decodable protocol methods
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: String.self)
arn = try container.decodeIfPresent(GenericArn.self, forKey: "Arn")
name = try container.decodeIfPresent(TargetName.self, forKey: "Name")
targetId = try container.decodeIfPresent(PolicyTargetId.self, forKey: "TargetId")
type = try container.decodeIfPresent(TargetType.self, forKey: "Type")
}
}
| [
-1
] |
d193eaf6c755c1c967bc7807fbe8978b3ed014db | 73fa5f9a1f257abbdb683d9944283a0435000873 | /Sejima/Sources/MURangeTrimmer/MUBasicRange.swift | e9518b1643295eb7e4dda89c1125ae278a62eedf | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ravish21/Sejima | 5a62b72b65461b7788c7d4166757da8b577d4edc | 09c38c64b9ec1fdd367a0b58d0dadcb57647a849 | refs/heads/master | 2020-11-26T09:29:20.240499 | 2019-12-09T16:56:27 | 2019-12-09T16:56:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 520 | swift | //
// MUBasicRange.swift
// Sejima
//
// Created by Loïc GRIFFIE on 14/03/2019.
// Copyright © 2019 Loïc GRIFFIE. All rights reserved.
//
import UIKit
/// Struct with just range and title
public struct MUBasicRange {
/// Specifies the range title.
public let title: String
/// Spécifies the range value.
public let range: MURange<CGFloat>
/// Init a MUBasicRange.
public init(with title: String, range: MURange<CGFloat>) {
self.title = title
self.range = range
}
}
| [
327446
] |
cdf8adb7c6b7437fa7feccbe7f4361bd072cd77f | 5f5a4ad52adeed593de161191b89f0c8f2a1588f | /Tests/LinuxMain.swift | 1fd6b9b02dc2af4b15aa9fe0831950e5c9ccf636 | [
"Apache-2.0"
] | permissive | sinoru/Logue | ab21bac2e7cd1260f49222b9eef9c6e75ce4be9b | 9d1d9092fc39ac9fb2cf8c1b494acf622ec4b5f6 | refs/heads/master | 2020-04-29T21:06:05.460701 | 2019-03-19T05:55:25 | 2019-03-19T05:55:30 | 176,402,631 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 111 | swift | import XCTest
import LogueTests
var tests = [XCTestCaseEntry]()
tests += LogueTests.allTests()
XCTMain(tests) | [
248320,
324609,
45058,
254467,
222725,
145938,
35347,
238613,
35352,
192029,
323613,
217120,
342562,
333349,
224296,
35372,
343599,
199216,
168501,
321591,
162362,
54336,
253504,
175173,
187467,
352334,
332368,
341076,
184406,
327256,
343655,
345191,
139367,
312943,
338547,
253046,
346746,
347259,
323711,
245377,
160899,
317063,
245389,
258709,
315548,
343205,
314022,
181929,
248489,
352942,
191672,
229049,
153274,
325305,
350909,
326335,
222401,
225986,
315585,
323781,
339668,
254173,
352992,
317667,
323818,
329453,
378095,
211187,
315124,
337651,
194809,
315135,
126210,
319236,
162565,
374023,
208138,
148237,
136462,
343309,
315151,
353048,
347418,
192288,
311585,
348961,
342307,
334116,
325413,
254246,
341798,
52521,
341808,
347444,
321846,
354103,
368445,
56638,
166726,
325452,
323408,
253782,
253786,
341854,
253790,
351071,
38753,
253794,
244581,
211814,
246117,
253802,
351083,
316780,
106860,
253806,
253810,
240501,
151932,
349584,
212378,
200603,
321437,
253342,
421793,
57767,
178088,
305586,
235958,
344504,
343486,
326592,
373199,
340946,
338389,
343519,
319458,
241123,
319462,
340969,
313324,
170481,
343027,
347125,
247798,
342525
] |
548765573e583f584a61d894a4e3c30c18bc839e | f1170eef183d6869805faa90ec9b0a76515c4e35 | /Common/HttpRequest.swift | 44f794b441dbaf935db163969e578aa407a482a4 | [
"BSD-3-Clause"
] | permissive | FrithjofMatthiasSchaefer/swifter | efe47450de135961b90de7802b100c5d7c46dc91 | a6154eddf01a3823e222fa00177ad9fadb29e556 | refs/heads/master | 2021-01-21T16:09:57.538727 | 2014-11-10T18:02:57 | 2014-11-10T18:02:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 310 | swift | //
// HttpRequest.swift
// Swifter
//
// Created by Damian Kolakowski on 19/08/14.
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
struct HttpRequest {
let url: String
let method: String
let headers: Dictionary<String, String>
let responseData: NSData?
}
| [
-1
] |
3d026035a2971eef5e6c3f6d5a8dcb1e5b584d9b | 856c80927ff77fdce861c33763b421b1eae1d1e9 | /ViewControllers/IzgubeniViewController.swift | f0dc8dc086adb6a6a1c156b499c0ba1911a857c7 | [] | no_license | IvanaStamardjijoska/NajdiMilenik_AnimalApp | 4a380a0577dadda24f563c93600b53e52f61ba11 | 9e4a8887bca4174f7144b8e99ce9ee24407e1428 | refs/heads/master | 2020-04-17T08:27:32.033971 | 2019-01-18T13:53:10 | 2019-01-18T13:53:10 | 166,412,871 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,048 | swift | //
// izgubeniViewController.swift
// Project
//
// Created by CodeWell on 12/22/18.
// Copyright © 2018 Ivana Stamardjioska. All rights reserved.
//
import UIKit
class IzgubeniViewController: UIViewController {
@IBOutlet weak var izgubeniImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
izgubeniImage.layer.cornerRadius = 30
izgubeniImage.clipsToBounds = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| [
340707
] |
f4160c575498cb20595693a9d36783faefbda9f4 | 667ba98aabf9314c46e2c3cc67443d5ee6a260d7 | /DeezerApp/Controllers/AlbumList/Controllers/AlbumsViewController.swift | 456766e808b069994fbf84f437bf29a93217ac38 | [] | no_license | jwd-ali/TidalAssignment | 38f5ebb65a38a17e6b42191e0cf05a5474033891 | ef1fd53363b5042cb66c3fbba72cf4a6bd7fb499 | refs/heads/master | 2020-11-26T11:14:40.557120 | 2019-12-19T13:22:27 | 2019-12-19T13:22:27 | 229,055,638 | 3 | 0 | null | 2019-12-19T13:02:14 | 2019-12-19T13:02:13 | null | UTF-8 | Swift | false | false | 2,725 | swift | //
// AlbumsViewController.swift
// DeezerApp
//
// Created by Praveen on 05/12/19.
// Copyright © 2019 Praveen. All rights reserved.
//
import UIKit
class AlbumsViewController: UIViewController {
// MARK: - Outlet
@IBOutlet var collectionView: UICollectionView!
// MARK: - Properties Injection
var artist: Artist
// MARK: - Properties Injection
//MARK:- should be private
private let viewModel: AlbumListViewModel = AlbumListViewModel()
private let albumCollectionViewDataSource: AlbumCollectionViewDataSource = AlbumCollectionViewDataSource()
// MARK: - Initializer
init(artist: Artist) {
self.artist = artist
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupCollectionView()
setupBindings()
self.viewModel.getAlbums("\(artist.id)")
}
//MARK:- should be private
private func setupViews() {
navigationController?.navigationBar.barStyle = .blackOpaque
self.navigationController?.navigationBar.prefersLargeTitles = false
self.navigationItem.title = artist.name
self.collectionView.backgroundColor = UIColor.Common.primary
self.view.backgroundColor = UIColor.Common.primary
}
//MARK:- should be private
private func setupCollectionView() {
albumCollectionViewDataSource.albumsViewControllerDelegate = self
albumCollectionViewDataSource.collectionView = self.collectionView
}
private func setupBindings() {
viewModel.isBusy.bind { [unowned self] isBusy in
self.view.showLoader(show: isBusy)
}
viewModel.albums.bind { [unowned self] (albums) in
if albums != nil {
self.albumCollectionViewDataSource.albums?.data?.removeAll()
self.albumCollectionViewDataSource.albums = albums
self.albumCollectionViewDataSource.collectionView?.reloadData()
}
}
viewModel.error.bind { [unowned self] (error) in
if let error = error {
self.view.showLoader(show: false)
UIAlertController.show(error.localizedDescription, from: self)
}
}
}
}
extension AlbumsViewController: AlbumsViewControllerDelegate {
func didSelectAlbum(album: Album) {
let vc = Navigator.getAlbumDetailViewController(album)
self.navigationController?.pushViewController(vc, animated: true)
}
}
| [
-1
] |
defd90ed9d04ba5ca9bcb84ad4a361bf08a2797c | b835ba90f53e56368f06995ae7a48bff661db186 | /Breakout/GameScene.swift | 97ea0fc31d2bd5c40dbda1c36b9c5642fbf2e516 | [] | no_license | noahrubin1119/Breakout | 10ce20a24a8d758b3666760aed07403901d4d192 | a83450af9c76153ff639f99ff2c8f572242049ee | refs/heads/master | 2020-03-22T21:58:49.476448 | 2018-07-12T14:40:25 | 2018-07-12T14:40:25 | 140,725,906 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,929 | swift | //
// GameScene.swift
// Breakout
//
// Created by Noah Rubin on 7/12/18.
// Copyright © 2018 Noah Rubin. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?
override func didMove(to view: SKView) {
// Get label node from scene and store it for use later
self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
if let label = self.label {
label.alpha = 0.0
label.run(SKAction.fadeIn(withDuration: 2.0))
}
// Create shape node to use during mouse interaction
let w = (self.size.width + self.size.height) * 0.05
self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3)
if let spinnyNode = self.spinnyNode {
spinnyNode.lineWidth = 2.5
spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
SKAction.fadeOut(withDuration: 0.5),
SKAction.removeFromParent()]))
}
}
func touchDown(atPoint pos : CGPoint) {
if let n = self.spinnyNode?.copy() as! SKShapeNode? {
n.position = pos
n.strokeColor = SKColor.green
self.addChild(n)
}
}
func touchMoved(toPoint pos : CGPoint) {
if let n = self.spinnyNode?.copy() as! SKShapeNode? {
n.position = pos
n.strokeColor = SKColor.blue
self.addChild(n)
}
}
func touchUp(atPoint pos : CGPoint) {
if let n = self.spinnyNode?.copy() as! SKShapeNode? {
n.position = pos
n.strokeColor = SKColor.red
self.addChild(n)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let label = self.label {
label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")
}
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
| [
230498,
314980,
230918,
256717,
351219,
289494,
317143,
308726,
288860,
300639
] |
c51a734a4575eab4f31cb71d8c1dc11460d42d98 | ffdf5d63ea54f0d0f7e39bc9475d12d5c5d5db15 | /SudokuValid/ViewController.swift | 38cc641c3578f2e256a55ddd33915bb381f1c850 | [] | no_license | utsha88/Sudoku | b32d3682683a5b62618423eb42dadcff54d75249 | 5d6254a2413aeacec989f37284a39d3a33395329 | refs/heads/master | 2020-03-12T18:45:29.504061 | 2018-04-23T23:33:22 | 2018-04-23T23:33:22 | 130,768,720 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,036 | swift | //
// ViewController.swift
// SudokuValid
//
// Created by Utsha Guha on 23-4-18.
// Copyright © 2018 Utsha Guha. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let flag = self.isValidSudoku(
[["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]])
print(flag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isValidSudoku(_ board: [[Character]]) -> Bool {
for i in 0..<board.count{
var myRowSet = Set<Character>()
var myRowArray = Array<Character>()
var myColSet = Set<Character>()
var myColArray = Array<Character>()
for j in 0..<board.count{
myRowSet.insert(board[i][j])
myRowArray.append(board[i][j])
myColSet.insert(board[j][i])
myColArray.append(board[j][i])
}
myRowArray = myRowArray.filter{ $0 != "."}
myRowSet.remove(".")
myColArray = myColArray.filter{ $0 != "."}
myColSet.remove(".")
if (Array(myRowSet).sorted() != myRowArray.sorted())
|| (Array(myColSet).sorted() != myColArray.sorted()) {
return false
}
}
let result = self.checkDuplicateIn3by3Matrix(board: board, rowIndex: 0, colIndex: 0)
return result
}
func checkDuplicateIn3by3Matrix(board:[[Character]],rowIndex:Int, colIndex:Int) -> Bool {
var tmpRow = rowIndex
while tmpRow<board.count {
var mySet = Set<Character>()
var myArray = Array<Character>()
for i in tmpRow..<tmpRow+3{
for j in colIndex..<colIndex+3{
mySet.insert(board[i][j])
myArray.append(board[i][j])
}
}
myArray = myArray.filter{ $0 != "."}
mySet.remove(".")
if (Array(mySet).sorted() != myArray.sorted()) {
return false
}
tmpRow = tmpRow + 3
if tmpRow == 9 {
if colIndex+3<9 {
let result = self.checkDuplicateIn3by3Matrix(board: board, rowIndex: 0, colIndex: colIndex+3)
return result
}
}
}
return true
}
}
| [
-1
] |
1cebb8834dd00a39e6d5ad6d3d2ccfa8c13e556f | 43e5f1075a3bc43abb9373e68c8cab3f1c757068 | /Brint_It_IOS_Jeison_Sergio/Bring It!/ViewControllers/ProductsViewController.swift | 1fa61652882b7d2cdc61df4cd6feeb5bd92302cd | [] | no_license | JeisonSaborioR/Brint_It_IOS_Jeison_Sergio | 9bcc873248c716e72fae47f210e627413503f977 | 8932f302784d3584e6bf49337992d4e1e358ab79 | refs/heads/master | 2021-08-23T01:34:38.669017 | 2017-12-02T05:51:15 | 2017-12-02T05:51:15 | 112,816,658 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 6,285 | swift | //
// ProductsViewController.swift
// Bring It!
//
// Created by Administrador on 10/19/17.
// Copyright © 2017 tec. All rights reserved.
//
import UIKit
import Alamofire
class ProductsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var nameShoppingList: UIBarButtonItem!
var productsCurrent = [Product]()
var alertController: UIAlertController!
@IBOutlet weak var productsTableV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
productsCurrent = (Singlenton.instance.currentShoppingList?.products)!
self.productsTableV.dataSource = self
self.productsTableV.delegate = self
self.title = Singlenton.instance.currentShoppingList?.name
loadActionSheet()
// Do any additional setup after loading the view.
}
@IBAction func backButton(_ sender: Any) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "HomeView") as! UITabBarController
self.present(viewController, animated: true, completion: nil)
}
@IBAction func speechButton(_ sender: Any) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "speechController") as! UINavigationController
self.present(viewController, animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
tabBarController?.tabBar.isHidden = true
self.navigationController?.isNavigationBarHidden = false
productsTableV.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func printMessage(error:String){
let alert = UIAlertController(title: "Alert", message: error, preferredStyle: .alert)
let accion = UIAlertAction(title: "Ok", style: .default){
(action) -> Void in
}
alert.addAction(accion)
self.present(alert,animated:true,completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberRows: Int = 0
numberRows = productsCurrent.count
print(numberRows)
return numberRows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "productList", for: indexPath) as! ProductTableViewCell
//myCell.nameShoppingListLabel.textColor = UIColor.white
let product = productsCurrent[(indexPath as NSIndexPath).row]
myCell.nameProductLabel.text! = product.name
myCell.quantityProductLabel.text! = String(product.quantity)
myCell.priceProductLabel.text! = String(product.price)
return myCell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let more = UITableViewRowAction(style:.normal,title: "More", handler: {action, indexPath in
Singlenton.instance.currentProductEdit = self.productsCurrent[(indexPath as NSIndexPath).row]
self.present(self.alertController, animated:true, completion:nil)
})
let delete = UITableViewRowAction(style:.destructive,title: "Delete", handler: {action, indexPath in
self.deleteProduct(tabRow: indexPath)
})
return [more, delete]
}
func loadActionSheet(){
alertController = UIAlertController(title:"", message:"",preferredStyle:UIAlertControllerStyle.actionSheet)
let editShoppingList = UIAlertAction(title:"Edit",style:UIAlertActionStyle.default){ (ACTION) -> Void in
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "updateProduct") as! UINavigationController
self.present(viewController, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title:"Cancel",style:UIAlertActionStyle.cancel){ (ACTION) -> Void in
}
alertController.addAction(editShoppingList)
alertController.addAction(cancelAction)
}
/////Revisar cierre de la ventana self.dismiss
func deleteProduct(tabRow: IndexPath){
let product = self.productsCurrent[tabRow.row]
let concatenateResult = product.id + "/" + (Singlenton.instance.currentShoppingList?.id)!
let url = URL(string: Constants.URL+Constants.DELETEPRODUCT+concatenateResult)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "DELETE"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest).responseJSON { response in
if response.response?.statusCode == Constants.STATUS_OK
{
self.productsCurrent.remove(at: tabRow.row)
self.productsTableV.reloadData()
}else{
self.printMessage(error: "Connection fail")
}
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "toSegueProductAdd"{
let destViewController = segue.destination as! UINavigationController
let targetController = destViewController.topViewController as! RegisterProductTableViewController
targetController.shoppingListId = (Singlenton.instance.currentShoppingList?.id)!
}
}
}
| [
-1
] |
e8e3f3a1cc1e063638265ecd025981e5f7cfbb32 | 00fb5bb5dbc18bdcd4084dbf69b550099d463190 | /TodoList/Screens/Settings.swift | aae56d4e1efd8f6f9114be3f564cbd007f9680db | [] | no_license | ChrisLFieldsII/swiftui-todos | 5db4488afbcaf14e1a1c7bf9fa874ff8cd9baa93 | 7b5964145afbb31c79f3162028f71b7f2455815c | refs/heads/master | 2020-09-22T14:04:06.202383 | 2019-12-13T23:31:32 | 2019-12-13T23:31:32 | 225,232,067 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 360 | swift | //
// Settings.swift
// TodoList
//
// Created by Christopher Fields on 12/13/19.
// Copyright © 2019 Christopher Fields. All rights reserved.
//
import SwiftUI
struct Settings: View {
var body: some View {
Text("Settings")
}
}
struct Settings_Previews: PreviewProvider {
static var previews: some View {
Settings()
}
}
| [
-1
] |
9dcb2f0090d205e71c4983397eb4ec07269123d1 | 3db122b417f490ecff5b8abe4eab341280495143 | /Kuaijizhang/Portal/Controller/ViewController.swift | 7281bb9aaf71d02bc636a25a1a685cc61928069f | [] | no_license | vancysheva/Kuaijizhang | 0991f1c3c0331c4b465ed501c6de53e435ee3d21 | 530d2d3fbd6b5f815775eda1f934bbd274ec8f6b | refs/heads/master | 2021-01-19T04:37:49.884402 | 2016-04-12T13:09:55 | 2016-04-12T13:09:55 | 47,373,319 | 4 | 0 | null | 2016-03-06T09:22:05 | 2015-12-04T01:40:16 | Swift | UTF-8 | Swift | false | false | 6,918 | swift | //
// ViewController.swift
// Kuaijizhang
//
// Created by 范伟 on 15/8/17.
// Copyright © 2015年 范伟. All rights reserved.
//
import UIKit
import UICountingLabel
import Charts
class ViewController: UIViewController {
@IBOutlet weak var todayExpenseLabel: CountingLabel!
@IBOutlet weak var todayConsumeTypeLabel: UICountingLabel!
@IBOutlet weak var todayCommentLabel: UICountingLabel!
@IBOutlet weak var weekExpenseLabel: UICountingLabel!
@IBOutlet weak var monthExpense: UICountingLabel!
@IBOutlet weak var monthIncomeLabel: UICountingLabel!
@IBOutlet weak var yearExpenseLabel: UICountingLabel!
@IBOutlet weak var yearIncomeLabel: UICountingLabel!
@IBOutlet var rmbLabel: [UILabel]!
@IBOutlet weak var currentAccountBookLabel: UILabel!
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet weak var yearLabel: UILabel!
@IBOutlet weak var todayDisplayLabel: UILabel!
@IBOutlet weak var weekDisplayLabel: UILabel!
@IBOutlet weak var monthDisplayLabel: UILabel!
@IBOutlet weak var yearDisplayLabel: UILabel!
@IBOutlet weak var columnChartView: ColumnChart!
var screenSize: CGSize = {
return UIScreen.mainScreen().bounds.size
}()
@IBOutlet weak var leftView: UIView! {
didSet {
leftView.frame = CGRect(x: 0, y: 0, width: 80, height: 40)
leftView.backgroundColor = leftView.superview?.backgroundColor
}
}
@IBOutlet weak var rightView: UIView! {
didSet {
rightView.frame = CGRect(x: 0, y: 0, width: 80, height: 40)
rightView.backgroundColor = rightView.superview?.backgroundColor
}
}
let portalViewModel = PortalViewModel()
var barChartController: FWChartController?
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
//// 设置右上角的正在使用的账本名称
setCurrentAccountBook()
adapteLabelsFont()
adapteRmbLabels(rmbLabel)
// 设置面板中日期
setDate()
updateUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//// 设置左上角的年月
monthLabel.text = DateHelper.getCurrentMonth()
yearLabel.text = "月/\(DateHelper.getCurrentYear())"
updateUI()
}
@IBAction func unwindToPortal(segue: UIStoryboardSegue) {
if let _ = segue.sourceViewController as? AccountBookViewController {
setCurrentAccountBook()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let navi = segue.destinationViewController as? UINavigationController, vc = navi.visibleViewController as? AddBillViewController {
vc.portalController = self
} else if segue.identifier == "toBillStream" {
navigationItem.backBarButtonItem = UIBarButtonItem(title: "\(DateHelper.getCurrentYear())年流水", style: .Plain, target: nil, action: nil)
} else {
navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: nil, action: nil)
}
}
}
//MARK: - Methods
extension ViewController {
func adapteLabelsFont() {
adapteLabelFont(todayExpenseLabel)
adapteLabelFont(todayConsumeTypeLabel)
adapteLabelFont(todayCommentLabel)
adapteLabelFont(weekExpenseLabel)
adapteLabelFont(monthExpense)
adapteLabelFont(monthIncomeLabel)
adapteLabelFont(yearExpenseLabel)
adapteLabelFont(yearIncomeLabel)
}
func updateUI() {
renderChart() //// 设置柱状图数据
updateTodayUI() //设置最近一笔支出或收入
updateCurrentWeekUI()
updateCurrentMonthUI()
updateCurrentYearUI()
}
func setDate() {
todayDisplayLabel.text = DateHelper.getCurrentDate()
weekDisplayLabel.text = "\(DateHelper.getStartWeekDisplayStringFromCurrentWeek())-\(DateHelper.getOverWeekDisplayStringFromCurrentWeek())"
monthDisplayLabel.text = "\(DateHelper.getStartMonthDisplayStringFromCurrentMonth())-\(DateHelper.getOverMonthDisplayStringFromCurrentMonth())"
yearDisplayLabel.text = "\(DateHelper.getCurrentYear())\(DateHelper.YearStr)"
}
func adapteLabelFont(label: UILabel) {
if screenSize.width == 320 && screenSize.height == 480 {
let fontSize = label.font.pointSize * 0.85
label.font = UIFont.systemFontOfSize(fontSize)
}
}
func adapteRmbLabels(labels: [UILabel]) {
if screenSize.width == 320 && screenSize.height == 480 {
for label in labels {
label.hidden = true
}
}
}
func numberCountingAnimatingWithLabel(labels: [UICountingLabel]) {
for label in labels {
let number: Float = Float(label.text!)!
if number == 0.0 {
continue
}
label.animationDuration = 1
label.format = "%.2f"
label.countFromZeroTo(CGFloat(number))
}
}
func renderChart() {
let data = portalViewModel.getChartDataByCurrentMonth()
barChartController = FWChartController(viewForChart: columnChartView, chartStyle: .BarChart(label: "test"), data: data, title: "")
barChartController?.animate()
}
// 设置首页账本相关的内容
func setCurrentAccountBook() {
let accountBookTitle = portalViewModel.getCurrentAccountBookTitle()
currentAccountBookLabel.text = accountBookTitle
}
func updateTodayUI() {
let latestBill = portalViewModel.getLatestBill()
todayConsumeTypeLabel.text = "最近一笔 \(latestBill.consumeptionTypeName) \(latestBill.money)"
todayCommentLabel.text = latestBill.comment
todayExpenseLabel.text = "\(portalViewModel.getTodayTotalExpense())"
numberCountingAnimatingWithLabel([todayExpenseLabel])
}
func updateCurrentWeekUI() {
weekExpenseLabel.text = "\(portalViewModel.getCurrentWeekExpense())"
numberCountingAnimatingWithLabel([weekExpenseLabel])
}
func updateCurrentMonthUI() {
monthExpense.text = "\(portalViewModel.getCurrentMonthExpense())"
monthIncomeLabel.text = "\(portalViewModel.getCurrentMonthIncome())"
numberCountingAnimatingWithLabel([monthExpense, monthIncomeLabel])
}
func updateCurrentYearUI() {
yearExpenseLabel.text = "\(portalViewModel.getCurrentYearExpense())"
yearIncomeLabel.text = "\(portalViewModel.getCurrentYearIncome())"
numberCountingAnimatingWithLabel([yearExpenseLabel, yearIncomeLabel])
}
}
| [
-1
] |
d81a8d193b88ebbb5659ea661f60dc9d27f50e21 | 785dba9ba61f16ff24f41cab5740f929d8c96c6b | /News App/Helpers/UIAlertController + Extension.swift | 2fba8e1a9c310350cb8294050b2fd273d5707efb | [] | no_license | junker098/News-App | c61e5f180f7c9894b482cad80afd9aa4c0516af6 | 28a1aa5ccabfd406c00b86d44deeacd2b6afba53 | refs/heads/master | 2023-01-05T21:28:18.791240 | 2020-10-28T10:46:05 | 2020-10-28T10:46:05 | 307,497,705 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 583 | swift | //
// UIAlertController + Extension.swift
// News App
//
// Created by Юрий Могорита on 26.10.2020.
// Copyright © 2020 Yuri Mogorita. All rights reserved.
//
import Foundation
import UIKit
extension ArticlesViewController {
func showAlert(message: String) {
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
}
}
| [
-1
] |
9d7416c90c5cc06871e826a34fe41fee5cd3612f | 48ae2fe64db0553c55c60307e25d46251508d565 | /Mass Converter/MassConverter/ViewController.swift | a1363d2d2be7299b832ac1d26e5989675ea24981 | [] | no_license | HudaAlshammari/week-04_HW_TextField_Delegate | 72727233a9f03083b2d19090848bbe2483720500 | e6ec058e887b1e05015dddd994fbbcb7706ba948 | refs/heads/main | 2023-08-23T09:54:59.799616 | 2021-10-27T17:54:35 | 2021-10-27T17:54:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,206 | swift | //
// ViewController.swift
// MassConverter
//
// Created by Huda N S on 20/03/1443 AH.
//
import UIKit
enum ConversionType {
case KG
case Pound
}
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var conversionLabel: UILabel!
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var segmentControl: UISegmentedControl!
var conversionType = ConversionType.KG
func convertToKG( pound : Double) -> Double{
return pound*2.2
}
func convertToPound( kg : Double) -> Double{
return kg*0.45
}
override func viewDidLoad() {
super.viewDidLoad()
inputTextField.delegate = self
}
@IBAction func dismissKeyboard() {
inputTextField.resignFirstResponder()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
if textField.text!.count > 5 && string.count > 0{
return false
}
else {
return true
}
}
@IBAction func Segment1(_ sender: Any) {
inputTextField.text = ""
switch segmentControl.selectedSegmentIndex {
case 0: conversionType = .KG
conversionLabel.text = "0.0 Pounds"
case 1: conversionType = .Pound
conversionLabel.text = "0.0 KG"
default: conversionType = .KG
conversionLabel.text = "0.0 Pounds"
}
}
@IBAction func TextFile(_ sender: Any) {
var amountValue = 0.0
amountValue = Double(inputTextField.text ?? "0.0") ?? 0.0
switch conversionType {
case .KG:
let convertedValue = convertToKG(pound: amountValue)
conversionLabel.text = "\(convertedValue) Pounds"
case .Pound:
let convertedValue = convertToPound(kg: amountValue)
conversionLabel.text = "\(convertedValue) KG"
}
}
@objc func dismissTap() {
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder()
}
}
| [
-1
] |
e2c1a0acb898e0c2a47110cdd3b5cab9a5fcfc5e | 30122f6a403f50be91b34452651679db33065630 | /greedycats/support/Geometry.swift | 27447a44a3e782d485edd611c2b910b383723d35 | [
"MIT"
] | permissive | dyuste/greedy-cats-lake-app-ios | 402d78664d437ffac8e2ec5d94437a5ea8a04c28 | 76a3e8a3dd1e82c8141da116dab7b879007a7cbd | refs/heads/master | 2021-03-13T03:46:51.907151 | 2017-05-16T20:07:33 | 2017-05-16T20:07:33 | 91,499,212 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 770 | swift | //
// Geometry.swift
// greedycats
//
// Created by David Yuste on 10/11/15.
// Copyright (c) 2015 David Yuste Romero
//
// THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
// OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
//
// Permission is hereby granted to use or copy this program
// for any purpose, provided the above notices are retained on all copies.
// Permission to modify the code and to distribute modified code is granted,
// provided the above notices are retained, and a notice that the code was
// modified is included with the above copyright notice.
//
import Foundation
import UIKit
func distanceBetween(point p1:CGPoint, andPoint p2:CGPoint) -> CGFloat {
return sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2))
}
| [
-1
] |
f97c7be92b1049759d3f64e630781db22e2881d0 | a124e1d594680e175e24529b7341c5f58c4d58d7 | /DbClient/DbConnectViewModel.swift | 6cc1bd27a3cde35c648d48fa36822faa10e17eec | [] | no_license | fajdof/DbClient | ef235189078193fc54408717b569ce3477b366ea | 54cc191efb1a60f95ce54a3084bd178fa7c32a0f | refs/heads/master | 2021-03-24T11:45:57.904250 | 2017-06-14T15:04:07 | 2017-06-14T15:04:07 | 73,552,392 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 6,615 | swift | //
// DbConnectViewModel.swift
// DbClient
//
// Created by Filip Fajdetic on 25/11/2016.
// Copyright © 2016 Filip Fajdetic. All rights reserved.
//
import Foundation
class DbConnectViewModel {
let hostName = "rppp.fer.hr:3000"
let username = "rppp"
let password = "r3p##2011"
let dbName = "Firma"
let selectQuery = "SELECT * FROM "
var items: [Item] = []
var docs: [Document] = []
var countries: [Country] = []
var places: [Place] = []
var people: [Person] = []
var partners: [Partner] = []
var units: [Unit] = []
var companies: [Company] = []
var idsToItems: [Int: Item] = [:]
var idsToCountries: [String: Country] = [:]
var idsToPlaces: [Int: Place] = [:]
var idsToDocs: [Int: Document] = [:]
var idsToPartners: [Int: Partner] = [:]
var idsToCompanies: [Int: Company] = [:]
var idsToPeople: [Int: Person] = [:]
var client: SQLClient?
init() {
client = SQLClient.sharedInstance()
}
func connectToSqlServer(completion: @escaping (_ completed: Bool) -> ()) {
client?.connect(hostName, username: username, password: password, database: dbName, completion: { (completed) in
completion(completed)
})
}
func executeQuery(table: Tables, completion: @escaping (_ dbData: [Any]?) -> ()) {
client?.execute(selectQuery + table.rawValue, completion: { (dbData) in
completion(dbData)
})
}
func proccessQuery(data: [Any], type: Tables) {
for table in data {
if let tab = table as? Array<Dictionary<String, AnyObject>> {
for row in tab {
parseRow(row: row, type: type)
}
}
}
}
func parseRow(row: Dictionary<String, AnyObject>, type: Tables) {
switch type {
case .Item:
if let item = Item(JSON: row) {
items.append(item)
if let code = item.code {
idsToItems[code] = item
}
}
case .Document:
if let doc = Document(JSON: row) {
docs.append(doc)
if let docId = doc.docId {
idsToDocs[docId] = doc
}
}
case .Country:
if let country = Country(JSON: row) {
countries.append(country)
if let mark = country.mark {
idsToCountries[mark] = country
}
}
case .Place:
if let place = Place(JSON: row) {
places.append(place)
if let id = place.id {
idsToPlaces[id] = place
}
}
case .Person:
if let person = Person(JSON: row) {
people.append(person)
if let id = person.id {
idsToPeople[id] = person
}
}
case .Partner:
if let partner = Partner(JSON: row) {
partners.append(partner)
if let partnerId = partner.partnerId {
idsToPartners[partnerId] = partner
}
}
case .Unit:
if let unit = Unit(JSON: row) {
units.append(unit)
}
case .Company:
if let company = Company(JSON: row) {
companies.append(company)
if let id = company.companyId {
idsToCompanies[id] = company
}
}
}
}
func connectUnitsWithItemsAndDocs(completion: @escaping () -> ()) {
DispatchQueue.global().async { [weak self] in
guard let `self` = self else { return }
for unit in self.units {
if let itemCode = unit.itemCode {
let item = self.idsToItems[itemCode]
unit.item = item
item?.units.append(unit)
}
if let docId = unit.docId {
let doc = self.idsToDocs[docId]
unit.document = doc
doc?.units.append(unit)
}
}
DispatchQueue.main.async {
completion()
}
}
}
func connectCountriesAndPlaces(completion: @escaping () -> ()) {
DispatchQueue.global().async { [weak self] in
guard let `self` = self else { return }
for place in self.places {
if let countryCode = place.countryCode {
let country = self.idsToCountries[countryCode]
place.country = country
country?.places.append(place)
}
}
DispatchQueue.main.async {
completion()
}
}
}
func connectPlacesAndPartners(completion: @escaping () -> ()) {
DispatchQueue.global().async { [weak self] in
guard let `self` = self else { return }
for partner in self.partners {
if let partnerAddressId = partner.partnerAddressId {
let partnerPlace = self.idsToPlaces[partnerAddressId]
partner.partnerPlace = partnerPlace
partnerPlace?.partners.insert(partner)
}
if let shipmentAddressId = partner.shipmentAddressId {
let shipmentPlace = self.idsToPlaces[shipmentAddressId]
partner.shipmentPlace = shipmentPlace
shipmentPlace?.partners.insert(partner)
}
}
DispatchQueue.main.async {
completion()
}
}
}
func connectDocsWithPartnersAndPreviousDocs(completion: @escaping () -> ()) {
DispatchQueue.global().async { [weak self] in
guard let `self` = self else { return }
for doc in self.docs {
if let partnerId = doc.partnerId {
let partner = self.idsToPartners[partnerId]
if let company = self.idsToCompanies[partnerId] {
doc.partner = company
}
if let person = self.idsToPeople[partnerId] {
doc.partner = person
}
partner?.docs.append(doc)
}
if let docBeforeId = doc.docBeforeId {
let docBefore = self.idsToDocs[docBeforeId]
doc.docBefore = docBefore
}
}
DispatchQueue.main.async {
completion()
}
}
}
func addPartnerPropertiesToPerson(completion: @escaping () -> ()) {
DispatchQueue.global().async { [weak self] in
guard let `self` = self else { return }
for person in self.people {
if let id = person.id {
if let partner = self.idsToPartners[id] {
self.addPartnerProperties(to: person, partnerOrigin: partner)
}
}
}
DispatchQueue.main.async {
completion()
}
}
}
func addPartnerPropertiesToCompany(completion: @escaping () -> ()) {
DispatchQueue.global().async { [weak self] in
guard let `self` = self else { return }
for company in self.companies {
if let id = company.companyId {
if let partner = self.idsToPartners[id] {
self.addPartnerProperties(to: company, partnerOrigin: partner)
}
}
}
DispatchQueue.main.async {
completion()
}
}
}
func addPartnerProperties(to partnerObject: Partner, partnerOrigin: Partner) {
partnerObject.oib = partnerOrigin.oib
partnerObject.docs = partnerOrigin.docs
partnerObject.partnerAddress = partnerOrigin.partnerAddress
partnerObject.partnerAddressId = partnerOrigin.partnerAddressId
partnerObject.shipmentAddress = partnerOrigin.shipmentAddress
partnerObject.shipmentAddressId = partnerOrigin.shipmentAddressId
partnerObject.shipmentPlace = partnerOrigin.shipmentPlace
partnerObject.partnerPlace = partnerOrigin.partnerPlace
partnerObject.type = partnerOrigin.type
}
}
| [
-1
] |
d0efa85b22e06fffb24f2b294e6ff4e347bfa253 | 705b03e373265ea0496e8c2a0ae6799e021b1195 | /swift-Demo/Project03- FindMyLocation/Project03- FindMyLocationUITests/Project03__FindMyLocationUITests.swift | 967b6703441a9c96ed059eeff39d9709ecf29f81 | [] | no_license | zhouxinfang/SwiftFortyDaysDemo | f09c4bfd29806a124b4a8651c359c7173c484e2c | 2eb61118363cc5845573915bc500d86b3f37368b | refs/heads/master | 2021-08-22T20:48:12.208020 | 2017-12-01T07:53:03 | 2017-12-01T07:53:03 | 107,066,063 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,304 | swift | //
// Project03__FindMyLocationUITests.swift
// Project03- FindMyLocationUITests
//
// Created by zhouxinfang on 2017/10/18.
// Copyright © 2017年 zhouxinfang. All rights reserved.
//
import XCTest
class Project03__FindMyLocationUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| [
333827,
182277,
243720,
282634,
313356,
155665,
305173,
237599,
241695,
223269,
229414,
292901,
354342,
102441,
315433,
278571,
313388,
325675,
102446,
282671,
354346,
229425,
124974,
243763,
241717,
180279,
229431,
215095,
319543,
213051,
288829,
325695,
288835,
286787,
307269,
237638,
313415,
239689,
233548,
311373,
315468,
278607,
196687,
311377,
354386,
223317,
315477,
368732,
180317,
323678,
315488,
321632,
45154,
280676,
313446,
307306,
194667,
217194,
278637,
233578,
288878,
319599,
278642,
284789,
131190,
288890,
215165,
131199,
278669,
235661,
333968,
241809,
323730,
278676,
311447,
153752,
327834,
284827,
278684,
329884,
299166,
278690,
311459,
233635,
215204,
333990,
284840,
299176,
284843,
278703,
323761,
184498,
278707,
278713,
223418,
280761,
258233,
295099,
180409,
227517,
280767,
299197,
299202,
139459,
309443,
176325,
338118,
227525,
299208,
301255,
280779,
282832,
227536,
301270,
229591,
301271,
280792,
147679,
311520,
325857,
147680,
356575,
280803,
307431,
338151,
182503,
319719,
317676,
286957,
125166,
125170,
395511,
313595,
184574,
309504,
125184,
217352,
125192,
125197,
194832,
227601,
125200,
319764,
278805,
338196,
125204,
334104,
315674,
282908,
311582,
299294,
282912,
233761,
278817,
125215,
211239,
282920,
334121,
317738,
325930,
311596,
338217,
125225,
321839,
336177,
315698,
98611,
125236,
282938,
307514,
278843,
127292,
168251,
287040,
319812,
311622,
280903,
227655,
323914,
201037,
383309,
282959,
229716,
250196,
289109,
168280,
379224,
323934,
391521,
239973,
381286,
285031,
313703,
416103,
280938,
242027,
242028,
321901,
354671,
278895,
287089,
250227,
199030,
315768,
291193,
139641,
223611,
291194,
313726,
311679,
211327,
291200,
158087,
313736,
227721,
242059,
311692,
106893,
227730,
285074,
240020,
190870,
249606,
190872,
291225,
315798,
293275,
285083,
317851,
242079,
285089,
293281,
289185,
305572,
156069,
301482,
289195,
375211,
334259,
338359,
299449,
319931,
311739,
293309,
278974,
336319,
311744,
317889,
291266,
278979,
336323,
278988,
129484,
281038,
281039,
278992,
283089,
283088,
289229,
326093,
279000,
176602,
242138,
160224,
279009,
291297,
285152,
369121,
188899,
279014,
242150,
302539,
279017,
195044,
311787,
334315,
319976,
281071,
319986,
236020,
279030,
311800,
293368,
279033,
317949,
322396,
279042,
283138,
233987,
287237,
324098,
334345,
309770,
340489,
342537,
279053,
322057,
283154,
303634,
279060,
279061,
303635,
182802,
279066,
188954,
322077,
291359,
342560,
293420,
236080,
283185,
289328,
279092,
23093,
234037,
244279,
244280,
338491,
234044,
340539,
301635,
309831,
55880,
322119,
377419,
303693,
281165,
301647,
281170,
326229,
309847,
189016,
115287,
244311,
332379,
111197,
295518,
287327,
242274,
244326,
279143,
279150,
281200,
287345,
287348,
301688,
189054,
303743,
297600,
287359,
291455,
301702,
279176,
311944,
334473,
344714,
316044,
311950,
316048,
326288,
316050,
311953,
287379,
336531,
295575,
227991,
289435,
303772,
205469,
221853,
285348,
314020,
340645,
279207,
295591,
176810,
248494,
279215,
285360,
293552,
285362,
299698,
287412,
166581,
295598,
154295,
279218,
164532,
303802,
314043,
287418,
66243,
291529,
287434,
225996,
363212,
287438,
135888,
279249,
242385,
164561,
303826,
279253,
369365,
369366,
158424,
230105,
299737,
322269,
338658,
342757,
295653,
289511,
230120,
234216,
330473,
285419,
330476,
289517,
279278,
312046,
215790,
170735,
125683,
230133,
199415,
342775,
234233,
242428,
279293,
205566,
289534,
35584,
299777,
322302,
228099,
285443,
375552,
291591,
295688,
322312,
346889,
285450,
312076,
326413,
285457,
295698,
291605,
166677,
207639,
283418,
285467,
221980,
281378,
234276,
336678,
283431,
203560,
279337,
262952,
262953,
293673,
289580,
262957,
164655,
301872,
242481,
234290,
303921,
318251,
285493,
230198,
328495,
285496,
301883,
201534,
289599,
281407,
342846,
222017,
295745,
293702,
318279,
283466,
281426,
279379,
244569,
234330,
201562,
281434,
295769,
275294,
230239,
301919,
279393,
293729,
230238,
281444,
357219,
279398,
303973,
351078,
349025,
177002,
308075,
242540,
242542,
310132,
295797,
228214,
207735,
201590,
295799,
279418,
177018,
269179,
308093,
336765,
314240,
291713,
158594,
330627,
340865,
240517,
287623,
228232,
416649,
279434,
320394,
316299,
252812,
234382,
308111,
308113,
293780,
310166,
289691,
209820,
240543,
283551,
310177,
189349,
289704,
279465,
293801,
326571,
304050,
177074,
326580,
289720,
326586,
289723,
189373,
213956,
359365,
19398,
345030,
213961,
127945,
279499,
211913,
56270,
191445,
304086,
183254,
207839,
340960,
234469,
314343,
304104,
123880,
340967,
324587,
234476,
183276,
289773,
320492,
320495,
203758,
287730,
248815,
240631,
214009,
201721,
312313,
312317,
234499,
418819,
293894,
330759,
322571,
230411,
330766,
320526,
234513,
238611,
140311,
293911,
238617,
197658,
316441,
326684,
336930,
132140,
113710,
189487,
281647,
322609,
318515,
312372,
203829,
238646,
300087,
238650,
320571,
21567,
308288,
336962,
160834,
314437,
349254,
238663,
300109,
234578,
207954,
250965,
296023,
205911,
339031,
314458,
156763,
281698,
281699,
285795,
230500,
250982,
322664,
228457,
279659,
318571,
234606,
300145,
230514,
238706,
187508,
312435,
279666,
300147,
302202,
285819,
314493,
285823,
150656,
234626,
279686,
222344,
285833,
285834,
234635,
228492,
318602,
337037,
177297,
187539,
347286,
308375,
188293,
324761,
285850,
296091,
119965,
234655,
300192,
302239,
339106,
306339,
234662,
300200,
302251,
208044,
238764,
249003,
3243,
322733,
294069,
324790,
300215,
64699,
294075,
228541,
339131,
343230,
283841,
148674,
283846,
312519,
279752,
283849,
148687,
290001,
189651,
316628,
279766,
189656,
279775,
304352,
298209,
304353,
339167,
279780,
310496,
228587,
279789,
290030,
302319,
234741,
316661,
208123,
292092,
279803,
228608,
320769,
322826,
242955,
312588,
177420,
318732,
126229,
318746,
320795,
320802,
130342,
304422,
130344,
130347,
292145,
298290,
208179,
312628,
345398,
300342,
159033,
222523,
286012,
181568,
279872,
279874,
300355,
193858,
294210,
372039,
304457,
230730,
345418,
337228,
296269,
222542,
224591,
234830,
238928,
296274,
331091,
318804,
150868,
314708,
283990,
357720,
300378,
300379,
294236,
316764,
292194,
230757,
281958,
134504,
306541,
314734,
284015,
296304,
312688,
234864,
230772,
314740,
314742,
327030,
310650,
224637,
306558,
290176,
306561,
179586,
337280,
243073,
314752,
294278,
314759,
296328,
296330,
298378,
368012,
314765,
318860,
304523,
9618,
279955,
306580,
314771,
224662,
112019,
282008,
314776,
234902,
318876,
282013,
290206,
343457,
148899,
298406,
282023,
245160,
279979,
279980,
241067,
314797,
286128,
173492,
279988,
286133,
284086,
259513,
310714,
284090,
228796,
302523,
54719,
302530,
280003,
228804,
292291,
306630,
310725,
300488,
306634,
370122,
310731,
300490,
280011,
310735,
339403,
337359,
329168,
312785,
280020,
222674,
329170,
280025,
310747,
239069,
144862,
286176,
187877,
310758,
320997,
280042,
280043,
191980,
300526,
329198,
337391,
282097,
308722,
296434,
306678,
191991,
288248,
40439,
286201,
300539,
288252,
210429,
359931,
290304,
245249,
228868,
292359,
218632,
302602,
323083,
230922,
294413,
359949,
304655,
323088,
329231,
282132,
302613,
282135,
316951,
175640,
374297,
302620,
222754,
306730,
312879,
230960,
288305,
239159,
290359,
323132,
235069,
157246,
288319,
288322,
280131,
349764,
310853,
282182,
194118,
288328,
292424,
292426,
286281,
124486,
333389,
224848,
349780,
290391,
128600,
235096,
239192,
196184,
306777,
212574,
99937,
204386,
300643,
323171,
300645,
282214,
345697,
312937,
204394,
224874,
243306,
312941,
138862,
206447,
310896,
314997,
294517,
290425,
288377,
339579,
337533,
325246,
333438,
280193,
282244,
239238,
288391,
282248,
286344,
323208,
179853,
286351,
188049,
229011,
239251,
280217,
323226,
179868,
229021,
318247,
302751,
282272,
198304,
245413,
282279,
298664,
298666,
317102,
286387,
300725,
286392,
300729,
302778,
306875,
280252,
280253,
282302,
323262,
286400,
321217,
296636,
280259,
321220,
282309,
323265,
239305,
280266,
306891,
296649,
212684,
302798,
9935,
241360,
282321,
313042,
286419,
333522,
241366,
280279,
282330,
18139,
280285,
294621,
282336,
325345,
294629,
153318,
337638,
333543,
12009,
181992,
282347,
288492,
282349,
34547,
67316,
323315,
286457,
284410,
313082,
200444,
288508,
282366,
286463,
319232,
288515,
280326,
282375,
323335,
284425,
300810,
282379,
216844,
116491,
284430,
280333,
300812,
161553,
124691,
284436,
278292,
278294,
282390,
116502,
118549,
321308,
321309,
282399,
341791,
282401,
339746,
241440,
186148,
186149,
216868,
241447,
315172,
333609,
286507,
294699,
284460,
280367,
300849,
282418,
280373,
282424,
280377,
319289,
321338,
282428,
280381,
345918,
413500,
241471,
280386,
325444,
280391,
153416,
315209,
325449,
342705,
280396,
159563,
307024,
325460,
237397,
307030,
18263,
341846,
317268,
188250,
241494,
284508,
300893,
307038,
370526,
237411,
284515,
276326,
282471,
296807,
292713,
282476,
292719,
296815,
313200,
325491,
313204,
317305,
317308,
339840,
315265,
280451,
325508,
327556,
333700,
282503,
67464,
243592,
305032,
325514,
350091,
350092,
315272,
311183,
184207,
315275,
282517,
294806,
350102,
214936,
294808,
337816,
239515,
333727,
298912,
319393,
214943,
294820,
118693,
333734,
219046,
284584,
294824,
298921,
313257,
292783,
126896,
200628,
300983,
343993,
288698,
98240,
294849,
214978,
280517,
280518,
214983,
282572,
282573,
153553,
231382,
323554,
292835,
190437,
292838,
294887,
317416,
174058,
278507,
311277,
296942,
124912,
327666,
278515,
325620,
239610
] |
7d729e73b6876259ea7fc90fd18044be220fa8cf | 350e0bef058c7f6b7aa22ccc73aa65501c75551c | /desafio-ios/desafio-ios/Views/StatementDetail/DetailViewModel.swift | 6dd12383a5e5c08e4c1aedc63c972948840da6a3 | [] | no_license | gustavotravassos/desafio-ios | 46324a1660ff14777d876a5a69b63e48920ba8ac | 466c6fc274460c7f06a4d775d35dde46db2c8a54 | refs/heads/main | 2023-02-19T06:46:45.410470 | 2021-01-15T15:49:45 | 2021-01-15T15:49:45 | 329,057,121 | 0 | 0 | null | 2021-01-12T17:10:52 | 2021-01-12T17:10:51 | null | UTF-8 | Swift | false | false | 1,999 | swift | //
// DetailViewModel.swift
// desafio-ios
//
// Created by Gustavo Igor Gonçalves Travassos on 12/01/21.
//
import Foundation
// MARK: - Class
final class DetailViewModel {
// MARK: - Private variables
private let coordinator: Coordinator
private let service = Service()
private let id: String
// MARK: - Internal variables
var model: Statement?
var dataArray: [(title: String, description: String)]
// MARK: - Initializers
init(coordinator: Coordinator, id: String) {
self.coordinator = coordinator
self.id = id
self.dataArray = []
}
}
extension DetailViewModel {
// MARK: - Internal methods
func getStatementDetail(completion: @escaping (Statement) -> Void) {
service.getStatementDetail(id: id) { response, error in
completion(response)
}
}
func setupDataArray() {
guard let model = model else { return }
var amount = "\(String(model.amount).formatToCurrency)"
amount = amount.replacingOccurrences(of: ".", with: ",")
dataArray.append((title: "Tipo de movimentação", description: model.transferenceType))
dataArray.append((title: "Tipo de Valor", description: amount))
if let to = model.to {
dataArray.append((title: "Recebedor", description: to))
}
if let bankName = model.bankName {
dataArray.append((title: "Instituição bancária", description: bankName))
}
dataArray.append((title: "Data/Hora",
description: model.createdAt.formatDate(inputSymbols: "yyyy-MM-dd'T'HH:mm:ss'Z'",
outputSymbols: "dd/MM/yyyy - HH:mm:ss")))
if let authentication = model.authentication {
dataArray.append((title: "Autenticação", description: authentication))
}
}
}
| [
-1
] |
4d9a85bf02ad6940e2a519af0bb9338f69631b3f | 723d66df6a4d6e5c05785b659f70b0913738f5cd | /Medha/ViewControllers/ResetPasswordViewController/ResetPasswordViewController.swift | 45b7f7be03ce9961cf6720df511eec70e88555d5 | [] | no_license | SameeraNallamalli/medhas-master1 | de1a14d20e7fdc72866808f4c9dde7f7c9c0716c | 97538c12cae0693a1443acac52a18766b53e9c08 | refs/heads/master | 2023-03-20T08:15:13.862390 | 2021-03-06T07:55:58 | 2021-03-06T07:55:58 | 345,036,531 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,561 | swift | //
// ResetPasswordViewController.swift
// Medha
//
// Created by Ganesh on 12/12/19.
// Copyright © 2019 Ganesh Musini. All rights reserved.
//
import UIKit
class ResetPasswordViewController: UIViewController {
@IBOutlet weak var fieldEnterPassword: UITextField!
@IBOutlet weak var fieldReEnterPassword: UITextField!
@IBOutlet weak var btnSubmit: UIButton!
var userID = ""
override func viewDidLoad() {
super.viewDidLoad()
self.addGradientBGColor()
fieldEnterPassword.addBorder()
fieldReEnterPassword.addBorder()
btnSubmit.addColors(titleColor: .white, bgColor: .clear, borderColor: .clear)
self.navigationItem.setHidesBackButton(true, animated: true)
}
@IBAction func btnSubmitClicked(_ sender: UIButton)
{
if fieldEnterPassword.text == "" || fieldReEnterPassword.text == ""
{
AlertView.shared.showAlert(message: Alert_Empty_Fields, toView: self, ButtonTitles: ["OK"], ButtonActions: [nil])
}
else
{
if fieldEnterPassword.text == fieldReEnterPassword.text
{
self.VerifyPassword()
}
else
{
AlertView.shared.showAlert(message: Alert_SetPass_NotMatch, toView: self, ButtonTitles: ["OK"], ButtonActions: [nil])
}
}
}
func popToLogin()
{
let popVCs = self.navigationController?.viewControllers
if popVCs?.count ?? 0 > 0
{
for(_,VC) in (popVCs?.enumerated())!
{
if VC.isKind(of: LoginViewController.self)
{
let loginVC = VC as! LoginViewController
self.navigationController?.popToViewController(loginVC, animated: true)
}
}
}
}
func VerifyPassword()
{
CommonObject().showHUD()
let paramsDict = ["email" : userID, "password" :fieldEnterPassword.text!] as [String : Any]
CommonObject().getDataFromServer(urlString: updatePassword, method: .POST, model: Success_Error.self, paramsDict: paramsDict) { (data, resp, err) in
if err == nil && resp != nil
{
print(data!)
if data?.status == "error"
{
DispatchQueue.main.async {
AlertView.shared.showAlert(message: data?.msg ?? "OOPS!", toView: self, ButtonTitles: ["OK"], ButtonActions: [nil])
CommonObject().dismisHUD()
}
}
else if data?.status == "success"
{
CommonObject().dismisHUD()
DispatchQueue.main.async {
AlertView.shared.showAlert(message: Alert_SetPass_Success, toView: self, ButtonTitles: ["OK"], ButtonActions: [{action1 in
CommonObject().showHUD()
self.popToLogin()
CommonObject().dismisHUD()
},nil])
}
}
}
else
{
if err != nil
{
if resp == nil
{
DispatchQueue.main.async {
AlertView.shared.showAlert(message: err ?? "error in network", toView: self, ButtonTitles: ["OK"], ButtonActions: [nil])
}
}
else
{
DispatchQueue.main.async {
let statusCode = resp as! HTTPURLResponse
AlertView.shared.showAlert(message: "Erro in network\nStatus Code :\(statusCode.statusCode)", toView: self, ButtonTitles: ["OK"], ButtonActions: [nil])
}
}
CommonObject().dismisHUD()
}
}
}
}
}
extension ResetPasswordViewController : UITextFieldDelegate
{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
fieldEnterPassword.resignFirstResponder()
fieldReEnterPassword.resignFirstResponder()
return true
}
}
| [
-1
] |
8f602d1e5e496d7902e2624b7cd6f96a5c052cd1 | 9b1027d642fe7fa2991042d4cf790aeed6fadb3f | /MarvelComicsTime/View/Cells/Comic/ComicTableViewCell.swift | 05a6c245b84854ade62234ce4ce1631d3432d2a7 | [] | no_license | rodrigaoLeme/marvelComics | 83b2b5ded8c1a9cc5fbba477a6b8074ec4aa6370 | 7225cd7d17db69b8dac22ccdfb4fc724aebe1d73 | refs/heads/master | 2023-04-01T15:48:50.560419 | 2021-04-13T20:44:38 | 2021-04-13T20:44:38 | 357,680,948 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 998 | swift | //
// ComicTableViewCell.swift
// MarvelComicsTime
//
// Created by Leonardo Evagelista on 08/12/20.
//
import UIKit
class ComicTableViewCell: UITableViewCell {
@IBOutlet weak var comicImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
static let identifier = "ComicTableViewCell"
static func nib() -> UINib {
return UINib(nibName: "ComicTableViewCell", bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setup(comic: Comic) {
titleLabel.text = comic.title
descriptionLabel.text = comic.description
if let image = comic.thumbnail{
if let path = image.path{
comicImageView.setImage(with: "\(path).\(image.type!)")
}
}
}
}
| [
-1
] |
eeed9cbef398d0d10ed469587adcad3a5c97170a | 161aadd9900c2566f91f7e249dea41e1e45c8cec | /Managers/UTMRegistryEntry.swift | 217a0f6ec51cacb279dbd5a5782f3c9dc71393e1 | [
"BSD-3-Clause",
"GPL-1.0-or-later",
"Apache-2.0",
"MIT"
] | permissive | fengjixuchui/UTM | 605bc20d3a2b3bb74c153f85cd738ce5c8e79e2c | 652eeb294d2cf62320550f851f8d92f105dd226b | refs/heads/main | 2023-03-18T18:47:59.058036 | 2023-03-11T06:15:48 | 2023-03-11T06:15:48 | 242,482,375 | 0 | 0 | Apache-2.0 | 2020-07-13T02:41:52 | 2020-02-23T08:31:30 | Objective-C | UTF-8 | Swift | false | false | 17,818 | swift | //
// Copyright © 2022 osy. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
@objc class UTMRegistryEntry: NSObject, Codable, ObservableObject {
@Published private var _name: String
@Published private var _package: File
private(set) var uuid: UUID
@Published private var _isSuspended: Bool
@Published private var _externalDrives: [String: File]
@Published private var _sharedDirectories: [File]
@Published private var _windowSettings: [Int: Window]
@Published private var _terminalSettings: [Int: Terminal]
@Published private var _hasMigratedConfig: Bool
@Published private var _macRecoveryIpsw: File?
private enum CodingKeys: String, CodingKey {
case name = "Name"
case package = "Package"
case uuid = "UUID"
case isSuspended = "Suspended"
case externalDrives = "ExternalDrives"
case sharedDirectories = "SharedDirectories"
case windowSettings = "WindowSettings"
case terminalSettings = "TerminalSettings"
case hasMigratedConfig = "MigratedConfig"
case macRecoveryIpsw = "MacRecoveryIpsw"
}
init(newFrom vm: UTMVirtualMachine) {
let package: File?
let path = vm.path
if let wrappedVM = vm as? UTMWrappedVirtualMachine {
package = try? File(path: path.path, bookmark: wrappedVM.bookmark)
} else {
package = try? File(url: path)
}
_name = vm.config.name
_package = package ?? File(path: path.path)
uuid = vm.config.uuid
_isSuspended = false
_externalDrives = [:]
_sharedDirectories = []
_windowSettings = [:]
_terminalSettings = [:]
_hasMigratedConfig = false
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
_name = try container.decode(String.self, forKey: .name)
_package = try container.decode(File.self, forKey: .package)
uuid = try container.decode(UUID.self, forKey: .uuid)
_isSuspended = try container.decode(Bool.self, forKey: .isSuspended)
_externalDrives = (try container.decode([String: File].self, forKey: .externalDrives)).filter({ $0.value.isValid })
_sharedDirectories = try container.decode([File].self, forKey: .sharedDirectories).filter({ $0.isValid })
_windowSettings = try container.decode([Int: Window].self, forKey: .windowSettings)
_terminalSettings = try container.decodeIfPresent([Int: Terminal].self, forKey: .terminalSettings) ?? [:]
_hasMigratedConfig = try container.decodeIfPresent(Bool.self, forKey: .hasMigratedConfig) ?? false
_macRecoveryIpsw = try container.decodeIfPresent(File.self, forKey: .macRecoveryIpsw)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(_name, forKey: .name)
try container.encode(_package, forKey: .package)
try container.encode(uuid, forKey: .uuid)
try container.encode(_isSuspended, forKey: .isSuspended)
try container.encode(_externalDrives, forKey: .externalDrives)
try container.encode(_sharedDirectories, forKey: .sharedDirectories)
try container.encode(_windowSettings, forKey: .windowSettings)
try container.encode(_terminalSettings, forKey: .terminalSettings)
if _hasMigratedConfig {
try container.encode(_hasMigratedConfig, forKey: .hasMigratedConfig)
}
try container.encodeIfPresent(_macRecoveryIpsw, forKey: .macRecoveryIpsw)
}
func asDictionary() throws -> [String: Any] {
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let xml = try encoder.encode(self)
let dict = try PropertyListSerialization.propertyList(from: xml, format: nil)
return dict as! [String: Any]
}
}
protocol UTMRegistryEntryDecodable: Decodable {}
extension UTMRegistryEntry: UTMRegistryEntryDecodable {}
extension UTMRegistryEntryDecodable {
init(from dictionary: [String: Any]) throws {
let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)
let decoder = PropertyListDecoder()
self = try decoder.decode(Self.self, from: data)
}
}
// MARK: - Accessors
@MainActor extension UTMRegistryEntry {
var name: String {
get {
_name
}
set {
_name = newValue
}
}
var package: File {
get {
_package
}
set {
_package = newValue
}
}
var isSuspended: Bool {
get {
_isSuspended
}
set {
_isSuspended = newValue
}
}
var externalDrives: [String: File] {
get {
_externalDrives
}
set {
_externalDrives = newValue
}
}
var sharedDirectories: [File] {
get {
_sharedDirectories
}
set {
_sharedDirectories = newValue
}
}
var windowSettings: [Int: Window] {
get {
_windowSettings
}
set {
_windowSettings = newValue
}
}
var terminalSettings: [Int: Terminal] {
get {
_terminalSettings
}
set {
_terminalSettings = newValue
}
}
var hasMigratedConfig: Bool {
get {
_hasMigratedConfig
}
set {
_hasMigratedConfig = newValue
}
}
var macRecoveryIpsw: File? {
get {
_macRecoveryIpsw
}
set {
_macRecoveryIpsw = newValue
}
}
func setExternalDrive(_ file: File, forId id: String) {
externalDrives[id] = file
}
func updateExternalDriveRemoteBookmark(_ bookmark: Data, forId id: String) {
externalDrives[id]?.remoteBookmark = bookmark
}
func removeExternalDrive(forId id: String) {
externalDrives.removeValue(forKey: id)
}
func setSingleSharedDirectory(_ file: File) {
sharedDirectories = [file]
}
func updateSingleSharedDirectoryRemoteBookmark(_ bookmark: Data) {
if !sharedDirectories.isEmpty {
sharedDirectories[0].remoteBookmark = bookmark
}
}
func removeAllSharedDirectories() {
sharedDirectories = []
}
func update(copying other: UTMRegistryEntry) {
isSuspended = other.isSuspended
externalDrives = other.externalDrives
sharedDirectories = other.sharedDirectories
windowSettings = other.windowSettings
terminalSettings = other.terminalSettings
hasMigratedConfig = other.hasMigratedConfig
}
}
// MARK: - Migration from UTMViewState
extension UTMRegistryEntry {
/// Migrate from a view state
/// - Parameter viewState: View state to migrate
private func migrate(viewState: UTMLegacyViewState) {
var primaryWindow = Window()
if viewState.displayScale != .zero {
primaryWindow.scale = viewState.displayScale
}
if viewState.displayOriginX != .zero || viewState.displayOriginY != .zero {
primaryWindow.origin = CGPoint(x: viewState.displayOriginX,
y: viewState.displayOriginY)
}
primaryWindow.isKeyboardVisible = viewState.isKeyboardShown
primaryWindow.isToolbarVisible = viewState.isToolbarShown
if primaryWindow != Window() {
_windowSettings[0] = primaryWindow
}
_isSuspended = viewState.hasSaveState
if let sharedDirectoryBookmark = viewState.sharedDirectory, let sharedDirectoryPath = viewState.sharedDirectoryPath {
if let file = try? File(path: sharedDirectoryPath,
bookmark: sharedDirectoryBookmark) {
_sharedDirectories = [file]
} else {
logger.error("Failed to migrate shared directory \(sharedDirectoryPath) because bookmark is invalid.")
}
}
if let shortcutBookmark = viewState.shortcutBookmark {
_package.remoteBookmark = shortcutBookmark
}
for drive in viewState.allDrives() {
if let bookmark = viewState.bookmark(forRemovableDrive: drive), let path = viewState.path(forRemovableDrive: drive) {
let file = File(path: path, remoteBookmark: bookmark)
_externalDrives[drive] = file
}
}
}
/// Try to migrate from a view.plist or does nothing if it does not exist.
/// - Parameter viewStateURL: URL to view.plist
@objc func migrateUnsafe(viewStateURL: URL) {
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: viewStateURL.path) else {
return
}
guard let dict = try? NSDictionary(contentsOf: viewStateURL, error: ()) as? [AnyHashable : Any] else {
logger.error("Failed to parse legacy \(viewStateURL)")
return
}
let viewState = UTMLegacyViewState(dictionary: dict)
migrate(viewState: viewState)
try? fileManager.removeItem(at: viewStateURL) // delete view.plist
}
/// Try to migrate old bookmarks stored in config.plist or does nothing if not appliable.
/// - Parameter config: Config to migrate
@objc func migrate(fromConfig config: UTMConfigurationWrapper) {
#if os(macOS)
if let appleConfig = config.appleConfig {
Task { @MainActor in
if !hasMigratedConfig {
migrate(fromAppleConfig: appleConfig)
hasMigratedConfig = true
}
}
}
#endif
}
#if os(macOS)
/// Try to migrate bookmarks from an Apple VM config.
/// - Parameter config: Apple config to migrate
@MainActor func migrate(fromAppleConfig config: UTMAppleConfiguration) {
for sharedDirectory in config.sharedDirectories {
if let url = sharedDirectory.directoryURL,
let file = try? File(url: url, isReadOnly: sharedDirectory.isReadOnly) {
sharedDirectories.append(file)
} else {
logger.error("Failed to migrate a shared directory from config.")
}
}
for drive in config.drives {
if drive.isExternal, let url = drive.imageURL,
let file = try? File(url: url, isReadOnly: drive.isReadOnly) {
externalDrives[drive.id] = file
} else {
logger.error("Failed to migrate drive \(drive.id) from config.")
}
}
}
#endif
}
// MARK: - Objective C bridging
// FIXME: these are NOT synchronized to the actor
@objc extension UTMRegistryEntry {
var hasSaveState: Bool {
get {
_isSuspended
}
set {
_isSuspended = newValue
}
}
var packageRemoteBookmark: Data? {
get {
_package.remoteBookmark
}
set {
_package.remoteBookmark = newValue
}
}
var packageRemotePath: String? {
get {
if _package.remoteBookmark != nil {
return _package.path
} else {
return nil
}
}
set {
if newValue != nil {
_package.path = newValue!
}
}
}
}
extension UTMRegistryEntry {
struct File: Codable, Identifiable {
var url: URL
var path: String
var bookmark: Data
var remoteBookmark: Data?
var isReadOnly: Bool
let id: UUID = UUID()
fileprivate var isValid: Bool
private enum CodingKeys: String, CodingKey {
case path = "Path"
case bookmark = "Bookmark"
case remoteBookmark = "BookmarkRemote"
case isReadOnly = "ReadOnly"
}
init(path: String, bookmark: Data, isReadOnly: Bool = false) throws {
self.path = path
self.bookmark = bookmark
self.isReadOnly = isReadOnly
self.url = try URL(resolvingPersistentBookmarkData: bookmark)
self.isValid = true
}
init(url: URL, isReadOnly: Bool = false) throws {
self.path = url.path
self.bookmark = try url.persistentBookmarkData(isReadyOnly: isReadOnly)
self.isReadOnly = isReadOnly
self.url = url
self.isValid = true
}
fileprivate init(path: String, remoteBookmark: Data = Data()) {
self.path = path
self.bookmark = Data()
self.isReadOnly = false
self.url = URL(fileURLWithPath: path)
self.remoteBookmark = remoteBookmark
self.isValid = true
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
path = try container.decode(String.self, forKey: .path)
bookmark = try container.decode(Data.self, forKey: .bookmark)
isReadOnly = try container.decode(Bool.self, forKey: .isReadOnly)
remoteBookmark = try container.decodeIfPresent(Data.self, forKey: .remoteBookmark)
url = URL(fileURLWithPath: path)
if bookmark.isEmpty {
isValid = true
} else {
// we cannot throw because that stops the decode process so we record the error and continue
do {
url = try URL(resolvingPersistentBookmarkData: bookmark)
isValid = true
} catch {
isValid = false
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(path, forKey: .path)
try container.encode(bookmark, forKey: .bookmark)
try container.encode(isReadOnly, forKey: .isReadOnly)
try container.encodeIfPresent(remoteBookmark, forKey: .remoteBookmark)
}
}
struct Window: Codable, Equatable {
var scale: CGFloat = 1.0
var origin: CGPoint = .zero
var isToolbarVisible: Bool = true
var isKeyboardVisible: Bool = false
var isDisplayZoomLocked: Bool = true
private enum CodingKeys: String, CodingKey {
case scale = "Scale"
case origin = "Origin"
case isToolbarVisible = "ToolbarVisible"
case isKeyboardVisible = "KeyboardVisible"
case isDisplayZoomLocked = "DisplayZoomLocked"
}
init() {
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
scale = try container.decode(CGFloat.self, forKey: .scale)
origin = try container.decode(CGPoint.self, forKey: .origin)
isToolbarVisible = try container.decode(Bool.self, forKey: .isToolbarVisible)
isKeyboardVisible = try container.decode(Bool.self, forKey: .isKeyboardVisible)
isDisplayZoomLocked = try container.decode(Bool.self, forKey: .isDisplayZoomLocked)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(scale, forKey: .scale)
try container.encode(origin, forKey: .origin)
try container.encode(isToolbarVisible, forKey: .isToolbarVisible)
try container.encode(isKeyboardVisible, forKey: .isKeyboardVisible)
try container.encode(isDisplayZoomLocked, forKey: .isDisplayZoomLocked)
}
}
struct Terminal: Codable, Equatable {
var columns: Int
var rows: Int
private enum CodingKeys: String, CodingKey {
case columns = "Columns"
case rows = "Rows"
}
init(columns: Int = 80, rows: Int = 24) {
self.columns = columns
self.rows = rows
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
columns = try container.decode(Int.self, forKey: .columns)
rows = try container.decode(Int.self, forKey: .rows)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(columns, forKey: .columns)
try container.encode(rows, forKey: .rows)
}
}
}
| [
-1
] |
5ee6f37feac44e8f8f2a833cf84382170c3a181f | 21f19ddb05f8cac3d656403e1e3dcdb23a0c3964 | /Vicinime-iOS/CardCell.swift | 77718b0fb6f2dff7badc37f5fc8e38120eb05273 | [] | no_license | andrew749/Vicinime-iOS | 1827023b3a86d5c0a6fed66b6956e9aa573bed24 | e12fdd2b026f0855180defa191f19ac69f0bc8b2 | refs/heads/master | 2021-01-25T03:27:04.886434 | 2015-07-31T00:54:39 | 2015-07-31T00:54:39 | 37,696,824 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,015 | swift | //
// CardCell.swift
// Vicinime-iOS
//
// Created by Andrew Codispoti on 2015-06-18.
// Copyright (c) 2015 Andrew Codispoti. All rights reserved.
//
import Foundation
import UIKit
class CardCell: UITableViewCell{
var cid:String?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dislikeImage: UIButton!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var descriptionText: UILabel!
@IBOutlet weak var mainImage: UIImageView!
var cellDelegate:CellDelegate?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func likeClick(sender: AnyObject) {
if let l=cellDelegate{
l.likeButtonClick(cid!)
}
}
@IBAction func dislikeClick(sender: AnyObject) {
if let l=cellDelegate{
l.dislikeButtonClick(cid!)
}
}
} | [
-1
] |
55aefbe5415c184a4c02694942ec9e756ee72d72 | 911614e725260256943731d502b75725dcff278a | /The-Dark-Place/The-Dark-Place/OtherFiles/AppDelegate.swift | 143322746efeac3829833a1976eb2cb082d44c95 | [
"MIT"
] | permissive | 2etime/Dark-Engine | 8aef54451e4d8a260f94ff612a5784ab5302cf84 | 52ff2f45e2a7ddff56d4f08765c00c7f3c3e929b | refs/heads/development | 2020-04-02T01:20:40.853084 | 2018-12-09T15:04:58 | 2018-12-09T15:04:58 | 153,850,705 | 4 | 1 | MIT | 2018-10-25T02:10:22 | 2018-10-19T23:06:38 | Swift | UTF-8 | Swift | false | false | 504 | swift | //
// AppDelegate.swift
// The-Dark-Place
//
// Created by Rick Twohy on 10/19/18.
// Copyright © 2018 2etime. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| [
293889,
333829,
384017,
361500,
235039,
332328,
200746,
324654,
289330,
243768,
44610,
188997,
322652,
323173,
287341,
416369,
344700,
244352,
291459,
402566,
239243,
116368,
327836,
284829,
339103,
62112,
226477,
358064,
165041,
164034,
265420,
286412,
3284,
313047,
313049,
275675,
383710,
119521,
302818,
286206,
234731,
242939,
237819,
117503,
352000,
171778,
320774,
336649,
138507,
352013,
201494,
295704,
259353,
113953,
237861,
200490,
333611,
295726,
245553,
326449,
351539,
216379,
351560,
349002,
225611,
351567,
250193,
389981,
182625,
321898,
224112,
288120,
436606,
200577,
293764,
183176,
236425,
349069,
368014,
349588,
253350,
38330,
229314,
415176,
234958,
193490,
234965,
327645,
144864,
327649,
183265,
313316,
168943,
249844,
308724,
313342
] |
c72c846a186ab9fda21d134737c238e65cd01af9 | 5b58a32a6438da3cb434c2ccbb1562c643b978e9 | /MoviesList/AppDelegate.swift | 432a1ec659dbdd018758d2876e971bac94a99e8f | [] | no_license | AndyStef/MoviesList | 597f9e360b4e8ab1961311c3f80d8f0fea177670 | ab701a0afdb41ba3157138f44d296de245bdbccd | refs/heads/master | 2021-01-20T19:34:26.958562 | 2016-05-29T19:13:49 | 2016-05-29T19:13:49 | 59,960,594 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,976 | swift | //
// AppDelegate.swift
// MoviesList
//
// Created by Andyy on 5/20/16.
// Copyright © 2016 Andyy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let dataModel = DataModel()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController = window!.rootViewController as! UINavigationController
let controller = navigationController.viewControllers[0] as! MainViewController
controller.dataModel = dataModel
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
saveData()
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
saveData()
}
func saveData() {
dataModel.saveMovies()
}
}
| [
276482,
229380,
276485,
229383,
282632,
229385,
276490,
278539,
229388,
278542,
229391,
276496,
282639,
229394,
278548,
229397,
229399,
229402,
278556,
229405,
278559,
354338,
278564,
354348,
282669,
276528,
204856,
282681,
282687,
276544,
284739,
67654,
276553,
278605,
354382,
280658,
354390,
288855,
227418,
194654,
223327,
278623,
313438,
227430,
276583,
278635,
313451,
223341,
276590,
278639,
284786,
276595,
131209,
417930,
141455,
141459,
276638,
184481,
288940,
176311,
280759,
307386,
176316,
280764,
276685,
278747,
278760,
157930,
227571,
278781,
276735,
227583,
278785,
278783,
276739,
227596,
282893,
291089,
211232,
282931,
276789,
280888,
280891,
155966,
282942,
278849,
280897,
282947,
280900,
260421,
239944,
285002,
239947,
282957,
278865,
280919,
276836,
280937,
276843,
276848,
280946,
280956,
227709,
280959,
285061,
178572,
285070,
190868,
285077,
65943,
283033,
291226,
276896,
283042,
285093,
278952,
276917,
283062,
278967,
283069,
278975,
281024,
278980,
289221,
278983,
278986,
278990,
278994,
176597,
281047,
283095,
279003,
279006,
276961,
227810,
279010,
279015,
279020,
279023,
279027,
281075,
279035,
281084,
279040,
279045,
283142,
287238,
121352,
279051,
281102,
279055,
279058,
279063,
281113,
279067,
281116,
281121,
182819,
227877,
227879,
281127,
279082,
279084,
281135,
279095,
281154,
377413,
158283,
281163,
279124,
277080,
262752,
285282,
281190,
277100,
281196,
295533,
184952,
170619,
282623,
277122,
277128,
285320,
279178,
287371,
277136,
227992,
299672,
164509,
227998,
287390,
299677,
299680,
209576,
279208,
287400,
285357,
277170,
342707,
154292,
277173,
285368,
133817,
277177,
277181,
279231,
277187,
287427,
277196,
119509,
226008,
279258,
213724,
363234,
228069,
279272,
283368,
285417,
283372,
381677,
277232,
228081,
289525,
234231,
234236,
234239,
209665,
234242,
285441,
242436,
226056,
285448,
242443,
33548,
234252,
242445,
228113,
242450,
281361,
285459,
234261,
369433,
281372,
234269,
234274,
277291,
234284,
279340,
281388,
234287,
283440,
285489,
234292,
285494,
279353,
234298,
281401,
283452,
289593,
234302,
234309,
281413,
281414,
234313,
277322,
234316,
281420,
283468,
234321,
234324,
281430,
234329,
281435,
234333,
279390,
281438,
234338,
279394,
281442,
234341,
174955,
177004,
234347,
234350,
234353,
234358,
277368,
234362,
226171,
234364,
234368,
226182,
213895,
234375,
39817,
187274,
226185,
277385,
213902,
279438,
234384,
234388,
234390,
226200,
234393,
279452,
234398,
277411,
279461,
279462,
234407,
234410,
226220,
234414,
234417,
226230,
234422,
197564,
234428,
226239,
234431,
189378,
52163,
226245,
234439,
234443,
234446,
234449,
234452,
304084,
234455,
234459,
281567,
234467,
234470,
228327,
5096,
234475,
228332,
234478,
277486,
234484,
234490,
285690,
234493,
234496,
277504,
234501,
277511,
234504,
234507,
295949,
234515,
234519,
234523,
234528,
234532,
234535,
234537,
144430,
234543,
234549,
300088,
277561,
234556,
234558,
230465,
296004,
277573,
228422,
205895,
234568,
234570,
277583,
234580,
234581,
234585,
277594,
234590,
277598,
285792,
277601,
234595,
281702,
234601,
228460,
164973,
203886,
160879,
234607,
279661,
281708,
281711,
187509,
234614,
279669,
285815,
285817,
234618,
289912,
398455,
285821,
234623,
226433,
234627,
222340,
234629,
279683,
285831,
302218,
285835,
234636,
234643,
226453,
234653,
283805,
234657,
234661,
234664,
165035,
277687,
277695,
302275,
283844,
302277,
228550,
279750,
283850,
203987,
279769,
363745,
279781,
285927,
279788,
195822,
279790,
120053,
204023,
228617,
283917,
283939,
259367,
130345,
113969,
296243,
222522,
286016,
226628,
283973,
283983,
222545,
179547,
146784,
230752,
302436,
173418,
410987,
279929,
181626,
281987,
281990,
226703,
230800,
226709,
288160,
288162,
279975,
282025,
282027,
277932,
370092,
279985,
296373,
284087,
337335,
282044,
296389,
38342,
64966,
288210,
280021,
288214,
228825,
288217,
280027,
288218,
288220,
280034,
280036,
280038,
187880,
288232,
288234,
286188,
288238,
288240,
226802,
282098,
288242,
308727,
148990,
282127,
286233,
282142,
284191,
282144,
108066,
226877,
228933,
226886,
128584,
276043,
280140,
286283,
366155,
226895,
280145,
276052,
276053,
147032,
235097,
243290,
280152,
159324,
282201,
284251,
284253,
284255,
370272,
159330,
284258,
284263,
284265,
286313,
284267,
280183,
280185,
276095,
280191,
276098,
280194,
282249,
276109,
280208,
286354,
278163,
280218,
276137,
278188,
278192,
296626,
278196,
282295,
282300,
280260,
276166,
280264,
276177,
278227,
280276,
278235,
280283,
284381,
229086,
278238,
284384,
216801,
282337,
284386,
216806,
284392,
284394,
284397,
284399,
419570,
282356,
276216,
280314,
282364,
282367,
67330,
278274,
278277,
282376,
280331,
284428,
282388,
116503,
282392,
284440,
329498,
296731,
276255,
284449,
278306,
282402,
300834,
227109,
282410,
280363,
276268,
306988,
165678,
278320,
282425,
280388,
280402,
276308,
282454,
284502,
284511,
280419,
282478,
110450,
315251,
284540,
1920,
282499,
282505,
276365,
282514,
44948,
280468,
282520,
280473,
294811,
284572,
282531,
276388,
284585,
276395,
276402,
40886,
276411,
231379,
276446,
276448,
276452,
276455,
231404,
276460,
276464,
278513,
227314,
276466,
278516,
278519,
276472,
276476,
276479
] |
34b4abfc94b20cb41cf62ca809ffa68e5f4ed972 | ae226e9dfd7d5ba388219b51a59b2fd22c5f541a | /DDSpiderChart/Classes/DDSpiderChartView.swift | cb8f173731d8f3811cddac4e95380d1ea24057fc | [
"MIT"
] | permissive | BOSSoNe0013/DDSpiderChart | 3ece20ae7032426cb7a2eae18d561bb03cab9dab | 7f8eb64f5745b8957cc26ac687ab8e2bb795b4d9 | refs/heads/master | 2020-04-07T23:36:57.074397 | 2018-12-03T14:55:04 | 2018-12-03T14:55:04 | 158,819,227 | 0 | 0 | MIT | 2018-11-23T10:46:26 | 2018-11-23T10:46:26 | null | UTF-8 | Swift | false | false | 6,004 | swift | //
// DDSpiderChartView.swift
// DDSpiderChart
//
// Created by dadalar on 05/01/2017.
// Copyright (c) 2017 dadalar. All rights reserved.
//
import UIKit
@IBDesignable open class DDSpiderChartView: UIView {
public var axes: [DrawableString] = [] {
didSet {
// When categories change, data sets should be cleaned
views.forEach { $0.removeFromSuperview() }
views = []
}
}
var views: [DDSpiderChartDataSetView] = [] // DDSpiderChartDataSetView's currently being presented
@IBInspectable public var color: UIColor = .gray {
didSet {
setNeedsDisplay()
}
}
@IBInspectable public var circleCount: Int = 10 {
didSet {
views.forEach {
$0.radius = circleRadius
$0.setNeedsDisplay()
}
}
}
@IBInspectable public var circleGap: CGFloat = 10 {
didSet {
views.forEach {
$0.radius = circleRadius
$0.setNeedsDisplay()
}
}
}
@IBInspectable public var endLineCircles: Bool = true {
didSet {
setNeedsDisplay()
}
}
@discardableResult public func addDataSet(values: [Float], color: UIColor, animated: Bool = true) -> UIView? {
guard values.count == axes.count else { return nil }
let view = DDSpiderChartDataSetView(radius: circleRadius, values: values, color: color)
view.frame = bounds
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.backgroundColor = .clear
views.append(view)
addSubview(view)
if animated {
view.alpha = 0
view.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: [], animations: {
view.alpha = 1.0
view.transform = CGAffineTransform.identity
}, completion: nil)
}
return view
}
public func removeDataSetView(_ view: UIView) {
guard let index = views.index(where: { $0 === view }) else { return }
views.remove(at: index)
view.removeFromSuperview()
}
}
// MARK: Drawing methods
extension DDSpiderChartView {
override open func draw(_ rect: CGRect) {
let center = CGPoint(x: rect.width/2, y: rect.height/2)
// Draw circles
let circlesToDraw = endLineCircles ? circleCount : circleCount + 1
for i in 1...circlesToDraw {
let radius = CGFloat(i) * circleGap
let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(2 * Float.pi), clockwise: true)
let color = (i % 2 == 0 || i == circlesToDraw) ? self.color : self.color.withAlphaComponent(0.5)
color.set()
circlePath.stroke()
}
// Draw each data set
for (index, axis) in axes.enumerated() {
// Draw line
let angle = CGFloat(-Float.pi / 2) - CGFloat(index) * CGFloat(2 * Float.pi) / CGFloat(axes.count)
self.color.set()
let linePath = UIBezierPath()
linePath.move(to: center)
let x = center.x + (circleRadius + circleGap) * cos(angle)
let y = center.y + (circleRadius + circleGap) * sin(angle)
linePath.addLine(to: CGPoint(x: x, y: y))
linePath.stroke()
var circleCenter = CGPoint(x: center.x + (circleRadius) * cos(angle), y: center.y + (circleRadius) * sin(angle))
if endLineCircles {
// Draw circle at the end the line
circleCenter = CGPoint(x: center.x + (circleRadius + circleGap * 3/2) * cos(angle), y: center.y + (circleRadius + circleGap * 3/2) * sin(angle))
let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleGap/2, startAngle: 0, endAngle: CGFloat(2 * Float.pi), clockwise: true)
circlePath.stroke()
}
// Draw axes label
let isOnTop = sin(angle) < 0 // we should draw text on top of the circle when circle is on the upper half. (and vice versa)
let isOnLeft = cos(angle) < 0 // we should draw text on left of the circle when circle is on the left half. (and vice versa)
let categoryStringSize = axis.size()
let categoryStringPadding = circleGap/2 + 5
if endLineCircles {
let categoryStringOrigin = CGPoint(x: circleCenter.x - categoryStringSize.width/2, y: circleCenter.y+(isOnTop ? (-(categoryStringSize.height+categoryStringPadding)) : (categoryStringPadding)))
axis.drawDrawable(with: .init(origin: categoryStringOrigin, size: categoryStringSize))
}
else {
let categoryStringOrigin = CGPoint(x: circleCenter.x-(index == 0 ? categoryStringSize.width/2 : (isOnLeft ? categoryStringSize.width+categoryStringPadding : -categoryStringPadding)), y: circleCenter.y+(isOnTop ? (-(categoryStringSize.height+categoryStringPadding)) : (categoryStringPadding)))
axis.drawDrawable(with: .init(origin: categoryStringOrigin, size: categoryStringSize))
}
}
}
}
// MARK: Computational properties & helper methods
extension DDSpiderChartView {
fileprivate var circleRadius: CGFloat {
return CGFloat(circleCount) * circleGap
}
override open var intrinsicContentSize: CGSize {
let len = 2 * circleRadius + 100 // +100 for text
return .init(width: len, height: len)
}
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
axes = ["Axis 1", "Axis 2", "Axis 3", "Axis 4", "Axis 5"]
_ = addDataSet(values: [0.7, 0.5, 0.6, 0.9, 1.0], color: .white)
}
}
| [
-1
] |
aa76449cc468cc5f9d5f328fb9f21ed65f8dccd9 | 926f3cfe60655bbd55bd8ec15d4306397e790795 | /AppiumSwiftClient/common/http/Client.swift | 25e3b2a33f3ca894b710387d7ec4d0af5e0d4866 | [
"MIT"
] | permissive | aravindanath/AppiumSwiftClient | 9576eb82054a6d38a35e16ecac23221270893d58 | 0b2220522fba0eb427bc08fac82b4b609773da9c | refs/heads/master | 2020-06-05T20:41:55.679607 | 2019-01-31T04:56:30 | 2019-01-31T04:56:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,668 | swift | //
// Client.swift
// AppiumSwiftClient
//
// Created by kazuaki matsuo on 2018/11/12.
// Copyright © 2018 KazuCocoa. All rights reserved.
//
import Foundation
struct HttpClient {
let endpoint: String
init(endpoint: String = "") {
self.endpoint = endpoint.isEmpty ? "http://127.0.0.1:4723/wd/hub/" : endpoint
}
func sendSyncRequest(method: HttpMethod, commandPath: String, json: Data) -> (Int, [String: Any]) {
let uri = "\(endpoint)\(commandPath)"
var returnValue: [String: Any] = ["value": ""]
var statusCode: Int = 0
guard let url = URL(string: uri) else {
print("failed to create session")
return (0, returnValue)
}
let semaphore = DispatchSemaphore(value: 0)
var commandURLRequest = URLRequest(url: url)
commandURLRequest.httpMethod = method.rawValue
commandURLRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
commandURLRequest.addValue("application/json", forHTTPHeaderField: "Accept")
commandURLRequest.timeoutInterval = 60.0 // 60 secons
if method == HttpMethod.post {
commandURLRequest.httpBody = json
}
let session = URLSession.shared
let task = session.dataTask(with: commandURLRequest) { (data, response, error) in
if let resp = response {
statusCode = (resp as! HTTPURLResponse).statusCode // swiftlint:disable:this force_cast
}
guard let responseData = data, error == nil else {
print("Error calling \(method.rawValue) on \(uri)")
return
}
returnValue = WebDriverResponseValue(responseJsonData: responseData)
.value as! [String: Any] // swiftlint:disable:this force_cast
semaphore.signal()
}
task.resume()
_ = semaphore.wait(timeout: .distantFuture)
return (statusCode, returnValue)
}
struct WebDriverResponseValue {
let value: Any
init(responseJsonData: Data) {
do {
guard let jsonValue =
try JSONSerialization.jsonObject(with: responseJsonData, options: []) as? [String: Any] else {
print("Could not get JSON from responseData as dictionary")
value = "Invalid JSON format"
return
}
value = jsonValue
} catch {
print("Error parsing response from POST")
value = "Invalid JSON format"
return
}
}
}
}
| [
-1
] |
7e94c28cf9eab67b812b03c26e5b3f0737a86f8f | 0aa1564e95a886cd2b092c96fb89ac9fe0c083fe | /Drunkosophy/Drunkosophy/ResponseTableViewCell.swift | b63ee61107db107fefac21e10e74f84db8d9a07e | [] | no_license | albyphoney/drunkosophy | dbd12bc5b77330b2535f046f845a3399e76ea68b | cdf4f4a4b9b76ea4cfecc574607fb9816c179857 | refs/heads/master | 2020-12-31T03:55:36.075817 | 2015-12-14T06:14:20 | 2015-12-14T06:14:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,023 | swift | //
// ResponseTableViewCell.swift
// Drunkosophy
//
// Created by Warren W Tian on 12/7/15.
// Copyright © 2015 Warren Tian and Albert Phone. All rights reserved.
//
import Foundation
import UIKit
import Parse
import Bolts
class ResponseTableViewCell: UITableViewCell {
var responseId = String()
@IBOutlet var responseTextView: UITextView!
@IBOutlet var scoreLabel: UILabel!
@IBOutlet var usernameLabel: UILabel!
@IBAction func upVote(sender: AnyObject) {
let query = PFQuery(className: "Response")
query.getObjectInBackgroundWithId(responseId) {
(response: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let response = response {
response.incrementKey("score")
let score = response.objectForKey("score") as! NSNumber
self.scoreLabel.text = "\(score)"
response.saveInBackground()
}
}
}
}
| [
-1
] |
3a7f7ac3e11f1f019588002f6a117703505f6015 | a09d4873186bee0bf12039c44bd7255b03497f55 | /Surf/Classes/Presentation/ChatScreen/Views/ChatTableView/Cells/InterlocutorChatMessageCell.swift | 6539982e8468dfc780e32716a7996001f9dcb451 | [] | no_license | AgentChe/Surf | f86af0cc390796de4cb6019e04a2ca234bff4d13 | 982e20851ea46ab3f9451f49f67d3ca11dcf172e | refs/heads/master | 2022-12-08T21:08:11.248890 | 2020-09-09T17:31:01 | 2020-09-09T17:31:01 | 278,627,017 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,766 | swift | //
// InterlocutorChatCell.swift
// FAWN
//
// Created by Andrey Chernyshev on 08/06/2020.
// Copyright © 2020 Алексей Петров. All rights reserved.
//
import UIKit
final class InterlocutorChatMessageCell: MessageTableCell {
lazy var messageBackgroundView = makeBackgroundView()
lazy var messageLabel = makeLabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .white
makeConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func bind(message: Message) {
super.bind(message: message)
messageLabel.text = message.body
}
}
// MARK: Make constraints
private extension InterlocutorChatMessageCell {
func makeConstraints() {
NSLayoutConstraint.activate([
messageBackgroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16.scale),
messageBackgroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 6.scale),
messageBackgroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -6.scale),
messageBackgroundView.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -80.scale)
])
NSLayoutConstraint.activate([
messageLabel.leadingAnchor.constraint(equalTo: messageBackgroundView.leadingAnchor, constant: 12.scale),
messageLabel.trailingAnchor.constraint(equalTo: messageBackgroundView.trailingAnchor, constant: -12.scale),
messageLabel.topAnchor.constraint(equalTo: messageBackgroundView.topAnchor, constant: 8.scale),
messageLabel.bottomAnchor.constraint(equalTo: messageBackgroundView.bottomAnchor, constant: -8.scale),
])
}
}
// MARK: Lazy initialization
private extension InterlocutorChatMessageCell {
func makeBackgroundView() -> UIView {
let view = UIView()
view.layer.cornerRadius = 18.scale
view.backgroundColor = UIColor(red: 237 / 255, green: 103 / 255, blue: 117 / 255, alpha: 1)
view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(view)
return view
}
func makeLabel() -> UILabel {
let view = UILabel()
view.numberOfLines = 0
view.textColor = .white
view.font = Font.SFProText.regular(size: 15.scale)
view.textAlignment = .left
view.translatesAutoresizingMaskIntoConstraints = false
messageBackgroundView.addSubview(view)
return view
}
}
| [
-1
] |
8795c835c82177499698558162501087419ac8bf | 86d29cf701f24ab2cee390ee87c9037e6f668a22 | /Modules/CharacterListKit/Tests/Presentation/CharactersListPresenterTest.swift | c980f5e89b2f88142fb7d212e3633b42575f7b80 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | minsone-opensource-fork/excelsior | 38e77a0c11e469308065fff8d623122ff0fc7c5b | acecfb60175c3608e67db00f960ed0e2e7ea8e52 | refs/heads/master | 2022-05-30T17:54:20.241605 | 2020-04-30T23:55:54 | 2020-04-30T23:55:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,899 | swift | //
// CharactersListPresenterTest.swift
// CharactersListKitTests
//
// Created by Rafael Bartolome on 22/03/2020.
// Copyright © 2020 Rafael Bartolome. All rights reserved.
//
import XCTest
@testable import CharactersListKit
class CharactersListPresenterTest: XCTestCase {
var sut: CharactersListPresenter!
let characterDetailNavigatorMock = CharacterDetailNavigatorMock()
let charactersListPresenterDelegateMock = CharactersListPresenterDelegateMock()
override func setUp() {
sut = CharactersListPresenter(characters: CharacterMother.anyCharacters,
navigator: characterDetailNavigatorMock)
sut.delegate = charactersListPresenterDelegateMock
}
}
extension CharactersListPresenterTest {
func test_numberOfCharacters_returnsRight() {
//when
let result = sut.numberOfCharacters
// then
XCTAssertEqual(result, CharacterMother.anyCharacters.count)
}
func test_characterForIndex_returnsRight() {
// given
let index = 1
//when
let result = sut.character(for: index)
// then
XCTAssertEqual(result, CharacterMother.anyCharacters[index])
}
func test_characterSelected_navigatesToDetailWithCharacterId() {
// given
let index = 1
//when
sut.characterSelected(at: index)
// then
XCTAssertEqual(CharacterMother.anyCharacters[index].id,
characterDetailNavigatorMock.navigateToCharacterDetailCalls.first)
}
func test_askedForLastCharacter_askForMore() {
// given
let index = CharacterMother.anyCharacters.count - 1
//when
_ = sut.character(for: index)
// then
XCTAssertEqual(1, charactersListPresenterDelegateMock.loadMoreCalls)
}
}
| [
-1
] |
d1f8b96a4c01220a600570fe62c0afc667abc531 | b748be1dd4c9648a832010986a7fd29bc4102b88 | /swift-segues-lab-swift-intro-000/Animals/AnimalViewController.swift | 4b6ba1c3f58322ce5f1b1fdc9a6f227369a39e46 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | mgschuster/Learn.coiOS10 | 531066ed7cffabf741355ef18e79c49d49fd4051 | c6d267c4ee564453b1e76ccc9685abe0221e95a6 | refs/heads/master | 2020-12-30T10:11:48.191485 | 2017-08-03T13:59:53 | 2017-08-03T13:59:53 | 99,237,110 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,321 | swift | //
// AnimalViewController.swift
// Animals
//
// Created by Michael Dippery on 7/17/16.
// Copyright © 2016 Flatiron School. All rights reserved.
//
import UIKit
class AnimalViewController: UIViewController {
@IBOutlet weak var emojiLabel: UILabel!
@IBOutlet weak var emojiTextLabel: UILabel!
var animal: String?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let animal = animal {
emojiTextLabel?.text = animal
let animalName = nameToEmoji(animal)
emojiLabel?.text = animalName
navigationItem.title = animal
}
}
fileprivate func nameToEmoji(_ name: String) -> String {
switch name {
case "Dog":
return "🐶"
case "Cat":
return "🐱"
case "Mouse":
return "🐭"
case "Hamster":
return "🐹"
case "Bunny":
return "🐰"
case "Panda":
return "🐼"
case "Lion":
return "🦁"
case "Pig":
return "🐷"
case "Frog":
return "🐸"
case "Octopus":
return ""
default:
return "🐙"
}
}
}
| [
-1
] |
ec72da6b7a30c820eec7389289877f6c352efe71 | f2aca42f22e37e1db4f803ecc658b0b93cd04492 | /Vesea_Columbia/Vesea_Columbia/CourseInfoView.swift | a2d519cdc96098235c32739b55744b66eb2972eb | [] | no_license | lahavlipson/Advesea_Columbia | c5f785adeb6a8e1cd77040a0718eede18fa5fbb9 | 378c65c90d762ea393d36485886e0f5cae42580c | refs/heads/master | 2021-06-06T22:44:22.358879 | 2016-08-30T07:10:16 | 2016-08-30T07:10:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,963 | swift | //
// CourseInfoView.swift
// Vesea_Columbia
//
// Created by Lahav Lipson on 7/15/16.
// Copyright © 2016 Lahav Lipson. All rights reserved.
//
import UIKit
@IBDesignable class CourseInfoView: UIView {
var delegate: QuestionViewController?
var view: UIView!
var nibName: String = "CourseInfoView"
private var courseID: String = ""
private var courseName: String = ""
private var courseDepartment: String = ""
private var culpaIndex: String = ""
private var courseCredits: String = ""
@IBOutlet weak var departmentLabel: UILabel!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var courseDirectoryNumLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var culpaButton: UIButton!
@IBAction func flipView(sender: UIButton) {
delegate?.flipInfoView("Info")
}
@IBAction func openCulpa(sender: AnyObject) {
if culpaIndex != ""{
UIApplication.sharedApplication().openURL(NSURL(string:"http://www.culpa.info/courses/" + culpaIndex)!)
}
}
@IBInspectable var ID : String {
get{
return courseID
} set (id){
courseID = id
idLabel.text = id
let courseDict = MyVariables.courses!.get(id)!
courseName = courseDict["Name"] as! String
nameLabel.text = courseName
courseDepartment = courseDict["Department"] as! String
let textRange = NSMakeRange(0, courseDepartment.characters.count)
let attributedText = NSMutableAttributedString(string: courseDepartment)
attributedText.addAttribute(NSUnderlineStyleAttributeName , value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
departmentLabel.attributedText = attributedText
self.courseCredits = "Credits: " + (courseDict["Credits"] as! String)
courseDirectoryNumLabel.text = self.courseCredits
culpaIndex = courseDict["Culpa"] as! String
if culpaIndex == ""{
culpaButton.hidden = true
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup(){
view = loadViewFromNib()
view.frame = bounds
//view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view)
self.layer.cornerRadius = 15
self.layer.masksToBounds = true
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
| [
-1
] |
5851594043b3897835b736b054a1f6faaeb54f0b | c0bcc2e2142ee93e83f43c9f8064f171477b4f81 | /OpenEmu/HomebrewViewController.swift | 49d4db959fc09564366164ea4025a6b1a4987adf | [] | no_license | NettoX75/OpenEmu | 7975b4393cda434b825c851646b1fefa7c2e68ce | dce9a15fc12bc6047fe8df8dcf4dca5c3d8e2ac0 | refs/heads/master | 2023-08-14T07:03:47.306358 | 2021-10-14T21:19:29 | 2021-10-15T14:02:53 | 417,882,939 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 17,221 | swift | // Copyright (c) 2020, OpenEmu Team
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the OpenEmu Team nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Cocoa
private extension NSUserInterfaceItemIdentifier {
static let headerView = NSUserInterfaceItemIdentifier("HeaderView")
static let featureView = NSUserInterfaceItemIdentifier("FeatureView")
static let gameView = NSUserInterfaceItemIdentifier("GameView")
static let dummyView = NSUserInterfaceItemIdentifier("DummyView")
}
final class HomebrewViewController: NSViewController {
private let homebrewGamesURL = URL(string: "https://raw.githubusercontent.com/OpenEmu/OpenEmu-Update/master/games.xml")!
@IBOutlet var tableView: NSTableView!
private var blankSlate: HomebrewBlankSlateView?
var database: OELibraryDatabase?
private var currentDownload: OEDownload?
private var games: [HomebrewGame]!
private var headerIndices: [Int]!
override func viewDidLoad() {
super.viewDidLoad()
view.autoresizingMask = [.width, .height]
tableView.allowsColumnReordering = false
tableView.allowsColumnResizing = false
tableView.allowsEmptySelection = true
tableView.allowsMultipleSelection = false
tableView.allowsTypeSelect = false
tableView.delegate = self
tableView.dataSource = self
tableView.sizeLastColumnToFit()
tableView.columnAutoresizingStyle = .uniformColumnAutoresizingStyle
tableView.tableColumns.last?.resizingMask = .autoresizingMask
}
override func viewDidAppear() {
super.viewDidAppear()
validateToolbarItems()
// Fetch games if we haven't already, this allows reloading if an error occured, by switching to a different library view and then back to homebrew
if games == nil || games.count == 0 {
updateGames()
}
}
private var toolbar: LibraryToolbar? {
view.window?.toolbar as? LibraryToolbar
}
func validateToolbarItems() {
guard let toolbar = toolbar else { return }
toolbar.viewModeSelector.isEnabled = false
toolbar.viewModeSelector.selectedSegment = -1
toolbar.gridSizeSlider.isEnabled = false
toolbar.decreaseGridSizeButton.isEnabled = false
toolbar.increaseGridSizeButton.isEnabled = false
toolbar.searchField.isEnabled = false
toolbar.searchField.searchMenuTemplate = nil
toolbar.searchField.stringValue = ""
toolbar.addButton.isEnabled = false
if #available(macOS 11.0, *) {
for item in toolbar.items {
if item.itemIdentifier == .oeSearch {
item.isEnabled = false
}
}
}
}
// MARK: - Data Handling
private func updateGames() {
// Indicate that we're fetching some remote resources
displayUpdate()
// Cancel last download
currentDownload?.cancel()
let download = OEDownload(url: homebrewGamesURL)
weak var blockDL = download
download?.completionHandler = { [self] destination, error in
if currentDownload == blockDL {
currentDownload = nil
}
if let nsErr = error as? CocoaError, nsErr.code == .userCancelled {
return
}
if error == nil, let destination = destination {
do {
try parseFile(at: destination)
displayResults()
} catch {
displayError(error)
}
}
else {
displayError(error)
}
}
currentDownload = download
download?.start()
}
private func parseFile(at url: URL) throws {
let document: XMLDocument
do {
document = try XMLDocument(contentsOf: url, options: [])
}
catch {
return DLog("\(String(describing: error))")
}
var allHeaderIndices = [Int]()
if let allGames = try? document.nodes(forXPath: "//system | //game") {
games = allGames.enumerated().compactMap { (index, node) in
// Keep track of system node indices to use for headers
if let _ = try? node.nodes(forXPath: "@id").last {
allHeaderIndices.append(index)
}
return HomebrewGame(node: node)
}
}
headerIndices = allHeaderIndices
}
// MARK: - View Management
private func displayUpdate() {
let blankSlate = HomebrewBlankSlateView(frame: view.bounds)
blankSlate.representedObject = NSLocalizedString("Fetching Games…", comment: "Homebrew Blank Slate View Updating Info")
displayBlankSlate(blankSlate)
}
private func displayError(_ error: Error?) {
guard view.window != nil else {
// User switched to another category. No need to display the error
// because changing back to Homebrew brings up the spinner again.
return
}
let blankSlate = HomebrewBlankSlateView(frame: view.bounds)
blankSlate.representedObject = error
displayBlankSlate(blankSlate)
}
private func displayResults() {
displayBlankSlate(nil)
}
private func displayBlankSlate(_ newBlankSlate: HomebrewBlankSlateView?) {
guard blankSlate != newBlankSlate else { return }
// Determine if we are about to replace the current first responder or one of its superviews
let firstResponder = view.window?.firstResponder
let makeFirstResponder = (firstResponder as? NSView)?.isDescendant(of: view) ?? false
blankSlate?.removeFromSuperview()
blankSlate = newBlankSlate
if let blankSlate = blankSlate, let window = view.window {
blankSlate.frame = NSRect(origin: .zero, size: window.contentLayoutRect.size)
blankSlate.autoresizingMask = [.height, .width]
view.addSubview(blankSlate)
tableView.isHidden = true
}
else {
tableView.reloadData()
tableView.isHidden = false
}
// Restore first responder if necessary
if makeFirstResponder {
if blankSlate != nil {
view.window?.makeFirstResponder(blankSlate)
} else {
view.window?.makeFirstResponder(tableView)
}
}
}
// MARK: - Actions
@IBAction func goToDeveloperWebsite(_ sender: NSButton) {
let row = rowOfView(sender)
guard row >= 0, row < games.count else { return }
let game = games[row]
if let url = URL(string: game.website) {
NSWorkspace.shared.open(url)
}
}
@IBAction func launchGame(_ sender: NSButton) {
let row = rowOfView(sender)
guard row >= 0, row < games.count else { return }
let homebrewGame = games[row]
let url = URL(string: homebrewGame.fileURLString)
let fileIndex = homebrewGame.fileIndex
let systemIdentifier = homebrewGame.systemIdentifier
let md5 = homebrewGame.md5
let name = homebrewGame.name
let context = database!.mainThreadContext
var rom: OEDBRom?
do {
rom = try OEDBRom(md5HashString: md5, in: context)
} catch {
let romDescription = OEDBRom.entityDescription(in: context)
let gameDescription = OEDBGame.entityDescription(in: context)
rom = OEDBRom(entity: romDescription, insertInto: context)
rom!.sourceURL = url
rom!.archiveFileIndex = NSNumber(value: fileIndex)
rom!.md5 = md5.lowercased()
let game = OEDBGame(entity: gameDescription, insertInto: context)
game.roms = Set<OEDBRom>([rom!])
game.name = name
game.system = OEDBSystem(forPluginIdentifier: systemIdentifier, in: context)
if let imageURL = homebrewGame.images?.first {
game.setBoxImage(url: imageURL)
}
}
let game = rom?.game
game?.save()
NSApp.sendAction(#selector(MainWindowController.startGame(_:)), to: nil, from: game)
}
private func rowOfView(_ view: NSView) -> Int {
let viewRect = view.frame
let viewRectOnView = tableView.convert(viewRect, from: view.superview)
let row = tableView.row(at: NSPoint(x: viewRectOnView.midX, y: viewRectOnView.midY))
if row == 1 {
let container = view.superview?.superview
if let superview = view.superview {
return container?.subviews.firstIndex(where: { $0 === superview }) ?? -1
}
return -1
}
return row
}
}
// MARK: - NSTableView Delegate
extension HomebrewViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if row == 0 || headerIndices.contains(row) {
return tableView.makeView(withIdentifier: .headerView, owner: self) as? NSTableCellView
}
else if row == 2 {
return tableView.makeView(withIdentifier: .dummyView, owner: self) as? NSTableCellView
}
else if row == 1 {
guard
let view = tableView.makeView(withIdentifier: .featureView, owner: self) as? NSTableCellView,
let games = self.tableView(tableView, objectValueFor: tableColumn, row: row) as? [HomebrewGame]
else { return nil }
let subview = view.subviews.last?.subviews.last
for (index, game) in games.enumerated() {
let container = subview?.subviews[index]
if let artworkView = container?.subviews[0] as? HomebrewCoverView {
artworkView.urls = game.images
artworkView.target = self
artworkView.doubleAction = #selector(launchGame(_:))
}
if let label = container?.subviews[1] as? NSTextField {
label.stringValue = game.name
}
}
return view
}
else {
guard
let view = tableView.makeView(withIdentifier: .gameView, owner: self) as? NSTableCellView,
let game = self.tableView(tableView, objectValueFor: tableColumn, row: row) as? HomebrewGame
else { return nil }
let subviews = view.subviews
if let title = subviews[0] as? NSTextField {
title.stringValue = game.name
}
if let system = subviews[1] as? NSButton {
system.title = game.systemShortName
}
if let year = subviews[2] as? NSButton {
let formatter = DateFormatter()
formatter.dateFormat = "Y"
year.title = formatter.string(from: game.released)
year.isHidden = game.released.timeIntervalSince1970 == 0
}
if let description = subviews[3] as? NSTextField {
description.stringValue = game.gameDescription
}
if let developer = subviews[5] as? TextButton {
developer.title = game.developer
developer.target = self
developer.action = #selector(goToDeveloperWebsite(_:))
developer.objectValue = game.website
developer.textColor = NSColor(from: "#929DA5")
developer.textColorHover = NSColor(from: "#9c2a32")
}
if let imagesView = subviews[4] as? HomebrewCoverView {
imagesView.urls = game.images
imagesView.target = self
imagesView.doubleAction = #selector(launchGame(_:))
}
return view
}
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return false
}
}
// MARK: - NSTableView DataSource
extension HomebrewViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return games?.count ?? 0 // -3 for featured games which share a row, +1 for the shared row, + 2 for headers
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
if row == 0 {
return NSLocalizedString("Featured Games", comment: "")
}
if row == 2 {
return nil
}
if row == 1 {
return Array(games[0...2])
}
if headerIndices.contains(row) {
// Use system lastLocalizedName for header
let game = games[row]
let identifier = game.systemGroup
let context = OELibraryDatabase.default!.mainThreadContext
let system = OEDBSystem(forPluginIdentifier: identifier, in: context)
return system.lastLocalizedName
}
return games[row]
}
}
// MARK: - HomebrewGame
private struct HomebrewGame {
let name: String
let developer: String
let website: String
let fileURLString: String
let fileIndex: Int
let gameDescription: String
//let added: Date
let released: Date
let systemIdentifier: String
let md5: String
let systemGroup: String
let images: [URL]?
init(node: XMLNode) {
func stringValue(_ xPath: String, node: XMLNode = node) -> String? {
return try? node.nodes(forXPath: xPath).last?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines)
}
func integerValue(_ xPath: String) -> Int? {
return Int(stringValue(xPath) ?? "")
}
func dateValue(_ xPath: String) -> Date {
return Date(timeIntervalSince1970: TimeInterval(integerValue(xPath) ?? 0))
}
name = stringValue("@name") ?? ""
developer = stringValue("@developer") ?? ""
website = stringValue("@website") ?? ""
fileURLString = stringValue("@file") ?? ""
fileIndex = integerValue("@fileIndex") ?? 0
gameDescription = stringValue("description") ?? ""
//added = dateValue("@added")
released = dateValue("@released")
systemIdentifier = stringValue("@system") ?? ""
md5 = stringValue("@md5") ?? ""
systemGroup = stringValue("@id") ?? ""
if let imageNodes = try? node.nodes(forXPath: "images/image") {
images = imageNodes.compactMap {
URL(string: stringValue("@src", node: $0) ?? "")
}
}
else { images = nil }
}
var systemShortName: String {
let identifier = systemIdentifier
let context = OELibraryDatabase.default!.mainThreadContext
let system = OEDBSystem(forPluginIdentifier: identifier, in: context)
if let shortname = system.shortname {
return shortname
} else {
return identifier.components(separatedBy: ".").last?.uppercased() ?? ""
}
}
}
| [
-1
] |
18f3bbae8fdfb3e5d6fb63b2291a17291155b4b7 | e0ff31d216980788136f4b7ca7009364294c97fb | /LNZCollectionLayouts/CollectionViewController.swift | b42155e7ad34a7d20ab3a8bc05aa902d9341684e | [
"MIT"
] | permissive | PhanithNY/LNZCollectionLayouts | dac713752ddc6f8e990636270f181e27509a18e3 | 1dfbb73e940eeb6419b14c9f67bd3c46cf6a9a01 | refs/heads/master | 2020-04-14T17:13:39.267891 | 2018-09-20T17:43:47 | 2018-09-20T17:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,470 | swift | //
// InfiniteViewController.swift
// LNZCollectionLayouts
//
// Created by Giuseppe Lanza on 18/07/17.
// Copyright © 2017 Gilt. All rights reserved.
//
import UIKit
class CollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
collectionView?.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 15
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let label = cell.contentView.viewWithTag(10)! as! UILabel
cell.layer.borderColor = UIColor.darkGray.cgColor
cell.layer.borderWidth = 1
label.text = "\(indexPath.item)"
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (coord) in
self.collectionView?.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
}
}
extension CollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 40)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 40)
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var identifier = "header"
if kind == UICollectionView.elementKindSectionFooter {
identifier = "footer"
}
let supplementaryView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)
supplementaryView.backgroundColor = UIColor.lightGray
let label = supplementaryView.viewWithTag(99) as? UILabel ?? UILabel(frame: supplementaryView.bounds)
label.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
label.textAlignment = .center
label.text = identifier
if label.superview == nil {
supplementaryView.addSubview(label)
}
return supplementaryView
}
}
| [
-1
] |
b77e20b831f174c763e8555c81a9781964865c8e | e33789a0c207a310036a95d619317f8923bfed14 | /Sources/ParseSwift/Objects/ParseObject+async.swift | de7f30c4b7cf7837ba346d638e3b7dcf654ca6ae | [
"MIT"
] | permissive | parse-community/Parse-Swift | 07708e0eaacc6beaff3dfeadf440d288d918414b | 3d4bb13acd7496a49b259e541928ad493219d363 | refs/heads/main | 2023-03-23T07:23:24.421880 | 2022-11-16T22:24:08 | 2022-11-16T22:24:08 | 98,342,385 | 320 | 93 | MIT | 2022-12-27T22:10:29 | 2017-07-25T19:27:25 | Swift | UTF-8 | Swift | false | false | 25,201 | swift | //
// ParseObject+async.swift
// ParseObject+async
//
// Created by Corey Baker on 8/6/21.
// Copyright © 2021 Parse Community. All rights reserved.
//
#if compiler(>=5.5.2) && canImport(_Concurrency)
import Foundation
public extension ParseObject {
// MARK: Async/Await
/**
Fetches the `ParseObject` *aynchronously* with the current data from the server.
- parameter includeKeys: The name(s) of the key(s) to include that are
`ParseObject`s. Use `["*"]` to include all keys one level deep. This is similar to `include` and
`includeAll` for `Query`.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns the fetched `ParseObject`.
- throws: An error of type `ParseError`.
- note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer
desires a different policy, it should be inserted in `options`.
*/
@discardableResult func fetch(includeKeys: [String]? = nil,
options: API.Options = []) async throws -> Self {
try await withCheckedThrowingContinuation { continuation in
self.fetch(includeKeys: includeKeys,
options: options,
completion: continuation.resume)
}
}
/**
Saves the `ParseObject` *asynchronously*.
- parameter ignoringCustomObjectIdConfig: Ignore checking for `objectId`
when `ParseConfiguration.isRequiringCustomObjectIds = true` to allow for mixed
`objectId` environments. Defaults to false.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns the saved `ParseObject`.
- throws: An error of type `ParseError`.
*/
@discardableResult func save(ignoringCustomObjectIdConfig: Bool = false,
options: API.Options = []) async throws -> Self {
try await withCheckedThrowingContinuation { continuation in
self.save(ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig,
options: options,
completion: continuation.resume)
}
}
/**
Creates the `ParseObject` *asynchronously*.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns the saved `ParseObject`.
- throws: An error of type `ParseError`.
*/
@discardableResult func create(options: API.Options = []) async throws -> Self {
try await withCheckedThrowingContinuation { continuation in
self.create(options: options,
completion: continuation.resume)
}
}
/**
Replaces the `ParseObject` *asynchronously*.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns the saved `ParseObject`.
- throws: An error of type `ParseError`.
*/
@discardableResult func replace(options: API.Options = []) async throws -> Self {
try await withCheckedThrowingContinuation { continuation in
self.replace(options: options,
completion: continuation.resume)
}
}
/**
Updates the `ParseObject` *asynchronously*.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns the saved `ParseObject`.
- throws: An error of type `ParseError`.
*/
@discardableResult internal func update(options: API.Options = []) async throws -> Self {
try await withCheckedThrowingContinuation { continuation in
self.update(options: options,
completion: continuation.resume)
}
}
/**
Deletes the `ParseObject` *asynchronously*.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of type `ParseError`.
*/
func delete(options: API.Options = []) async throws {
let result = try await withCheckedThrowingContinuation { continuation in
self.delete(options: options,
completion: continuation.resume)
}
if case let .failure(error) = result {
throw error
}
}
}
public extension Sequence where Element: ParseObject {
/**
Fetches a collection of objects *aynchronously* with the current data from the server and sets
an error if one occurs.
- parameter includeKeys: The name(s) of the key(s) to include that are
`ParseObject`s. Use `["*"]` to include all keys one level deep. This is similar to `include` and
`includeAll` for `Query`.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns an array of Result enums with the object if a fetch was successful or a
`ParseError` if it failed.
- throws: An error of type `ParseError`.
*/
@discardableResult func fetchAll(includeKeys: [String]? = nil,
options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] {
try await withCheckedThrowingContinuation { continuation in
self.fetchAll(includeKeys: includeKeys,
options: options,
completion: continuation.resume)
}
}
/**
Saves a collection of objects *asynchronously*.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter ignoringCustomObjectIdConfig: Ignore checking for `objectId`
when `ParseConfiguration.isRequiringCustomObjectIds = true` to allow for mixed
`objectId` environments. Defaults to false.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns an array of Result enums with the object if a save was successful or a
`ParseError` if it failed.
- throws: An error of type `ParseError`.
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
- warning: If you are using `ParseConfiguration.isRequiringCustomObjectIds = true`
and plan to generate all of your `objectId`'s on the client-side then you should leave
`ignoringCustomObjectIdConfig = false`. Setting
`ParseConfiguration.isRequiringCustomObjectIds = true` and
`ignoringCustomObjectIdConfig = true` means the client will generate `objectId`'s
and the server will generate an `objectId` only when the client does not provide one. This can
increase the probability of colliiding `objectId`'s as the client and server `objectId`'s may be generated using
different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the
client-side checks are disabled. Developers are responsible for handling such cases.
- note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer
desires a different policy, it should be inserted in `options`.
*/
@discardableResult func saveAll(batchLimit limit: Int? = nil,
transaction: Bool = configuration.isUsingTransactions,
ignoringCustomObjectIdConfig: Bool = false,
options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] {
try await withCheckedThrowingContinuation { continuation in
self.saveAll(batchLimit: limit,
transaction: transaction,
ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig,
options: options,
completion: continuation.resume)
}
}
/**
Creates a collection of objects *asynchronously*.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns an array of Result enums with the object if a save was successful or a
`ParseError` if it failed.
- throws: An error of type `ParseError`.
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
- note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer
desires a different policy, it should be inserted in `options`.
*/
@discardableResult func createAll(batchLimit limit: Int? = nil,
transaction: Bool = configuration.isUsingTransactions,
options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] {
try await withCheckedThrowingContinuation { continuation in
self.createAll(batchLimit: limit,
transaction: transaction,
options: options,
completion: continuation.resume)
}
}
/**
Replaces a collection of objects *asynchronously*.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns an array of Result enums with the object if a save was successful or a
`ParseError` if it failed.
- throws: An error of type `ParseError`.
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
- note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer
desires a different policy, it should be inserted in `options`.
*/
@discardableResult func replaceAll(batchLimit limit: Int? = nil,
transaction: Bool = configuration.isUsingTransactions,
options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] {
try await withCheckedThrowingContinuation { continuation in
self.replaceAll(batchLimit: limit,
transaction: transaction,
options: options,
completion: continuation.resume)
}
}
/**
Updates a collection of objects *asynchronously*.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns an array of Result enums with the object if a save was successful or a
`ParseError` if it failed.
- throws: An error of type `ParseError`.
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
- note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer
desires a different policy, it should be inserted in `options`.
*/
internal func updateAll(batchLimit limit: Int? = nil,
transaction: Bool = configuration.isUsingTransactions,
options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] {
try await withCheckedThrowingContinuation { continuation in
self.updateAll(batchLimit: limit,
transaction: transaction,
options: options,
completion: continuation.resume)
}
}
/**
Deletes a collection of objects *asynchronously*.
- parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched.
is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`.
Defaults to 50.
- parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that
prevents the transaction from completing, then none of the objects are committed to the Parse Server database.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- returns: Returns `nil` if the delete successful or a `ParseError` if it failed.
- throws: An error of type `ParseError`.
- warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the
objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else
the transactions can fail.
*/
@discardableResult func deleteAll(batchLimit limit: Int? = nil,
transaction: Bool = configuration.isUsingTransactions,
options: API.Options = []) async throws -> [(Result<Void, ParseError>)] {
try await withCheckedThrowingContinuation { continuation in
self.deleteAll(batchLimit: limit,
transaction: transaction,
options: options,
completion: continuation.resume)
}
}
}
// MARK: Helper Methods (Internal)
internal extension ParseObject {
// swiftlint:disable:next function_body_length
func ensureDeepSave(options: API.Options = [],
isShouldReturnIfChildObjectsFound: Bool = false) async throws -> ([String: PointerType],
[UUID: ParseFile]) {
var options = options
// Remove any caching policy added by the developer as fresh data
// from the server is needed.
options.remove(.cachePolicy(.reloadIgnoringLocalCacheData))
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
var objectsFinishedSaving = [String: PointerType]()
var filesFinishedSaving = [UUID: ParseFile]()
do {
let object = try ParseCoding.parseEncoder()
.encode(self,
objectsSavedBeforeThisOne: nil,
filesSavedBeforeThisOne: nil)
var waitingToBeSaved = object.unsavedChildren
if isShouldReturnIfChildObjectsFound && waitingToBeSaved.count > 0 {
let error = ParseError(code: .unknownError,
message: """
When using transactions, all child ParseObjects have to originally
be saved to the Parse Server. Either save all child objects first
or disable transactions for this call.
""")
throw error
}
while waitingToBeSaved.count > 0 {
var savableObjects = [ParseEncodable]()
var savableFiles = [ParseFile]()
var nextBatch = [ParseEncodable]()
try waitingToBeSaved.forEach { parseType in
if let parseFile = parseType as? ParseFile {
// ParseFiles can be saved now
savableFiles.append(parseFile)
} else if let parseObject = parseType as? Objectable {
// This is a ParseObject
let waitingObjectInfo = try ParseCoding
.parseEncoder()
.encode(parseObject,
collectChildren: true,
objectsSavedBeforeThisOne: objectsFinishedSaving,
filesSavedBeforeThisOne: filesFinishedSaving)
if waitingObjectInfo.unsavedChildren.count == 0 {
//If this ParseObject has no additional children, it can be saved now
savableObjects.append(parseObject)
} else {
//Else this ParseObject needs to wait until it is children are saved
nextBatch.append(parseObject)
}
}
}
waitingToBeSaved = nextBatch
if waitingToBeSaved.count > 0 && savableObjects.count == 0 && savableFiles.count == 0 {
throw ParseError(code: .unknownError,
message: "Found a circular dependency in ParseObject.")
}
if savableObjects.count > 0 {
let savedChildObjects = try await self.saveAll(objects: savableObjects,
options: options)
let savedChildPointers = try savedChildObjects.compactMap { try $0.get() }
for (index, object) in savableObjects.enumerated() {
let hash = try BaseObjectable.createHash(object)
objectsFinishedSaving[hash] = savedChildPointers[index]
}
}
for savableFile in savableFiles {
filesFinishedSaving[savableFile.id] = try await savableFile.save(options: options)
}
}
return (objectsFinishedSaving, filesFinishedSaving)
} catch {
let defaultError = ParseError(code: .unknownError,
message: error.localizedDescription)
let parseError = error as? ParseError ?? defaultError
throw parseError
}
}
func command(method: Method,
ignoringCustomObjectIdConfig: Bool = false,
options: API.Options,
callbackQueue: DispatchQueue) async throws -> Self {
let (savedChildObjects, savedChildFiles) = try await self.ensureDeepSave(options: options)
do {
let command: API.Command<Self, Self>!
switch method {
case .save:
command = try self.saveCommand(ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig)
case .create:
command = self.createCommand()
case .replace:
command = try self.replaceCommand()
case .update:
command = try self.updateCommand()
}
return try await command
.executeAsync(options: options,
callbackQueue: callbackQueue,
childObjects: savedChildObjects,
childFiles: savedChildFiles)
} catch {
let defaultError = ParseError(code: .unknownError,
message: error.localizedDescription)
let parseError = error as? ParseError ?? defaultError
throw parseError
}
}
}
// MARK: Batch Support
internal extension Sequence where Element: ParseObject {
func batchCommand(method: Method,
batchLimit limit: Int?,
transaction: Bool,
ignoringCustomObjectIdConfig: Bool = false,
options: API.Options,
callbackQueue: DispatchQueue) async throws -> [(Result<Element, ParseError>)] {
var options = options
options.insert(.cachePolicy(.reloadIgnoringLocalCacheData))
var childObjects = [String: PointerType]()
var childFiles = [UUID: ParseFile]()
var commands = [API.Command<Self.Element, Self.Element>]()
let objects = map { $0 }
for object in objects {
let (savedChildObjects, savedChildFiles) = try await object
.ensureDeepSave(options: options,
isShouldReturnIfChildObjectsFound: transaction)
try savedChildObjects.forEach {(key, value) in
guard childObjects[key] == nil else {
throw ParseError(code: .unknownError, message: "circular dependency")
}
childObjects[key] = value
}
try savedChildFiles.forEach {(key, value) in
guard childFiles[key] == nil else {
throw ParseError(code: .unknownError, message: "circular dependency")
}
childFiles[key] = value
}
do {
switch method {
case .save:
commands.append(
try object.saveCommand(ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig)
)
case .create:
commands.append(object.createCommand())
case .replace:
commands.append(try object.replaceCommand())
case .update:
commands.append(try object.updateCommand())
}
} catch {
let defaultError = ParseError(code: .unknownError,
message: error.localizedDescription)
let parseError = error as? ParseError ?? defaultError
throw parseError
}
}
do {
var returnBatch = [(Result<Self.Element, ParseError>)]()
let batchLimit = limit != nil ? limit! : ParseConstants.batchLimit
try canSendTransactions(transaction, objectCount: commands.count, batchLimit: batchLimit)
let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit)
for batch in batches {
let saved = try await API.Command<Self.Element, Self.Element>
.batch(commands: batch, transaction: transaction)
.executeAsync(options: options,
batching: true,
callbackQueue: callbackQueue,
childObjects: childObjects,
childFiles: childFiles)
returnBatch.append(contentsOf: saved)
}
return returnBatch
} catch {
let defaultError = ParseError(code: .unknownError,
message: error.localizedDescription)
let parseError = error as? ParseError ?? defaultError
throw parseError
}
}
}
// MARK: Savable Encodable Version
internal extension ParseEncodable {
func saveAll(objects: [ParseEncodable],
transaction: Bool = configuration.isUsingTransactions,
options: API.Options = [],
callbackQueue: DispatchQueue = .main) async throws -> [(Result<PointerType, ParseError>)] {
try await API.NonParseBodyCommand<AnyCodable, PointerType>
.batch(objects: objects,
transaction: transaction)
.executeAsync(options: options,
callbackQueue: callbackQueue)
}
}
#endif
| [
-1
] |
64f54dc761c1d1c10c88b331b1dcfd9ff6cdd257 | d10836bc01ebb11a9289b12c6f0fa6727ba693ff | /Sources/Version.swift | 5c9288c705b9666bf0580a14db7236d73ab240e1 | [] | no_license | StreamLayer/prefixify | 8a5afffcb77f924096ee1dddc070a2ce5a909e15 | 3617a483de3d70ed80199186d9294f2641677d93 | refs/heads/master | 2020-11-30T23:02:40.127762 | 2020-01-14T03:11:39 | 2020-01-14T03:11:39 | 230,504,331 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 427 | swift | //
// Version.swift
// DePublicize
//
// Created by Vitaly Aminev on 2019-12-27.
//
import Foundation
import SPMUtility
import Basic
struct Version: Command {
let command = "version"
let overview = "prints current version"
init(parser: ArgumentParser) {
_ = parser.add(subparser: command, overview: overview)
}
func run(with arguments: ArgumentParser.Result) throws {
print("0.0.19+streamlayer")
}
}
| [
-1
] |
19614af2668a3d0688e77d45807695bd6c9abd80 | f305ec31a47e0146f0426c85057c975b08db6aad | /RemoteHome/Utility/UIViewController+Utils.swift | 8f2701e34984f4d2495fd0f65cf42cdfdfd47433 | [] | no_license | fordee/RemoteHome | 8d850e77c20714f43bf07cffaa979b9571bbf9d2 | 284b37c36d15ece6642702c2e708068175dd2192 | refs/heads/master | 2020-04-10T01:14:17.486573 | 2019-01-23T17:15:31 | 2019-01-23T17:15:31 | 160,709,955 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 546 | swift | //
// UIViewController+Utils.swift
// RemoteHome
//
// Created by John Forde on 12/12/18.
// Copyright © 2018 4DWare. All rights reserved.
//
import UIKit
extension UIViewController {
public func showErrorDialog(_ message: String) {
print("presentedViewController: \(presentedViewController == nil)")
if presentedViewController == nil { // If another vc is alreadey being presented (e.g. login vc), don't present
let vc = ErrorViewController()
vc.message = message
self.present(vc, animated: true, completion: nil)
}
}
}
| [
-1
] |
30e9aa2c742aa5d50ed6567528136def1615a7f8 | 84f7b510e582983d4bbb2baac0bfa91adf565c73 | /viewer-final/Design System/UIView/UIView+Border.swift | dd741929b74516e3de12b5ee397b94f20a7d2ace | [] | no_license | taijased/final-viewer | 50024c08a6e6e5c45abdf6f4cd638cf79f35edfa | df8cda2f11741c27c1e55b5234e2738b17e52a7e | refs/heads/master | 2022-04-17T03:20:22.688328 | 2020-04-09T17:26:03 | 2020-04-09T17:26:03 | 242,732,728 | 1 | 1 | null | 2020-03-02T18:12:56 | 2020-02-24T12:38:34 | Swift | UTF-8 | Swift | false | false | 1,921 | swift | //
// UIView+Border.swift
// viewer-final
//
// Created by Максим Спиридонов on 18.02.2020.
// Copyright © 2020 Максим Спиридонов. All rights reserved.
//
import UIKit
extension UIView {
enum ViewBorder: String {
case left, right, top, bottom
}
func add(Border border: ViewBorder, withColor color: UIColor = UIColor.lightGray, andWidth width: CGFloat = 1.0) {
let borderView = UIView()
borderView.backgroundColor = color
borderView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(borderView)
NSLayoutConstraint.activate(getConstrainsFor(forView: borderView, WithBorderType: border, andWidth: width))
}
func changeBorderColor(color: UIColor) {
self.subviews.first?.backgroundColor = color
}
private func getConstrainsFor(forView borderView: UIView, WithBorderType border: ViewBorder, andWidth width: CGFloat) -> [NSLayoutConstraint] {
let height = borderView.heightAnchor.constraint(equalToConstant: width)
let widthAnchor = borderView.widthAnchor.constraint(equalToConstant: width)
let leading = borderView.leadingAnchor.constraint(equalTo: self.leadingAnchor)
let trailing = borderView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
let top = borderView.topAnchor.constraint(equalTo: self.topAnchor)
let bottom = borderView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
switch border {
case .bottom:
return [bottom, leading, trailing, height]
case .top:
return [top, leading, trailing, height]
case .left:
return [top, bottom, leading, widthAnchor]
case .right:
return [top, bottom, trailing, widthAnchor]
}
}
}
| [
-1
] |
e63b80b771abc5406e388d93b5f04e438d907069 | e96a06666f6bb670d2a4933a09baf437398bfa12 | /SwiftSnakeUITests/SwiftSnakeUITests.swift | 8a11b10e3e452c4df00475ae04753e90335cd130 | [] | no_license | BlazJurisic/SwiftySnake | d36df0beda12c2d61afc7592892c81e9df12c5a9 | 4c259bd44d1d9bf6ca32e68a1d79537a571919df | refs/heads/master | 2021-06-09T00:23:34.851637 | 2016-12-02T14:47:30 | 2016-12-02T14:47:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,262 | swift | //
// SwiftSnakeUITests.swift
// SwiftSnakeUITests
//
// Created by Blaž Jurišić on 29/11/16.
// Copyright © 2016 Blaž Jurišić. All rights reserved.
//
import XCTest
class SwiftSnakeUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| [
155665,
237599,
229414,
278571,
229425,
180279,
229431,
319543,
213051,
286787,
237638,
311373,
196687,
278607,
311377,
368732,
180317,
278637,
319599,
278642,
131190,
131199,
278669,
278676,
311447,
327834,
278684,
278690,
311459,
278698,
278703,
278707,
180409,
278713,
295099,
139459,
131270,
229591,
147679,
311520,
147680,
319719,
295147,
286957,
319764,
278805,
311582,
278817,
311596,
336177,
98611,
278843,
287040,
319812,
311622,
319816,
229716,
278895,
287089,
139641,
311679,
311692,
106893,
156069,
311723,
377265,
311739,
319931,
278974,
336319,
311744,
278979,
336323,
278988,
278992,
279000,
369121,
279009,
279014,
319976,
279017,
311787,
319986,
279030,
311800,
279033,
279042,
287237,
377352,
279053,
303634,
303635,
279060,
279061,
188954,
279066,
279092,
377419,
303693,
115287,
189016,
287319,
295518,
287327,
279143,
279150,
287345,
287348,
189054,
287359,
303743,
164487,
279176,
311944,
344714,
311948,
311950,
311953,
336531,
287379,
295575,
303772,
221853,
205469,
279207,
295591,
295598,
279215,
279218,
287412,
164532,
287418,
303802,
66243,
287434,
287438,
164561,
303826,
279249,
279253,
369365,
369366,
230105,
295653,
230120,
279278,
312046,
230133,
279293,
205566,
295688,
312076,
295698,
221980,
336678,
262952,
262953,
279337,
262957,
164655,
328495,
303921,
230198,
222017,
295745,
279379,
295769,
230238,
230239,
279393,
303973,
279398,
295797,
295799,
279418,
336765,
287623,
279434,
320394,
189327,
189349,
279465,
304050,
189373,
213956,
345030,
213961,
279499,
304086,
304104,
123880,
320492,
320495,
287730,
320504,
214009,
312313,
312317,
328701,
328705,
418819,
320520,
230411,
320526,
238611,
140311,
238617,
197658,
336930,
189487,
312372,
238646,
238650,
320571,
336962,
238663,
205911,
296023,
156763,
230500,
214116,
279659,
238706,
279666,
312435,
230514,
279686,
222344,
337037,
296091,
238764,
279729,
148674,
312519,
279752,
148687,
189651,
279766,
189656,
279775,
304352,
304353,
279780,
279789,
279803,
320769,
312588,
320795,
320802,
304422,
312628,
345398,
222523,
181568,
279872,
279874,
304457,
345418,
230730,
337228,
296269,
222542,
238928,
296274,
230757,
296304,
312688,
230772,
337280,
296328,
296330,
304523,
9618,
279955,
148899,
279979,
279980,
173492,
279988,
280003,
370122,
280011,
337359,
329168,
312785,
222674,
329170,
280020,
280025,
239069,
320997,
280042,
280043,
329198,
337391,
296434,
288248,
288252,
312830,
230922,
329231,
304655,
230933,
222754,
312879,
230960,
288305,
239159,
157246,
288319,
288322,
280131,
124486,
288328,
239192,
99937,
345697,
312937,
312941,
206447,
288377,
337533,
280193,
239238,
288391,
239251,
280217,
198304,
337590,
280252,
280253,
296636,
321217,
280259,
321220,
296649,
239305,
280266,
9935,
313042,
280279,
18139,
280285,
321250,
337638,
181992,
288492,
34547,
67316,
313082,
288508,
288515,
280326,
116491,
280333,
124691,
116502,
321308,
321309,
280367,
280373,
280377,
321338,
280381,
345918,
280386,
280391,
280396,
337746,
18263,
370526,
296807,
296815,
313200,
313204,
124795,
182145,
280451,
67464,
305032,
124816,
214936,
337816,
124826,
329627,
239515,
214943,
313257,
288698,
214978,
280517,
280518,
214983,
231382,
329696,
190437,
313322,
329707,
174058,
296942,
124912,
313338,
239610,
182277,
313356,
305173,
223269,
354342,
354346,
313388,
124974,
321589,
215095,
288829,
288835,
313415,
239689,
354386,
329812,
223317,
354394,
321632,
280676,
313446,
215144,
288878,
288890,
215165,
329884,
215204,
125108,
280761,
223418,
280767,
338118,
280779,
321744,
280792,
280803,
182503,
338151,
125166,
125170,
395511,
313595,
125180,
125184,
125192,
125197,
125200,
125204,
338196,
125215,
125225,
338217,
321839,
125236,
280903,
289109,
379224,
239973,
313703,
280938,
321901,
354671,
354672,
199030,
223611,
248188,
313726,
240003,
158087,
313736,
240020,
190870,
190872,
289185,
305572,
289195,
338359,
289229,
281038,
281039,
281071,
322057,
182802,
322077,
289328,
338491,
322119,
281165,
281170,
281200,
313970,
297600,
289435,
314020,
248494,
166581,
314043,
363212,
158424,
322269,
338658,
289511,
330473,
330476,
289517,
215790,
125683,
199415,
322302,
289534,
35584,
322312,
346889,
264971,
322320,
166677,
207639,
281378,
289580,
281407,
289599,
281426,
281434,
322396,
281444,
207735,
314240,
158594,
330627,
240517,
289691,
240543,
289699,
289704,
289720,
289723,
281541,
19398,
191445,
183254,
183258,
207839,
314343,
183276,
289773,
248815,
240631,
330759,
322571,
330766,
330789,
248871,
281647,
322609,
314437,
207954,
339031,
314458,
281698,
281699,
322664,
314493,
150656,
347286,
330912,
339106,
306339,
249003,
208044,
322733,
3243,
339131,
290001,
339167,
298209,
290030,
208123,
322826,
126229,
298290,
208179,
159033,
216387,
372039,
224591,
331091,
314708,
150868,
314711,
314721,
281958,
314727,
134504,
306541,
314734,
314740,
314742,
314745,
290170,
224637,
306558,
290176,
306561,
314759,
298378,
314765,
314771,
306580,
224662,
282008,
314776,
282013,
290206,
314788,
314790,
282023,
298406,
241067,
314797,
306630,
306634,
339403,
191980,
282097,
306678,
191991,
290304,
323079,
323083,
323088,
282132,
282135,
175640,
282147,
306730,
290359,
323132,
282182,
224848,
224852,
290391,
306777,
323171,
282214,
224874,
314997,
290425,
339579,
282244,
323208,
282248,
323226,
282272,
282279,
298664,
298666,
306875,
282302,
323262,
323265,
282309,
306891,
241360,
282321,
241366,
282330,
282336,
12009,
282347,
282349,
323315,
200444,
282366,
249606,
282375,
323335,
282379,
216844,
118549,
282390,
282399,
241440,
282401,
339746,
315172,
216868,
241447,
282418,
282424,
282428,
413500,
241471,
315209,
159563,
307024,
307030,
241494,
307038,
282471,
282476,
339840,
315265,
282503,
315272,
315275,
184207,
282517,
298912,
118693,
298921,
126896,
200628,
282572,
282573,
323554,
298987,
282634,
241695,
315431,
315433,
102441,
102446,
282671,
241717,
307269,
233548,
315468,
315477,
200795,
323678,
315488,
315489,
45154,
217194,
233578,
307306,
249976,
241809,
323730,
299166,
233635,
299176,
184489,
323761,
184498,
258233,
299197,
299202,
176325,
299208,
233678,
282832,
356575,
307431,
184574,
217352,
315674,
282908,
299294,
282912,
233761,
282920,
315698,
332084,
307514,
282938,
127292,
168251,
323914,
201037,
282959,
250196,
168280,
323934,
381286,
242027,
242028,
250227,
315768,
315769,
291194,
291193,
291200,
242059,
315798,
291225,
242079,
283039,
299449,
291266,
373196,
283088,
283089,
242138,
176602,
160224,
291297,
242150,
283138,
233987,
324098,
340489,
283154,
291359,
283185,
234037,
340539,
234044,
332379,
111197,
242274,
291455,
316044,
184974,
316048,
316050,
340645,
176810,
299698,
291529,
225996,
135888,
242385,
299737,
234216,
234233,
242428,
291584,
299777,
291591,
283418,
234276,
283431,
242481,
234290,
201534,
283466,
201562,
234330,
275294,
349025,
357219,
177002,
308075,
242540,
242542,
201590,
177018,
308093,
291713,
340865,
299912,
316299,
234382,
308111,
308113,
209820,
283551,
177074,
127945,
340960,
234469,
340967,
324587,
234476,
201721,
234499,
234513,
316441,
300087,
21567,
308288,
160834,
349254,
300109,
234578,
250965,
250982,
234606,
300145,
300147,
234626,
234635,
177297,
308375,
324761,
119965,
234655,
300192,
234662,
300200,
324790,
300215,
283841,
283846,
283849,
316628,
251124,
234741,
283894,
316661,
292092,
234756,
242955,
177420,
292145,
300342,
333114,
333115,
193858,
300355,
300354,
234830,
283990,
357720,
300378,
300379,
316764,
292194,
284015,
234864,
316786,
243073,
292242,
112019,
234902,
333224,
284086,
259513,
284090,
54719,
415170,
292291,
300488,
300490,
234957,
144862,
300526,
308722,
300539,
210429,
292359,
218632,
316951,
374297,
235069,
349764,
194118,
292424,
292426,
333389,
349780,
128600,
235096,
300643,
300645,
243306,
325246,
333438,
235136,
317102,
300725,
300729,
333508,
333522,
325345,
153318,
333543,
284410,
284425,
300810,
300812,
284430,
161553,
284436,
325403,
341791,
325411,
186148,
186149,
333609,
284460,
300849,
325444,
153416,
325449,
317268,
325460,
341846,
284508,
300893,
284515,
276326,
292713,
292719,
325491,
333687,
317305,
317308,
325508,
333700,
243590,
243592,
325514,
350091,
350092,
350102,
333727,
219046,
333734,
284584,
292783,
300983,
153553,
292835,
6116,
292838,
317416,
325620,
333827,
243720,
292901,
325675,
243763,
325695,
333902,
227432,
194667,
284789,
284790,
292987,
227459,
194692,
235661,
333968,
153752,
284827,
333990,
284840,
284843,
227517,
309443,
227525,
301255,
227536,
301270,
301271,
325857,
334049,
317676,
309504,
194832,
227601,
325904,
334104,
211239,
334121,
317738,
325930,
227655,
383309,
391521,
285031,
416103,
227702,
211327,
227721,
285074,
227730,
285083,
293275,
317851,
227743,
285089,
293281,
301482,
375211,
334259,
293309,
317889,
326083,
129484,
326093,
285152,
195044,
334315,
236020,
293368,
317949,
342537,
309770,
334345,
342560,
227881,
293420,
236080,
23093,
244279,
244280,
301635,
309831,
55880,
301647,
326229,
309847,
244311,
244326,
301688,
244345,
301702,
334473,
326288,
227991,
285348,
318127,
293552,
285360,
285362,
342705,
154295,
342757,
285419,
170735,
342775,
375552,
228099,
285443,
285450,
326413,
285457,
285467,
326428,
318247,
293673,
318251,
301872,
285493,
285496,
301883,
342846,
293702,
318279,
244569,
301919,
293729,
351078,
310132,
228214,
269179,
228232,
416649,
236427,
252812,
293780,
310166,
277404,
310177,
293801,
326571,
326580,
326586,
359365,
211913,
326602,
56270,
203758,
277493,
293894,
293911,
326684,
113710,
318515,
203829,
277600,
285795,
228457,
318571,
187508,
302202,
285819,
285823,
285833,
318602,
285834,
228492,
162962,
187539,
326803,
285850,
302239,
302251,
294069,
294075,
64699,
228541,
343230,
310496,
228587,
302319,
228608,
318732,
245018,
318746,
130342,
130344,
130347,
286012,
294210,
286019,
294220,
318804,
294236,
327023,
327030,
310650,
179586,
294278,
368012,
318860,
318876,
343457,
245160,
286128,
286133,
310714,
302523,
228796,
302530,
228804,
310725,
310731,
302539,
310735,
327122,
310747,
286176,
187877,
310758,
40439,
286201,
359931,
286208,
245249,
228868,
302602,
294413,
359949,
302613,
302620,
245291,
310853,
286281,
196184,
212574,
204386,
204394,
138862,
310896,
294517,
286344,
179853,
286351,
188049,
229011,
179868,
229021,
302751,
245413,
212649,
286387,
286392,
302778,
286400,
212684,
302798,
286419,
294621,
294629,
286457,
286463,
319232,
278273,
278292,
278294,
294699,
286507,
319289,
237397,
188250,
237411,
327556,
188293,
311183,
294806,
294808,
319393,
294820,
294824,
343993,
98240,
294849,
24531,
294887,
278507,
311277,
327666,
278515
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.