repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pksprojects/ElasticSwift
|
refs/heads/master
|
Sources/ElasticSwiftCore/ElasticSwiftCore.swift
|
mit
|
1
|
//
// utils.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 6/18/17.
//
//
import Foundation
// MARK: - Serializer Protocol
public protocol Serializer {
func decode<T>(data: Data) -> Result<T, DecodingError> where T: Decodable
func encode<T>(_ value: T) -> Result<Data, EncodingError> where T: Encodable
}
// MARK: - HTTPSettings
public enum HTTPSettings {
case managed(adaptorConfig: HTTPAdaptorConfiguration)
case independent(adaptor: HTTPClientAdaptor)
}
// MARK: - ClientCredential
public protocol ClientCredential {
var token: String { get }
}
// MARK: - QueryParams enums
/// Enum QueryParams represent all the query params supported by ElasticSearch.
public enum QueryParams: String {
case format
case h
case help
case local
case masterTimeout = "master_timeout"
case s
case v
case ts
case bytes
case health
case pri
case fullId = "full_id"
case size
case ignoreUnavailable = "ignore_unavailable"
case actions
case detailed
case nodeId = "node_id"
case parentNode = "parent_node"
case version
case versionType = "version_type"
case refresh
case parentTask = "parent_task"
case waitForActiveShards = "wait_for_active_shards"
case waitForCompletion = "wait_for_completion"
case opType = "op_type"
case routing
case timeout
case ifSeqNo = "if_seq_no"
case ifPrimaryTerm = "if_primary_term"
case pipeline
case includeTypeName = "include_type_name"
case parent
case retryOnConflict = "retry_on_conflict"
case fields
case lang
case source = "_source"
case sourceIncludes = "_source_includes"
case sourceExcludes = "_source_excludes"
case conflicts
case requestsPerSecond = "requests_per_second"
case slices
case requestCache = "request_cache"
case stats
case from
case scrollSize = "scroll_size"
case realTime = "realtime"
case preference
case storedFields = "stored_fields"
case termStatistics = "term_statistics"
case fieldStatistics = "field_statistics"
case offsets
case positions
case payloads
case scroll
case restTotalHitsAsInt = "rest_total_hits_as_int"
case searchType = "search_type"
case ignoreThrottled = "ignore_throttled"
case allowNoIndices = "allow_no_indices"
case expandWildcards = "expand_wildcards"
case minScore = "min_score"
case q
case analyzer
case analyzeWildcard = "analyze_wildcard"
case defaultOperator = "default_operator"
case df
case lenient
case terminateAfter = "terminate_after"
case typedKeys = "typed_keys"
case level
case waitForNodes = "wait_for_nodes"
case waitForEvents = "wait_for_events"
case waitForNoRelocatingShards = "wait_for_no_relocating_shards"
case waitForNoInitializingShards = "wait_for_no_initializing_shards"
case waitForStatus = "wait_for_status"
case flatSettings = "flat_settings"
case includeDefaults = "include_defaults"
}
enum EndPointCategory: String {
case cat = "_cat"
case cluster = "_cluster"
case ingest = "_ingest"
case nodes = "_nodes"
case snapshots = "_snapshots"
case tasks = "_tasks"
}
enum EndPointPath: String {
case aliases
case allocation
case count
case health
case indices
case master
case nodes
case recovery
case shards
case segments
case pendingTasks = "pending_tasks"
case threadPool = "thread_pool"
case fieldData = "fielddata"
case plugins
case nodeAttributes = "nodeattrs"
case repositories
case snapshots
case tasks
case templates
case state
case stats
case reroute
case settings
case allocationExplain = "allocation/explain"
case pipeline
case simulate
case hotThreads = "hotthreads"
case restore = "_recovery"
case status = "_status"
case verify = "_verify"
case `default` = ""
}
/// Enum representing URLScheme
public enum URLScheme: String {
case http
case https
}
/// Generic protocol for Type Builders in ElasticSwift
public protocol ElasticSwiftTypeBuilder {
associatedtype ElasticSwiftType
func build() throws -> ElasticSwiftType
}
|
12ee3b80f7432b288f1b987e616bfb91
| 24.279762 | 80 | 0.68519 | false | false | false | false |
WalterCreazyBear/Swifter30
|
refs/heads/master
|
DotDemo/DotDemo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// DotDemo
//
// Created by Bear on 2017/6/29.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var dotOne : UIImageView!
var dotTwo : UIImageView!
var dotThree : UIImageView!
lazy var logoImage : UIImageView = {
let view : UIImageView = UIImageView(frame: CGRect.init(x: 0, y: 50, width: UIScreen.main.bounds.width, height: 100))
view.image = #imageLiteral(resourceName: "logo")
view.contentMode = .scaleAspectFit
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// view.addSubview(logoImage)
dotOne = generateImgeView(frame: CGRect.init(x: 50, y: 150, width: 30, height: 30))
dotTwo = generateImgeView(frame: CGRect.init(x: 90, y: 150, width: 30, height: 30))
dotThree = generateImgeView(frame: CGRect.init(x: 130, y: 150, width: 30, height: 30))
view.addSubview(dotOne)
view.addSubview(dotTwo)
view.addSubview(dotThree)
startAnimation()
}
func startAnimation()
{
dotOne.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
dotTwo.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
dotThree.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
UIView.animate(withDuration: 0.6, delay: 0.0, options: [.repeat, .autoreverse], animations: {
self.dotOne.transform = CGAffineTransform.identity
}, completion: nil)
UIView.animate(withDuration: 0.6, delay: 0.2, options: [.repeat, .autoreverse], animations: {
self.dotTwo.transform = CGAffineTransform.identity
}, completion: nil)
UIView.animate(withDuration: 0.6, delay: 0.4, options: [.repeat, .autoreverse], animations: {
self.dotThree.transform = CGAffineTransform.identity
}, completion: nil)
}
func generateImgeView(frame:CGRect) -> UIImageView {
let view : UIImageView = UIImageView(frame: frame)
view.image = #imageLiteral(resourceName: "dot")
view.contentMode = .scaleAspectFit
return view
}
}
|
7e35cc10e3b8c06f7b9bdd2784a4a77f
| 33.242424 | 125 | 0.626991 | false | false | false | false |
rwash8347/desktop-apod
|
refs/heads/master
|
DesktopAPOD/DesktopAPOD/URLSession-Extension.swift
|
mit
|
1
|
//
// URLSession-Extension.swift
// APODDesktopImage
//
// Created by Richard Ash on 3/28/17.
// Copyright © 2017 Richard. All rights reserved.
//
import Foundation
enum URLSessionError: Error {
case unknown(URLResponse?)
}
extension URLSession {
func dataTask(with url: URL, completion: @escaping (Result<Data>) -> Void) -> URLSessionDataTask {
return self.dataTask(with: url) { (data, response, error) in
if let error = error, data == nil {
completion(.failure(error))
} else if let data = data, error == nil {
completion(.success(data))
} else {
completion(.failure(URLSessionError.unknown(response)))
}
}
}
}
|
91448bf3fc72972a424c7199d04f8781
| 24.259259 | 100 | 0.646628 | false | false | false | false |
Bunn/macGist
|
refs/heads/master
|
macGist/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// macGist
//
// Created by Fernando Bunn on 20/06/17.
// Copyright © 2017 Fernando Bunn. All rights reserved.
//
import Cocoa
class LoginViewController: NSViewController {
@IBOutlet private weak var passwordTextField: NSSecureTextField!
@IBOutlet private weak var usernameTextField: NSTextField!
@IBOutlet private weak var spinner: NSProgressIndicator!
@IBOutlet private weak var loginButton: NSButton!
@IBOutlet private weak var githubClientIdTextField: NSTextField!
@IBOutlet private weak var githubClientSecretTextField: NSTextField!
@IBOutlet weak var errorLabel: NSTextField!
weak var delegate: LoginViewControllerDelegate?
private let githubAPI = GitHubAPI()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupCredentialsUI()
}
@IBAction private func loginButtonClicked(_ sender: NSButton) {
setupUI()
authenticate()
}
@IBAction private func cancelButtonClicked(_ sender: NSButton) {
delegate?.didFinish(controller: self)
}
@IBAction func saveButtonClicked(_ sender: NSButton) {
GitHubCredentialManager.clientId = githubClientIdTextField.stringValue
GitHubCredentialManager.clientSecret = githubClientSecretTextField.stringValue
}
fileprivate func setupUI() {
spinner.isHidden = true
errorLabel.isHidden = true
}
private func showSpinner(show: Bool) {
spinner.isHidden = !show
loginButton.isHidden = show
if show {
spinner.startAnimation(nil)
} else {
spinner.stopAnimation(nil)
}
}
fileprivate func displayError(message: String) {
showSpinner(show: false)
errorLabel.isHidden = false
errorLabel.stringValue = message
}
private func openTwoFactorController() {
let twoFactorController = TwoFactorViewController()
twoFactorController.delegate = self
presentAsSheet(twoFactorController)
}
fileprivate func authenticate(twoFactorCode: String? = nil) {
showSpinner(show: true)
githubAPI.authenticate(username: usernameTextField.stringValue, password: passwordTextField.stringValue, twoFactorCode: twoFactorCode) { (error: Error?) in
print("Error \(String(describing: error))")
DispatchQueue.main.async {
if error != nil {
if let apiError = error as? GitHubAPI.GitHubAPIError {
switch apiError {
case .twoFactorRequired:
self.openTwoFactorController()
return
default: break
}
}
self.displayError(message: "Bad username or password")
} else {
UserDefaults.standard.set(self.usernameTextField.stringValue, forKey: UserDefaultKeys.usernameKey.rawValue)
self.delegate?.didFinish(controller: self)
}
}
}
}
private func setupCredentialsUI() {
githubClientIdTextField.stringValue = GitHubCredentialManager.clientId ?? ""
githubClientSecretTextField.stringValue = GitHubCredentialManager.clientSecret ?? ""
}
}
protocol LoginViewControllerDelegate: class {
func didFinish(controller: LoginViewController)
}
extension LoginViewController: TwoFactorViewControllerDelegate {
func didEnter(code: String, controller: TwoFactorViewController) {
authenticate(twoFactorCode: code)
controller.dismiss(nil)
}
func didCancel(controller: TwoFactorViewController) {
setupUI()
displayError(message: "Two-Factor cancelled")
controller.dismiss(nil)
}
}
|
d96a3d00652cd330457f08c07b8fb095
| 32.612069 | 163 | 0.640934 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS
|
refs/heads/master
|
SmartReceipts/Modules/Columns/ColumnsInteractor.swift
|
agpl-3.0
|
2
|
//
// ColumnsInteractor.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 12/07/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import Viperit
import RxSwift
class ColumnsInteractor: Interactor {
func columns(forCSV: Bool) -> Observable<[Column]> {
let columns = forCSV ? Database.sharedInstance().allCSVColumns() : Database.sharedInstance().allPDFColumns()
for (idx, column) in columns!.enumerated() {
let col = column as! Column
col.uniqueIdentity = "\(idx)"
}
return Observable<[Column]>.just(columns as! [Column])
}
func addColumn(_ column: Column, isCSV: Bool) {
let db = Database.sharedInstance()
let orderId = isCSV ? db.nextCustomOrderIdForCSVColumn() : db.nextCustomOrderIdForPDFColumn()
column.customOrderId = orderId
let result = isCSV ? db.addCSVColumn(column) : db.addPDFColumn(column)
Logger.info("Add Column '\(column.name!)'. Result: \(result)")
}
func removeColumn(_ column: Column, isCSV: Bool) {
let db = Database.sharedInstance()
let result = isCSV ? db.removeCSVColumn(column) : db.removePDFColumn(column)
Logger.info("Remove Column '\(column.name!)'. Result: \(result)")
}
func reorder(columnLeft: Column, columnRight: Column, isCSV: Bool) {
let db = Database.sharedInstance()
let result = isCSV
? db.reorderCSVColumn(columnLeft, withCSVColumn: columnRight)
: db.reorderPDFColumn(columnLeft, withPDFColumn: columnRight)
Logger.info("Reorder columns. Result: \(result)")
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension ColumnsInteractor {
var presenter: ColumnsPresenter {
return _presenter as! ColumnsPresenter
}
}
|
4e730f1de5d9dc43ff9b8f517d80e278
| 34.576923 | 116 | 0.654595 | false | false | false | false |
anotheren/TrafficPolice
|
refs/heads/master
|
Source/TrafficManager.swift
|
mit
|
1
|
//
// TrafficManager.swift
// TrafficPolice
//
// Created by 刘栋 on 2016/11/17.
// Copyright © 2016年 anotheren.com. All rights reserved.
//
import Foundation
import SwiftTimer
public class TrafficManager {
public static let shared = TrafficManager()
public private(set) var interval: Double
public weak var delegate: TrafficManagerDelegate?
private lazy var timer: SwiftTimer = {
let timer = SwiftTimer.repeaticTimer(interval: .fromSeconds(self.interval)) {[weak self] timer in
self?.updateSummary()
}
return timer
}()
private var counter: TrafficCounter = TrafficCounter()
private var summary: TrafficSummary?
private init(interval: Double = 1.0) {
self.interval = interval
}
public func reset() {
summary = nil
}
public func start() {
timer.start()
}
public func cancel() {
timer.suspend()
}
private func updateSummary() {
let newSummary: TrafficSummary = {
if let summary = self.summary {
return summary.update(by: counter.usage, time: interval)
} else {
return TrafficSummary(origin: counter.usage)
}
}()
delegate?.post(summary: newSummary)
summary = newSummary
}
}
public protocol TrafficManagerDelegate: class {
func post(summary: TrafficSummary)
}
|
10565fc7031ab68dd6472dd92fb58bec
| 22.126984 | 105 | 0.601235 | false | false | false | false |
hisui/ReactiveSwift
|
refs/heads/master
|
ReactiveSwift/UITableView+Subject.swift
|
mit
|
1
|
// Copyright (c) 2014 segfault.jp. All rights reserved.
import UIKit
private var selectionSubjectKey = "selectionSubjectKey"
public extension UITableView {
public var selectionSubject: SetCollection<NSIndexPath> {
return getAdditionalFieldOrUpdate(&selectionSubjectKey) { TableViewSelectionSubject<()>(self) }
}
public func setDataSource<T, C: UITableViewCell>(model: SeqCollection<T>, prototypeCell: String, _ f: (T, C) -> ()) -> Stream<()> {
return setDataSource(model) { [weak self] (e, i) in
let (cell) = self!.dequeueReusableCellWithIdentifier(prototypeCell) as! C
f(e, cell)
return cell
}
}
public func setDataSource<T, C: UITableViewCell>(model: SeqView<T>, prototypeCell: String, _ f: (T, C) -> ()) -> Stream<()> {
return setDataSource(model) { [weak self] (e, i) in
let (cell) = self!.dequeueReusableCellWithIdentifier(prototypeCell) as! C
f(e, cell)
return cell
}
}
public func setDataSource<T>(model: SeqCollection<T>, _ f: (T, Int) -> UITableViewCell) -> Stream<()> {
return setDataSource(MutableTableViewDataSource(SeqViewErasure(model, f)), model)
}
public func setDataSource<T>(model: SeqView<T>, _ f: (T, Int) -> UITableViewCell) -> Stream<()> {
return setDataSource(TableViewDataSource(SeqViewErasure(model, f)), model)
}
private func setDataSource<X>(source: TableViewDataSource, _ model: SeqView<X>) -> Stream<()> {
dataSource = source
reloadData()
return mix([Streams.pure(())
, model.skip(1)
.foreach { [weak self] e -> () in self?.update(e, source.model); () }
.onClose { [weak self] _ -> () in
self?.dataSource = nil
self?.reloadData()
}
.nullify()])
}
private func update<E>(update: SeqView<E>.UpdateType, _ `guard`: AnyObject) {
if update.sender === `guard` {
return
}
beginUpdates()
for e in update.detail {
deleteRowsAtIndexPaths(e.deletes, withRowAnimation: .None)
insertRowsAtIndexPaths(e.inserts, withRowAnimation: .None)
}
endUpdates()
}
}
private class TableViewSelectionSubject<T>: SetCollection<NSIndexPath> {
private weak var table: UITableView!
private var observer: NotificationObserver? = nil
init(_ table: UITableView) {
self.table = table
super.init()
observer = NotificationObserver(nil, UITableViewSelectionDidChangeNotification, nil)
{ [weak self] e in
if (e.object === self?.table) {
self!.assign(self!.table.indexPathsForSelectedRows ?? [], sender: table)
}
}
}
override func commit(update: UpdateType) {
if update.sender !== table {
for e in update.detail.insert {
table.selectRowAtIndexPath(e, animated: false, scrollPosition: .None)
}
for e in update.detail.delete {
table.deselectRowAtIndexPath(e, animated: false)
}
}
super.commit(update)
}
}
internal protocol SeqViewBridge: NSObjectProtocol {
var count: Int { get }
func viewForIndex(path: NSIndexPath) -> UIView
func removeAt(index: NSIndexPath)
func move(from: NSIndexPath, to: NSIndexPath)
}
internal class SeqViewErasure<T, V: UIView>: NSObject, SeqViewBridge {
private let a: SeqView<T>
private let f: (T, Int) -> V
init(_ a: SeqView<T>, _ f: (T, Int) -> V) {
self.a = a
self.f = f
}
var count: Int { return Int(a.count) }
var mutable: SeqCollection<T> { return a as! SeqCollection<T> }
func viewForIndex(path: NSIndexPath) -> UIView {
return f(a[path.row]!, path.row)
}
func removeAt(index: NSIndexPath) {
mutable.removeAt(index.row)
}
func move(from: NSIndexPath, to: NSIndexPath) {
mutable.move(from.row, to: to.row, sender: self)
}
}
private class TableViewDataSource: NSObject, UITableViewDataSource {
let model: SeqViewBridge
required init (_ model: SeqViewBridge) {
self.model = model
}
@objc func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return model.count
}
@objc func tableView(_: UITableView, cellForRowAtIndexPath path: NSIndexPath) -> UITableViewCell {
return model.viewForIndex(path) as! UITableViewCell
}
}
private class MutableTableViewDataSource: TableViewDataSource {
@objc func tableView(_: UITableView, canEditRowAtIndexPath _: NSIndexPath) -> Bool {
return true
}
@objc func tableView(_: UITableView, commitEditingStyle style: UITableViewCellEditingStyle, forRowAtIndexPath path: NSIndexPath) {
if style == .Delete {
model.removeAt(path)
}
}
@objc func tableView(_: UITableView, canMoveRowAtIndexPath _: NSIndexPath) -> Bool {
return true
}
@objc func tableView(_: UITableView, moveRowAtIndexPath src: NSIndexPath, toIndexPath dest: NSIndexPath) {
model.move(src, to: dest)
}
}
internal extension SeqDiff {
var deletes: [NSIndexPath] { return indexPathsInRange(offset ..< (offset+delete)) }
var inserts: [NSIndexPath] { return indexPathsInRange(offset ..< (offset+UInt(insert.count))) }
}
private func indexPathsInRange(range: Range<UInt>) -> [NSIndexPath] {
var a = [NSIndexPath]()
for i in range {
a.append(NSIndexPath(forRow: Int(i), inSection: 0))
}
return a
}
|
e42375227f66d52f1bd4f5e1bc97a293
| 29.728723 | 135 | 0.603947 | false | false | false | false |
chengxianghe/MissGe
|
refs/heads/master
|
MissGe/MissGe/Class/Project/Request/Mine/MLMineRequest.swift
|
mit
|
1
|
//
// MLMineQuestionRequest.swift
// MissLi
//
// Created by chengxianghe on 16/7/28.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
import TUNetworking
//我的提问
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=myThemePostList&pg=1&size=20&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&uid=19793&orderby=add_date&orderway=desc
class MLMineQuestionRequest: MLBaseRequest {
var page = 1
//c=post&a=myThemePostList&pg=1&size=20&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU& uid=19793&orderby=add_date&orderway=desc
override func requestParameters() -> [String : Any]? {
let dict: [String : String] = ["c":"post","a":"myThemePostList","uid":MLNetConfig.shareInstance.userId,"token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20","orderby":"add_date","orderway":"desc"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
}
//我的回复
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=myRethemepostList&pg=1&size=20& token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU& orderby=add_date&orderway=desc
class MLMineAnswerRequest: MLBaseRequest {
var page = 1
//c=post&a=myRethemepostList&pg=1&size=20&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&orderby=add_date&orderway=desc
override func requestParameters() -> [String : Any]? {
//"uid":MLNetConfig.shareInstance.userId,
let dict: [String : String] = ["c":"post","a":"myRethemepostList","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20","orderby":"add_date","orderway":"desc"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
}
//我的收藏
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=article&a=getcollect&token=XPdcOIKGqf7nmgZSoqA9eshEbpWRSs7%252B%252BkqAtMdIf5uoyjo&page=0&size=20&orderby=add_date
class MLMineFavoriteRequest: MLBaseRequest {
var page = 1
//c=article&a=getcollect&token=XPdcOIKGqf7nmgZSoqA9eshEbpWRSs7%252B%252BkqAtMdIf5uoyjo&page=0&size=20
override func requestParameters() -> [String : Any]? {
//,"orderby":"add_date","orderway":"desc"
let dict: [String : String] = ["c":"article","a":"getcollect","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
override func requestVerifyResult() -> Bool {
guard let dict = self.responseObject as? NSDictionary else {
return false
}
return (dict["result"] as? String) == "200"
}
}
//我的评论
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=user&a=comlist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&page=0&size=20
class MLMineCommentRequest: MLBaseRequest {
var page = 1
//c=user&a=comlist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&page=0&size=20
override func requestParameters() -> [String : Any]? {
//,"orderby":"add_date","orderway":"desc"
let dict: [String : String] = ["c":"user","a":"comlist","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
}
//圈儿消息
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=user&a=replylistV2&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20
class MLMineSquareMessageRequest: MLBaseRequest {
var page = 1
//c=user&a=replylistV2&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20
override func requestParameters() -> [String : Any]? {
//,"orderby":"add_date","orderway":"desc"
let dict: [String : String] = ["c":"user","a":"replylistV2","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
}
//文章评论
//http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=user&a=commelist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20
class MLMineArticleCommentRequest: MLBaseRequest {
var page = 1
//c=user&a=commelist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20
override func requestParameters() -> [String : Any]? {
//,"orderby":"add_date","orderway":"desc"
let dict: [String : String] = ["c":"user","a":"commelist","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"]
return dict
}
override func requestHandleResult() {
print("requestHandleResult -- \(self.classForCoder)")
}
}
|
29bb768cc51a2ac861a41922e2d659f4
| 41.302326 | 273 | 0.702034 | false | true | false | false |
tdgunes/TDGMessageKit
|
refs/heads/master
|
Example/Example/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Example
//
// Created by Taha Doğan Güneş on 10/07/15.
// Copyright (c) 2015 Taha Doğan Güneş. All rights reserved.
//
import UIKit
import TDGMessageKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var upperMessageBox = TDGMessageBox(orientation: .Bottom)
upperMessageBox.titleLabel.text = "TitleLabel Example Text"
upperMessageBox.bodyLabel.text = "BodyLabel Example Text"
upperMessageBox.view.alpha = 0.8
upperMessageBox.addTo(self.view)
upperMessageBox.toggle()
var bottomMessageBox = TDGMessageBox(orientation: .Top)
bottomMessageBox.titleLabel.text = "TitleLabel Example Text"
bottomMessageBox.bodyLabel.text = "BodyLabel Example Text"
bottomMessageBox.addTo(self.view)
bottomMessageBox.toggle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
4e3c29738342ec7d089c2a0e596cbb58
| 27.675 | 80 | 0.681779 | false | false | false | false |
lyb5834/YBAttributeTextTapForSwfit
|
refs/heads/master
|
YBAttributeTextTapForSwfit-Demo/YBAttributeTextTapForSwfit/YBAttributeTextTapForSwfit.swift
|
mit
|
2
|
//
// YBAttributeTextTapForSwfit.swift
// YBAttributeTextTapForSwfit
//
// Created by LYB on 16/7/7.
// Copyright © 2016年 LYB. All rights reserved.
//
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
private var isTapAction : Bool?
private var attributeStrings : [YBAttributeModel]?
private var tapBlock : ((_ str : String ,_ range : NSRange ,_ index : Int) -> Void)?
private var isTapEffect : Bool = true
private var effectDic : Dictionary<String , NSAttributedString>?
extension UILabel {
// MARK: - Objects
/// 是否打开点击效果,默认是打开
var enabledTapEffect : Bool {
set {
isTapEffect = newValue
}
get {
return isTapEffect
}
}
// MARK: - mainFunction
/**
给文本添加点击事件
- parameter strings: 需要点击的字符串数组
- parameter tapAction: 点击事件回调
*/
func yb_addAttributeTapAction( _ strings : [String] , tapAction : @escaping ((String , NSRange , Int) -> Void)) -> Void {
yb_getRange(strings)
tapBlock = tapAction
}
// MARK: - touchActions
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if isTapAction == false {
return
}
let touch = touches.first
let point = touch?.location(in: self)
yb_getTapFrame(point!) { (String, NSRange, Int) -> Void in
if tapBlock != nil {
tapBlock! (String, NSRange , Int)
}
if isTapEffect {
self.yb_saveEffectDicWithRange(NSRange)
self.yb_tapEffectWithStatus(true)
}
}
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if isTapEffect {
self.performSelector(onMainThread: #selector(self.yb_tapEffectWithStatus(_:)), with: nil, waitUntilDone: false)
}
}
open override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
if isTapEffect {
self.performSelector(onMainThread: #selector(self.yb_tapEffectWithStatus(_:)), with: nil, waitUntilDone: false)
}
}
override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if isTapAction == true {
let result = yb_getTapFrame(point, result: { (
String, NSRange, Int) -> Void in
})
if result == true {
return self
}
}
return super.hitTest(point, with: event)
}
// MARK: - getTapFrame
@discardableResult
fileprivate func yb_getTapFrame(_ point : CGPoint , result : ((_ str : String ,_ range : NSRange ,_ index : Int) -> Void)) -> Bool {
let framesetter = CTFramesetterCreateWithAttributedString(self.attributedText!)
var path = CGMutablePath()
path.addRect(self.bounds, transform: CGAffineTransform.identity)
var frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
let range = CTFrameGetVisibleStringRange(frame)
if self.attributedText?.length > range.length {
var m_font : UIFont
let n_font = self.attributedText?.attribute(NSAttributedString.Key.font, at: 0, effectiveRange: nil)
if n_font != nil {
m_font = n_font as! UIFont
}else if (self.font != nil) {
m_font = self.font
}else {
m_font = UIFont.systemFont(ofSize: 17)
}
path = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height + m_font.lineHeight), transform: CGAffineTransform.identity)
frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
}
let lines = CTFrameGetLines(frame)
if lines == [] as CFArray {
return false
}
let count = CFArrayGetCount(lines)
var origins = [CGPoint](repeating: CGPoint.zero, count: count)
CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), &origins)
let transform = CGAffineTransform(translationX: 0, y: self.bounds.size.height).scaledBy(x: 1.0, y: -1.0);
let verticalOffset = 0.0
for i : CFIndex in 0..<count {
let linePoint = origins[i]
let line = CFArrayGetValueAtIndex(lines, i)
let lineRef = unsafeBitCast(line,to: CTLine.self)
let flippedRect : CGRect = yb_getLineBounds(lineRef , point: linePoint)
var rect = flippedRect.applying(transform)
rect = rect.insetBy(dx: 0, dy: 0)
rect = rect.offsetBy(dx: 0, dy: CGFloat(verticalOffset))
let style = self.attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: nil)
var lineSpace : CGFloat = 0.0
if (style != nil) {
lineSpace = (style as! NSParagraphStyle).lineSpacing
}else {
lineSpace = 0.0
}
let lineOutSpace = (CGFloat(self.bounds.size.height) - CGFloat(lineSpace) * CGFloat(count - 1) - CGFloat(rect.size.height) * CGFloat(count)) / 2
rect.origin.y = lineOutSpace + rect.size.height * CGFloat(i) + lineSpace * CGFloat(i)
if rect.contains(point) {
let relativePoint = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY)
var index = CTLineGetStringIndexForPosition(lineRef, relativePoint)
var offset : CGFloat = 0.0
CTLineGetOffsetForStringIndex(lineRef, index, &offset)
if offset > relativePoint.x {
index = index - 1
}
let link_count = attributeStrings?.count
for j in 0 ..< link_count! {
let model = attributeStrings![j]
let link_range = model.range
if NSLocationInRange(index, link_range!) {
result(model.str!,model.range!,j)
return true
}
}
}
}
return false
}
fileprivate func yb_getLineBounds(_ line : CTLine , point : CGPoint) -> CGRect {
var ascent : CGFloat = 0.0;
var descent : CGFloat = 0.0;
var leading : CGFloat = 0.0;
let width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading)
let height = ascent + fabs(descent) + leading
return CGRect.init(x: point.x, y: point.y , width: CGFloat(width), height: height)
}
// MARK: - getRange
fileprivate func yb_getRange(_ strings : [String]) -> Void {
if self.attributedText?.length == 0 {
return;
}
self.isUserInteractionEnabled = true
isTapAction = true
var totalString = self.attributedText?.string
attributeStrings = [];
for str : String in strings {
let range = totalString?.range(of: str)
if (range?.lowerBound != nil) {
totalString = totalString?.replacingCharacters(in: range!, with: self.yb_getString(str.characters.count))
let model = YBAttributeModel()
model.range = totalString?.nsRange(from: range!)
model.str = str
attributeStrings?.append(model)
}
}
}
fileprivate func yb_getString(_ count : Int) -> String {
var string = ""
for _ in 0 ..< count {
string = string + " "
}
return string
}
// MARK: - tapEffect
fileprivate func yb_saveEffectDicWithRange(_ range : NSRange) -> Void {
effectDic = [:]
let subAttribute = self.attributedText?.attributedSubstring(from: range)
_ = effectDic?.updateValue(subAttribute!, forKey: NSStringFromRange(range))
}
@objc fileprivate func yb_tapEffectWithStatus(_ status : Bool) -> Void {
if isTapEffect {
let attStr = NSMutableAttributedString.init(attributedString: self.attributedText!)
let subAtt = NSMutableAttributedString.init(attributedString: (effectDic?.values.first)!)
let range = NSRangeFromString(effectDic!.keys.first!)
if status {
subAtt.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.lightGray, range: NSMakeRange(0, subAtt.length))
attStr.replaceCharacters(in: range, with: subAtt)
}else {
attStr.replaceCharacters(in: range, with: subAtt)
}
self.attributedText = attStr
}
}
}
private class YBAttributeModel: NSObject {
var range : NSRange?
var str : String?
}
private extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
return NSRange(range,in : self)
}
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
}
|
f3ad2e9cba7334d022fb0c0dd7e50afc
| 31.884848 | 167 | 0.53861 | false | false | false | false |
pkc456/Roastbook
|
refs/heads/master
|
Roastbook/Roastbook/Business Layer/FeedBusinessLayer.swift
|
mit
|
1
|
//
// FeedBusinessLayer.swift
// Roastbook
//
// Created by Pradeep Choudhary on 4/8/17.
// Copyright © 2017 Pardeep chaudhary. All rights reserved.
//
import Foundation
class FeedBusinessLayer: NSObject
{
class var sharedInstance: FeedBusinessLayer {
struct Static {
static let instance: FeedBusinessLayer = FeedBusinessLayer()
}
return Static.instance
}
func parseArrayJsonData(data: NSArray) -> [Feed] {
let modelObject = Feed.modelsFromDictionaryArray(array: data)
return modelObject
}
//Methods to get dummy data
func getFeedInformationDataArray() -> [Feed] {
let feedDictionary = getFeedListData()
let arrayOfMusicData = Feed.modelsFromDictionaryArray(array: [feedDictionary])
return arrayOfMusicData
}
private func getFeedListData() -> NSMutableDictionary{
let data : NSMutableDictionary = NSMutableDictionary()
data.setValue("I am rockstar. I am rockstar. I am rockstar What are your views. I am waiting. Slide across the down button. Show me! Can you I am rockstar. I am rockstar. I am rockstar What are your views. I am waiting. Slide across the down button. Show me! Can you. Testing", forKey: KKEY_FEED)
data.setValue("Pardeep", forKey: KKEY_FEED_NAME)
return data
}
}
|
20e9eb2bde2253694757de5d8b46d22d
| 33.1 | 304 | 0.673754 | false | false | false | false |
snazzware/HexMatch
|
refs/heads/master
|
HexMatch/Scenes/GameScene.swift
|
gpl-3.0
|
2
|
//
// GameScene.swift
// HexMatch
//
// Created by Josh McKee on 1/11/16.
// Copyright (c) 2016 Josh McKee. All rights reserved.
//
import SpriteKit
import CoreData
import SNZSpriteKitUI
import GameKit
class GameScene: SNZScene {
var gameboardLayer = SKNode()
var guiLayer = SKNode()
var currentPieceLabel: SKLabelNode?
var currentPieceHome = CGPoint(x: 0,y: 0)
var currentPieceSprite: SKSpriteNode?
var currentPieceSpriteProgressionLeft: SKSpriteNode?
var currentPieceSpriteProgressionRight: SKSpriteNode?
var currentPieceSpriteProgressionArrow: SKSpriteNode?
var currentPieceCaption: SKShapeNode?
var currentPieceCaptionText: String = ""
var stashPieceLabel: SKLabelNode?
var stashPieceHome = CGPoint(x: 0,y: 0)
var stashBox: SKShapeNode?
var menuButton: SNZTextureButtonWidget?
var undoButton: SNZTextureButtonWidget?
var gameOverLabel: SKLabelNode?
var bankButton: BankButtonWidget?
var stashButton: SNZButtonWidget?
var currentButton: SNZButtonWidget?
var statsButton: SNZButtonWidget?
var highScoreButton: SNZButtonWidget?
var uiTextScale:CGFloat = 1.0
var scoreDisplay: SKLabelNode?
var scoreLabel: SKLabelNode?
var goalScoreDisplay: SKLabelNode?
var goalScoreLabel: SKLabelNode?
var bankPointsDisplay: SKLabelNode?
var bankPointsLabel: SKLabelNode?
var highScoreDisplay: SKLabelNode?
var highScoreLabel: SKLabelNode?
var mergingPieces: [HexPiece] = Array()
var mergedPieces: [HexPiece] = Array()
var lastPlacedPiece: HexPiece?
var lastPointsAwarded = 0
var mergesCurrentTurn = 0
var hexMap: HexMap?
var undoState: Data?
var debugShape: SKShapeNode?
let lock = Spinlock()
var _score = 0
var score: Int {
get {
return self._score
}
set {
self._score = newValue
self.updateScore()
// Update score in state
GameState.instance!.score = self._score
// Update overall high score
if (self._score > GameState.instance!.highScore) {
GameState.instance!.highScore = self._score
self.updateHighScore()
}
// Update level mode specific high score
if (self._score > GameStats.instance!.getIntForKey("highscore_"+String(LevelHelper.instance.mode.rawValue))) {
GameStats.instance!.setIntForKey("highscore_"+String(LevelHelper.instance.mode.rawValue), self._score)
}
}
}
var _bankPoints = 0
var bankPoints: Int {
get {
return self._bankPoints
}
set {
self._bankPoints = newValue
self.updateBankPoints()
// Update score in state
GameState.instance!.bankPoints = self._bankPoints
}
}
override func didMove(to view: SKView) {
super.didMove(to: view)
if (GameStateMachine.instance!.currentState is GameSceneInitialState) {
// Set up GUI, etc.
self.initGame()
// If hexMap is blank, enter restart state to set up new game
if (GameState.instance!.hexMap.isBlank) {
GameStateMachine.instance!.enter(GameSceneRestartState.self)
} else {
GameStateMachine.instance!.enter(GameScenePlayingState.self)
}
}
self.updateGuiPositions()
}
func initGame() {
// Set background
self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0)
// Calculate font scale factor
self.initScaling()
// Add guiLayer to scene
addChild(self.guiLayer)
// Get the hex map and render it
self.renderFromState()
// Build progression sprites
self.buildProgression()
// Generate proxy sprite for current piece
self.updateCurrentPieceSprite()
// Add gameboardLayer to scene
addChild(self.gameboardLayer)
// Init bank points
self.bankPoints = GameState.instance!.bankPoints
// Init guiLayer
self.initGuiLayer()
// Check to see if we are already out of open cells, and change to end game state if so
// e.g. in case state was saved during end game.
if (HexMapHelper.instance.hexMap!.getOpenCells().count==0) {
GameStateMachine.instance!.enter(GameSceneGameOverState.self)
}
// Update game center, just in case we missed anything (crash, kill, etc)
GameStats.instance!.updateGameCenter()
}
func renderFromState() {
// Init HexMap
self.hexMap = GameState.instance!.hexMap
// Init score
self._score = GameState.instance!.score
// Init level
HexMapHelper.instance.hexMap = self.hexMap!
// Render our hex map to the gameboardLayer
HexMapHelper.instance.renderHexMap(gameboardLayer);
}
/**
Reset game state. This includes clearing current score, stashed piece, current piece, and regenerating hexmap with a new random starting layout.
*/
func resetLevel() {
// Remove current piece, stash piece sprites
self.removeTransientGuiSprites()
// Make sure that Game Over label is no longer displayed
self.hideGameOver()
// Clear the board
HexMapHelper.instance.clearHexMap(self.gameboardLayer)
// Clear the hexmap
self.hexMap?.clear()
// Generate level
LevelHelper.instance.initLevel(self.hexMap!)
// Generate new current piece
self.generateCurrentPiece()
// Generate proxy sprite for current piece
self.updateCurrentPieceSprite()
// Reset buyables
GameState.instance!.resetBuyablePieces()
// Clear stash
if (GameState.instance!.stashPiece != nil) {
if (GameState.instance!.stashPiece!.sprite != nil) {
GameState.instance!.stashPiece!.sprite!.removeFromParent()
}
GameState.instance!.stashPiece = nil
}
// Render game board
HexMapHelper.instance.renderHexMap(gameboardLayer);
// Reset score
self.score = 0
// Reset merges counter
self.mergesCurrentTurn = 0
// Update GUI
self.updateGuiLayer()
// Clear undo
self.undoButton!.hidden = true
self.undoState = nil
// Update game center
GameStats.instance!.updateGameCenter()
}
/**
Handles touch begin and move events. Updates animations for any pieces which would be merged if the player were to end the touch event in the cell being touched, if any.
*/
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if (self.widgetTouchesBegan(touches, withEvent: event)) {
return
}
let location = touches.first?.location(in: self)
if (location != nil) {
let nodes = self.nodes(at: location!)
for node in nodes {
if (node.name == "hexMapCell") {
// Get cell using stord position from node's user data
let x = node.userData!.value(forKey: "hexMapPositionX") as! Int
let y = node.userData!.value(forKey: "hexMapPositionY") as! Int
let cell = HexMapHelper.instance.hexMap!.cell(x,y)
// If we have a Remove piece, move it to the target cell regardless of contents
if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) {
currentPieceSprite!.position = node.position
} else
// Otherwise, check to see if the cell will accept the piece
if (cell!.willAccept(GameState.instance!.currentPiece!)) {
self.updateMergingPieces(cell!)
// Move to touched point
currentPieceSprite!.removeAction(forKey: "moveAnimation")
currentPieceSprite!.position = node.position
}
}
}
}
}
/**
touchesMoved override. We just call touchesBegan for this game, since the logic is the same.
*/
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchesBegan(touches, with: event)
}
/**
touchesEnded override. Widgets first, then our own local game nodes.
*/
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if (self.widgetTouchesEnded(touches, withEvent: event) || touches.first == nil) {
return
}
let location = touches.first?.location(in: self)
if ((location != nil) && (GameStateMachine.instance!.currentState is GameScenePlayingState)) {
for node in self.nodes(at: location!) {
if (self.nodeWasTouched(node)) {
break;
}
}
}
if (GameStateMachine.instance!.currentState is GameSceneGameOverState && self.gameOverLabel?.parent != nil) {
self.scene!.view?.presentScene(SceneHelper.instance.levelScene, transition: SKTransition.push(with: SKTransitionDirection.up, duration: 0.4))
}
}
/**
Handle a node being touched. Place piece, merge, collect, etc.
*/
func nodeWasTouched(_ node: SKNode) -> Bool {
var handled = false
if (node.name == "hexMapCell") {
let x = node.userData!.value(forKey: "hexMapPositionX") as! Int
let y = node.userData!.value(forKey: "hexMapPositionY") as! Int
let cell = HexMapHelper.instance.hexMap!.cell(x,y)
// Refresh merging pieces
self.updateMergingPieces(cell!)
// Do we have a Remove piece?
if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) {
// Capture state for undo
self.captureState()
// Process the removal
self.playRemovePiece(cell!)
} else
// Does the cell contain a collectible hex piece?
if (cell!.hexPiece != nil && cell!.hexPiece!.isCollectible) {
// Capture state for undo
self.captureState()
// Let the piece know it was collected
cell!.hexPiece!.wasCollected()
// Clear out the hex cell
cell!.hexPiece = nil
} else
// Will the target cell accept our current piece, and will the piece either allow placement
// without a merge, or if not, do we have a merge?
if (cell!.willAccept(GameState.instance!.currentPiece!) && (GameState.instance!.currentPiece!.canPlaceWithoutMerge() || self.mergingPieces.count>0)) {
// Capture state for undo
self.captureState()
// Store last placed piece, prior to any merging
GameState.instance!.lastPlacedPiece = GameState.instance!.currentPiece
// Place the current piece
self.placeCurrentPiece(cell!)
}
handled = true
}
return handled
}
/**
Handle the merging of pieces
*/
func handleMerge(_ cell: HexCell) {
// Are we merging pieces?
if (self.mergingPieces.count>0) {
var maxValue = 0
var minValue = 10000
// Remove animations from merging pieces, and find the maximum value
for hexPiece in self.mergingPieces {
hexPiece.sprite!.removeAction(forKey: "mergeAnimation")
hexPiece.sprite!.setScale(1.0)
if (hexPiece.value > maxValue) {
maxValue = hexPiece.value
}
if (hexPiece.value < minValue) {
minValue = hexPiece.value
}
}
// Let piece know it was placed w/ merge
GameState.instance!.currentPiece = GameState.instance!.currentPiece!.wasPlacedWithMerge(minValue, mergingPieces: self.mergingPieces)
self.mergesCurrentTurn += 1
// Store merged pieces, if any
self.mergedPieces = self.mergingPieces
// Block while we merge
self.lock.around {
GameStateMachine.instance!.blocked = true
}
// Create merge animation
let moveAction = SKAction.move(to: HexMapHelper.instance.hexMapToScreen(cell.position), duration: 0.25)
let moveSequence = SKAction.sequence([moveAction, SKAction.removeFromParent(), SKAction.run({self.lock.around {
GameStateMachine.instance!.blocked = false
}})])
// Remove merged pieces from board
for hexPiece in self.mergingPieces {
if (hexPiece.value == minValue) {
hexPiece.sprite!.run(moveSequence)
hexPiece.hexCell?.hexPiece = nil
}
}
} else {
// let piece know we are placing it
GameState.instance!.currentPiece!.wasPlacedWithoutMerge()
}
}
/**
Take the current piece and place it in a given cell.
*/
func placeCurrentPiece(_ cell: HexCell) {
// Handle merging, if any
self.handleMerge(cell)
// Place the piece
cell.hexPiece = GameState.instance!.currentPiece
// Record statistic
GameStats.instance!.incIntForKey(cell.hexPiece!.getStatsKey())
// Move sprite from GUI to gameboard layer
GameState.instance!.currentPiece!.sprite!.move(toParent: self.gameboardLayer)
// Position on gameboard
GameState.instance!.currentPiece!.sprite!.position = HexMapHelper.instance.hexMapToScreen(cell.position)
// Remove animation
self.currentPieceSprite!.removeAllActions()
self.currentPieceSprite!.isHidden = true
// Award points
self.awardPointsForPiece(GameState.instance!.currentPiece!)
self.scrollPoints(self.lastPointsAwarded, position: GameState.instance!.currentPiece!.sprite!.position)
// End turn
self.turnDidEnd()
}
/**
Use a "remove" piece on a given cell. This causes the piece currently in the cell to be removed from play.
*/
func playRemovePiece(_ cell: HexCell) {
if (cell.hexPiece != nil) {
// Let the piece know it was collected
cell.hexPiece!.wasRemoved()
// Clear out the hex cell
cell.hexPiece = nil
// Remove sprite
GameState.instance!.currentPiece!.sprite!.removeFromParent()
// End turn
self.turnDidEnd()
}
}
/**
Captures state for undo.
*/
func captureState() {
self.undoState = NSKeyedArchiver.archivedData(withRootObject: GameState.instance!)
// Show undo button
self.undoButton!.hidden = false
}
/**
Restores the previous state from undo.
*/
func restoreState() {
if (self.undoState != nil) {
// Remove current piece, stash piece sprites
self.removeTransientGuiSprites()
// Clear piece sprites from rendered hexmap
HexMapHelper.instance.clearHexMap(self.gameboardLayer)
// Load undo state
GameState.instance = (NSKeyedUnarchiver.unarchiveObject(with: self.undoState!) as? GameState)!
// Get the hex map and render it
self.renderFromState()
// Restore bank points
self.bankPoints = GameState.instance!.bankPoints
// Update gui
self.updateGuiLayer()
// Clear undo state
self.undoState = nil
}
}
/**
Called after player has placed a piece. Processes moves for mobile pieces, checks for end game state.
*/
func turnDidEnd() {
GameStateMachine.instance!.enter(GameSceneMergingState.self)
// Get all occupied cells
let occupiedCells = HexMapHelper.instance.hexMap!.getOccupiedCells()
// tell each piece to get ready to take a turn
for occupiedCell in occupiedCells {
occupiedCell.hexPiece?.preTakeTurn()
}
}
func doMerges() {
// Look for merges resulting from hexpiece turns
var merges = HexMapHelper.instance.getFirstMerge();
if (merges.count>0) {
var mergeFocus: HexPiece?
var highestAdded = -1
var maxValue = 0
var minValue = 10000
for merged in merges {
if (merged.added > highestAdded) {
highestAdded = merged.added
mergeFocus = merged
}
if (merged.value > maxValue) {
maxValue = merged.value
}
if (merged.value < minValue) {
minValue = merged.value
}
}
// Set blocking flag
self.lock.around {
GameStateMachine.instance!.blocked = true
}
// Create merge animation
let moveAction = SKAction.move(to: mergeFocus!.sprite!.position, duration: 0.25)
let moveSequence = SKAction.sequence([moveAction, SKAction.removeFromParent(), SKAction.run({self.lock.around {
GameStateMachine.instance!.blocked = false
}})])
var actualMerged: [HexPiece] = Array()
// Remove merged pieces from board
for merged in merges {
if (merged != mergeFocus && merged.value == minValue) {
actualMerged.append(merged)
merged.sprite!.run(moveSequence)
merged.hexCell?.hexPiece = nil
}
}
// add pieces which were not the merge focus to our list of pieces merged on the last turn
self.mergedPieces += actualMerged
// let merge focus know it was merged
mergeFocus = mergeFocus!.wasPlacedWithMerge(minValue, mergingPieces: merges)
self.mergesCurrentTurn += 1
// Award points
self.awardPointsForPiece(mergeFocus!)
self.scrollPoints(self.lastPointsAwarded, position: mergeFocus!.sprite!.position)
// Record statistics
GameStats.instance!.incIntForKey(mergeFocus!.getStatsKey())
// Get next merge
merges = HexMapHelper.instance.getFirstMerge();
} else {
GameStateMachine.instance!.enter(GameSceneEnemyState.self)
}
}
func doAutonomousActions() {
// Get all occupied cells
let occupiedCells = HexMapHelper.instance.hexMap!.getOccupiedCells()
// Give each piece a turn
for occupiedCell in occupiedCells {
occupiedCell.hexPiece?.takeTurn()
}
// Test for game over
if (HexMapHelper.instance.hexMap!.getOpenCells().count==0) {
GameStateMachine.instance!.enter(GameSceneGameOverState.self)
} else {
// Generate new piece
self.generateCurrentPiece()
// Update current piece sprite
self.updateCurrentPieceSprite()
// Reset merge counter
self.mergesCurrentTurn = 0
// Return to playing state
GameStateMachine.instance!.enter(GameScenePlayingState.self)
}
}
override internal func update(_ currentTime: TimeInterval) {
if (!GameStateMachine.instance!.blocked) {
if (GameStateMachine.instance!.currentState is GameSceneMergingState) {
self.doMerges()
} else
if (GameStateMachine.instance!.currentState is GameSceneEnemyState) {
self.doAutonomousActions()
}
}
}
/**
Rolls back the last move made. Places removed merged pieces back on the board, removes points awarded, and calls self.restoreLastPiece, which puts the last piece played back in the currentPiece property.
*/
func undoLastMove() {
self.restoreState()
// Hide undo button
self.undoButton!.hidden = true
}
/**
Stops merge animation on any current set of would-be merged pieces, then updates self.mergingPieces with any merges which would occur if self.curentPiece were to be placed in cell. Stats merge animation on the new set of merging pieces, if any.
- Parameters:
- cell: The cell to test for merging w/ the current piece
*/
func updateMergingPieces(_ cell: HexCell) {
if (cell.willAccept(GameState.instance!.currentPiece!)) {
// Stop animation on current merge set
for hexPiece in self.mergingPieces {
hexPiece.sprite!.removeAction(forKey: "mergeAnimation")
hexPiece.sprite!.setScale(1.0)
}
self.mergingPieces = cell.getWouldMergeWith(GameState.instance!.currentPiece!)
// Start animation on new merge set
for hexPiece in self.mergingPieces {
hexPiece.sprite!.removeAction(forKey: "mergeAnimation")
hexPiece.sprite!.setScale(1.2)
}
}
}
func initScaling() {
let width = (self.frame.width < self.frame.height) ? self.frame.width : self.frame.height
if (width >= 375) {
self.uiTextScale = 1.0
} else {
self.uiTextScale = width / 375
}
}
/**
Initializes GUI layer components, sets up labels, buttons, etc.
*/
func initGuiLayer() {
// Calculate size of upper UI
let upperUsableArea = (self.frame.height < self.frame.width ? self.frame.height : self.frame.width) - SNZSpriteKitUITheme.instance.uiOuterMargins.horizontal
var bankButtonWidth = (upperUsableArea / 2) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3)
var currentButtonWidth = (upperUsableArea / 4) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3)
var stashButtonWidth = currentButtonWidth
bankButtonWidth = bankButtonWidth > 200 ? 200 : bankButtonWidth
currentButtonWidth = currentButtonWidth > 100 ? 100 : currentButtonWidth
stashButtonWidth = stashButtonWidth > 100 ? 100 : stashButtonWidth
// Calculate current piece home position
self.currentPieceHome = CGPoint(x: 80, y: self.frame.height - 70)
// Add current piece label
self.currentPieceLabel = self.createUILabel("Current")
self.currentPieceLabel!.position = CGPoint(x: 20, y: self.frame.height - 40)
self.currentPieceLabel!.horizontalAlignmentMode = .center
self.guiLayer.addChild(self.currentPieceLabel!)
// Add current button
self.currentButton = SNZButtonWidget()
self.currentButton!.size = CGSize(width: currentButtonWidth, height: 72)
self.currentButton!.position = CGPoint(x: SNZSpriteKitUITheme.instance.uiOuterMargins.left, y: self.frame.height - 90)
self.currentButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25)
self.currentButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15)
self.currentButton!.caption = ""
self.currentButton!.bind("tap",{
if (GameStateMachine.instance!.currentState is GameScenePlayingState) {
self.swapStash()
}
})
self.addWidget(self.currentButton!)
// Calculate stash piece home position
self.stashPieceHome = CGPoint(x: 180, y: self.frame.height - 70)
// Add stash button
self.stashButton = SNZButtonWidget()
self.stashButton!.size = CGSize(width: stashButtonWidth, height: 72)
self.stashButton!.position = CGPoint(x: currentButton!.position.x + (SNZSpriteKitUITheme.instance.uiInnerMargins.left) + currentButtonWidth, y: self.frame.height - 90)
self.stashButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25)
self.stashButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15)
self.stashButton!.caption = ""
self.stashButton!.bind("tap",{
if (GameStateMachine.instance!.currentState is GameScenePlayingState) {
self.swapStash()
}
})
self.addWidget(self.stashButton!)
// Add stash piece label
self.stashPieceLabel = self.createUILabel("Stash")
self.stashPieceLabel!.position = CGPoint(x: 150, y: self.frame.height - 40)
self.stashPieceLabel!.horizontalAlignmentMode = .center
self.guiLayer.addChild(self.stashPieceLabel!)
// Add stash piece sprite, if any
self.updateStashPieceSprite()
// Add bank label
self.bankPointsLabel = self.createUILabel("Bank Points")
self.bankPointsLabel!.position = CGPoint(x: self.frame.width - 100, y: self.frame.height - 120)
self.bankPointsLabel!.ignoreTouches = true
self.guiLayer.addChild(self.bankPointsLabel!)
// Add bank display
self.bankPointsDisplay = self.createUILabel(HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.bankPoints))!)
self.bankPointsDisplay!.position = CGPoint(x: self.frame.width - 100, y: self.frame.height - 144)
self.bankPointsDisplay!.fontSize = 18 * self.uiTextScale
self.guiLayer.addChild(self.bankPointsDisplay!)
// Add bank button
self.bankButton = BankButtonWidget()
self.bankButton!.size = CGSize(width: bankButtonWidth, height: 72)
self.bankButton!.position = CGPoint(x: self.frame.width - 100, y: self.frame.height-90)
self.bankButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25)
self.bankButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15)
self.bankButton!.caption = ""
self.bankButton!.bind("tap",{
if (GameStateMachine.instance!.currentState is GameScenePlayingState) {
self.scene!.view?.presentScene(SceneHelper.instance.bankScene, transition: SKTransition.push(with: SKTransitionDirection.down, duration: 0.4))
}
})
self.addWidget(self.bankButton!)
// Add menu button
self.menuButton = MergelTextureButtonWidget(parentNode: guiLayer)
self.menuButton!.texture = SKTexture(imageNamed: "menu51")
self.menuButton!.anchorPoint = CGPoint(x: 0,y: 0)
self.menuButton!.textureScale = 0.8
self.menuButton!.bind("tap",{
self.scene!.view?.presentScene(SceneHelper.instance.levelScene, transition: SKTransition.push(with: SKTransitionDirection.up, duration: 0.4))
})
self.addWidget(self.menuButton!)
// Add undo button
self.undoButton = MergelTextureButtonWidget(parentNode: guiLayer)
self.undoButton!.texture = SKTexture(imageNamed: "curve4")
self.undoButton!.anchorPoint = CGPoint(x: 1,y: 0)
self.undoButton!.bind("tap",{
self.undoLastMove()
})
self.addWidget(self.undoButton!)
// Add score label
self.scoreLabel = self.createUILabel("Score")
self.scoreLabel!.position = CGPoint(x: 20, y: self.frame.height - 120)
self.guiLayer.addChild(self.scoreLabel!)
// Add score display
self.scoreDisplay = self.createUILabel(HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.score))!)
self.scoreDisplay!.position = CGPoint(x: 20, y: self.frame.height - 144)
self.scoreDisplay!.fontSize = 24 * self.uiTextScale
self.guiLayer.addChild(self.scoreDisplay!)
// Add stats button
self.statsButton = SNZButtonWidget()
self.statsButton!.size = CGSize(width: (self.stashButton!.position.x + self.stashButton!.size.width) - self.currentButton!.position.x, height: 62)
self.statsButton!.position = CGPoint(x: 20, y: self.currentButton!.position.y - (self.currentButton!.size.height / 2) - 4 - (self.statsButton!.size.height / 2))
self.statsButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25)
self.statsButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15)
self.statsButton!.caption = ""
self.statsButton!.bind("tap",{
self.scene!.view?.presentScene(SceneHelper.instance.statsScene, transition: SKTransition.push(with: SKTransitionDirection.right, duration: 0.4))
})
self.addWidget(self.statsButton!)
self.highScoreButton = SNZButtonWidget()
self.highScoreButton!.size = CGSize(width: bankButtonWidth, height: 62)
self.highScoreButton!.position = CGPoint(x: self.bankButton!.position.x, y: self.statsButton!.position.y)
self.highScoreButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25)
self.highScoreButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15)
self.highScoreButton!.caption = ""
self.highScoreButton!.bind("tap",{
NotificationCenter.default.post(name: Notification.Name(rawValue: ShowGKGameCenterViewController), object: nil)
//self.scene!.view?.presentScene(SceneHelper.instance.statsScene, transition: SKTransition.pushWithDirection(SKTransitionDirection.Right, duration: 0.4))
})
self.addWidget(self.highScoreButton!)
// Add high score label
self.highScoreLabel = self.createUILabel("High Score")
self.highScoreLabel!.position = CGPoint(x: 20, y: self.frame.height - 170)
self.highScoreLabel!.horizontalAlignmentMode = .right
self.guiLayer.addChild(self.highScoreLabel!)
// Add high score display
self.highScoreDisplay = self.createUILabel(HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.highScore))!)
self.highScoreDisplay!.position = CGPoint(x: 20, y: self.frame.height - 204)
self.highScoreDisplay!.fontSize = 18 * self.uiTextScale
self.highScoreDisplay!.horizontalAlignmentMode = .right
self.guiLayer.addChild(self.highScoreDisplay!)
// Add goal score display
self.goalScoreDisplay = self.createUILabel("Goal " + HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.goalScore))!)
self.goalScoreDisplay!.position = CGPoint(x: 20, y: self.frame.height - 204)
self.goalScoreDisplay!.fontSize = 12 * self.uiTextScale
self.goalScoreDisplay!.horizontalAlignmentMode = .right
self.goalScoreDisplay!.fontColor = UIColor(red: 0xf7/255, green: 0xef/255, blue: 0xed/255, alpha: 0.8)
self.guiLayer.addChild(self.goalScoreDisplay!)
// Current piece caption
self.buildCurrentPieceCaption()
// Set initial positions
self.updateGuiPositions()
// Set initial visibility of undo button
self.undoButton!.hidden = (GameState.instance!.lastPlacedPiece == nil);
// Render the widgets
self.renderWidgets()
}
func buildProgression() {
// Progression
self.currentPieceSpriteProgressionLeft = SKSpriteNode(texture: SKTexture(imageNamed: "HexCellVoid"))
self.currentPieceSpriteProgressionLeft!.setScale(0.5)
self.guiLayer.addChild(self.currentPieceSpriteProgressionLeft!)
self.currentPieceSpriteProgressionArrow = SKSpriteNode(texture: SKTexture(imageNamed: "play-arrow"))
self.currentPieceSpriteProgressionArrow!.setScale(0.15)
self.guiLayer.addChild(self.currentPieceSpriteProgressionArrow!)
self.currentPieceSpriteProgressionRight = SKSpriteNode(texture: SKTexture(imageNamed: "HexCellVoid"))
self.currentPieceSpriteProgressionRight!.setScale(0.5)
self.guiLayer.addChild(self.currentPieceSpriteProgressionRight!)
}
func buildCurrentPieceCaption() {
var isHidden = true
if (self.currentPieceCaption != nil) {
isHidden = self.currentPieceCaption!.isHidden
self.currentPieceCaption!.removeFromParent()
}
if (self.frame.width > self.frame.height) {
self.currentPieceCaption = SKShapeNode(rect: CGRect(x: 0, y: 0, width: self.statsButton!.size.width, height: self.statsButton!.size.width), cornerRadius: 4)
} else {
self.currentPieceCaption = SKShapeNode(rect: CGRect(x: 0, y: 0, width: self.size.width - 40, height: self.statsButton!.size.height), cornerRadius: 4)
}
self.currentPieceCaption!.fillColor = UIColor(red: 54/255, green: 93/255, blue: 126/255, alpha: 1.0)
self.currentPieceCaption!.lineWidth = 0
self.currentPieceCaption!.zPosition = 999
self.guiLayer.addChild(self.currentPieceCaption!)
self.updateCurrentPieceCaption(self.currentPieceCaptionText)
self.currentPieceCaption!.isHidden = isHidden
}
/**
Updates the position of GUI elements. This gets called whem rotation changes.
*/
func updateGuiPositions() {
if (self.currentPieceLabel != nil) {
// Calculate size of upper UI
let upperUsableArea = (self.frame.height < self.frame.width ? self.frame.height : self.frame.width) - SNZSpriteKitUITheme.instance.uiOuterMargins.horizontal
// Calculate upper button widths
var bankButtonWidth = (upperUsableArea / 2) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3)
var currentButtonWidth = (upperUsableArea / 4) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3)
var stashButtonWidth = currentButtonWidth
bankButtonWidth = bankButtonWidth > 200 ? 200 : bankButtonWidth
currentButtonWidth = currentButtonWidth > 100 ? 100 : currentButtonWidth
stashButtonWidth = stashButtonWidth > 100 ? 100 : stashButtonWidth
// Current Piece
self.currentButton!.position = CGPoint(x: SNZSpriteKitUITheme.instance.uiOuterMargins.left, y: self.frame.height - 90)
self.currentButton!.size = CGSize(width: currentButtonWidth, height: 72)
self.currentPieceLabel!.position = CGPoint(x: self.currentButton!.position.x + (currentButtonWidth / 2), y: self.frame.height - 40)
self.currentPieceHome = CGPoint(x: self.currentButton!.position.x + (currentButtonWidth / 2), y: self.frame.height - 70)
if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece!.sprite != nil) {
GameState.instance!.currentPiece!.sprite!.position = self.currentPieceHome
}
// Current Piece Caption
self.buildCurrentPieceCaption()
if (self.frame.width > self.frame.height) {
self.currentPieceCaption!.position = CGPoint(x: 20, y: (self.frame.height - 165) - (self.currentPieceCaption!.frame.height / 2))
} else {
self.currentPieceCaption!.position = CGPoint(x: 20, y: (self.frame.height - 130) - (self.currentPieceCaption!.frame.height / 2))
}
// Stash Piece
self.stashButton!.position = CGPoint(x: currentButton!.position.x + (SNZSpriteKitUITheme.instance.uiInnerMargins.left) + currentButtonWidth, y: self.frame.height - 90)
self.stashButton!.size = CGSize(width: stashButtonWidth, height: 72)
self.stashPieceLabel!.position = CGPoint(x: self.stashButton!.position.x + (stashButtonWidth/2), y: self.frame.height - 40)
self.stashPieceHome = CGPoint(x: self.stashButton!.position.x + (stashButtonWidth/2), y: self.frame.height - 70)
if (GameState.instance!.stashPiece != nil && GameState.instance!.stashPiece!.sprite != nil) {
GameState.instance!.stashPiece!.sprite!.position = self.stashPieceHome
}
// Bank Button
self.bankButton!.position = CGPoint(x: self.frame.width - bankButtonWidth - SNZSpriteKitUITheme.instance.uiOuterMargins.right, y: self.frame.height-90)
self.bankButton!.size = CGSize(width: bankButtonWidth, height: 72)
// bank points
self.bankPointsLabel!.position = CGPoint(x: self.bankButton!.position.x + SNZSpriteKitUITheme.instance.uiInnerMargins.left, y: self.frame.height - 40)
self.bankPointsDisplay!.position = CGPoint(x: self.bankButton!.position.x + SNZSpriteKitUITheme.instance.uiInnerMargins.left, y: self.frame.height - 64)
// Score
self.scoreLabel!.position = CGPoint(x: 30, y: self.frame.height - 120)
self.scoreDisplay!.position = CGPoint(x: 30, y: self.frame.height - 145)
self.highScoreLabel!.position = CGPoint(x: self.frame.width - 30, y: self.frame.height - 120)
self.highScoreDisplay!.position = CGPoint(x: self.frame.width - 30, y: self.frame.height - 138)
self.goalScoreDisplay!.position = CGPoint(x: self.frame.width - 30, y: self.frame.height - 150)
// Stats button
self.statsButton!.position = CGPoint(x: 20, y: self.currentButton!.position.y - (self.currentButton!.size.height / 2) - 4 - (self.statsButton!.size.height / 2))
// High Score button
self.highScoreButton!.position = CGPoint(x: self.bankButton!.position.x, y: self.statsButton!.position.y)
// Gameboard
self.updateGameboardLayerPosition()
// Widgets
self.updateWidgets()
// Progression
self.currentPieceSpriteProgressionLeft!.position = CGPoint(x: 38, y: self.frame.height - 180)
self.currentPieceSpriteProgressionArrow!.position = CGPoint(x: 58, y: self.frame.height - 177)
self.currentPieceSpriteProgressionRight!.position = CGPoint(x: 78, y: self.frame.height - 180)
}
}
/**
Scales and positions the gameboard to fit the current screen size and orientation.
*/
func updateGameboardLayerPosition() {
if (HexMapHelper.instance.hexMap != nil) {
var scale: CGFloat = 1.0
var shiftY: CGFloat = 0
let marginPortrait: CGFloat = 30
let marginLandscape: CGFloat = 60
let gameboardWidth = HexMapHelper.instance.getRenderedWidth()
let gameboardHeight = HexMapHelper.instance.getRenderedHeight()
// Calculate scaling factor to make gameboard fit screen
if (self.frame.width > self.frame.height) { // landscape
scale = self.frame.height / (gameboardHeight + marginLandscape)
} else { // portrait
scale = self.frame.width / (gameboardWidth + marginPortrait)
shiftY = 50 // shift down a little bit if we are in portrait, so that we don't overlap UI elements.
}
// Scale gameboard layer
self.gameboardLayer.setScale(scale)
// Reposition gameboard layer to center in view
self.gameboardLayer.position = CGPoint(x: ((self.frame.width) - (gameboardWidth * scale))/2, y: (((self.frame.height) - (gameboardHeight * scale))/2) - shiftY)
}
}
/**
Helper function to create an instance of SKLabelNode with typical defaults for our GUI and a specified caption.
- Parameters:
- caption: The caption for the label node
- Returns: An instance of SKLabelNode, initialized with caption and gui defaults.
*/
func createUILabel(_ caption: String, baseFontSize: CGFloat = 18) -> SKLabelNode {
let label = SKLabelNode(text: caption)
label.fontColor = UIColor(red: 0xf7/255, green: 0xef/255, blue: 0xed/255, alpha: 1.0)
label.fontSize = baseFontSize * self.uiTextScale
label.zPosition = 20
label.fontName = "Avenir-Black"
label.ignoreTouches = true
label.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
return label
}
/**
Remove sprites which are not a static part of the gui - the current piece and the stash piece.
*/
func removeTransientGuiSprites() {
if (GameState.instance!.stashPiece != nil) {
if (GameState.instance!.stashPiece!.sprite != nil) {
GameState.instance!.stashPiece!.sprite!.removeFromParent()
}
}
if (GameState.instance!.currentPiece != nil) {
if (GameState.instance!.currentPiece!.sprite != nil) {
GameState.instance!.currentPiece!.sprite!.removeFromParent()
}
}
}
/**
Helper method to call all of the various gui update methods.
*/
func updateGuiLayer() {
self.updateStashPieceSprite()
self.updateScore()
self.updateHighScore()
self.updateCurrentPieceSprite()
self.updateGuiPositions()
}
/**
Refresh the current stash piece sprite. We call createSprite method of the stash piece to get the new sprite,
so that we also get any associated animations, etc.
*/
func updateStashPieceSprite() {
if (GameState.instance!.stashPiece != nil) {
if (GameState.instance!.stashPiece!.sprite == nil) {
GameState.instance!.stashPiece!.sprite = GameState.instance!.stashPiece!.createSprite()
GameState.instance!.stashPiece!.sprite!.position = self.stashPieceHome
self.guiLayer.addChild(GameState.instance!.stashPiece!.sprite!)
} else {
GameState.instance!.stashPiece!.sprite!.removeFromParent()
GameState.instance!.stashPiece!.sprite = GameState.instance!.stashPiece!.createSprite()
GameState.instance!.stashPiece!.sprite!.position = self.stashPieceHome
self.guiLayer.addChild(GameState.instance!.stashPiece!.sprite!)
}
}
}
/**
Refreshes the text of the score display with a formatted copy of the current self.score value
*/
func updateScore() {
if (self.scoreDisplay != nil) {
self.scoreDisplay!.text = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.score))
}
}
/**
Refreshes the bank point display with a formatted copy of the current self.bankPoints value.
*/
func updateBankPoints() {
if (self.bankPointsDisplay != nil) {
self.bankPointsDisplay!.text = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.bankPoints))
}
}
/**
Refreshes the text of the high score display with a formatted copy of the current high score value
*/
func updateHighScore() {
if (self.highScoreDisplay != nil) {
self.highScoreDisplay!.text = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.highScore))
}
}
/**
Scrolls a number upward with a fade-out animation, starting from a given point.
*/
func scrollPoints(_ points: Int, position: CGPoint) {
if (points > 0) {
let scrollUp = SKAction.moveBy(x: 0, y: 100, duration: 1.5)
let fadeOut = SKAction.fadeAlpha(to: 0, duration: 1.5)
let remove = SKAction.removeFromParent()
let scrollFade = SKAction.sequence([SKAction.group([scrollUp, fadeOut]),remove])
let pointString:String = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: points))!
let label = SKLabelNode(text: pointString)
switch (self.mergesCurrentTurn) {
case 0...1:
label.fontColor = UIColor.white
break;
case 2:
label.fontColor = UIColor.yellow
case 3:
label.fontColor = UIColor.green
case 4...99:
label.fontColor = UIColor.cyan
default:
label.fontColor = UIColor.white
break;
}
label.fontSize = CGFloat(20 + pointString.characters.count) * self.uiTextScale + (CGFloat(self.mergesCurrentTurn - 1) * 2)
label.zPosition = 30
label.position = position
label.fontName = "Avenir-Black"
self.gameboardLayer.addChild(label)
label.run(scrollFade)
}
}
/**
Calculates and applies a multiplier to the fontSize of an SKLabelNode to make it fit in a given rectangle.
*/
func scaleToFitRect(_ node:SKLabelNode, rect:CGRect) {
node.fontSize *= min(rect.width / node.frame.width, rect.height / node.frame.height)
}
/**
Displays a message with a scale up, pause, and fade out effect, centered on the screen.
- Parameters:
- message: The message to be displayed. Newline (\n) characters in the message will be used as delimiters for the creation of separate SKLabelNodes, effectively allowing for the display of multi-line messages.
- action: If provided, an SKAction which should be called once the fade-out animation completes.
*/
func burstMessage(_ message: String, action: SKAction? = nil) {
let tokens = message.components(separatedBy: "\n").reversed()
var totalHeight:CGFloat = 0
let padding:CGFloat = 20
var labels: [SKLabelNode] = Array()
for token in tokens {
let label = ShadowLabelNode(text: token)
label.fontColor = UIColor.white
label.zPosition = 1000
label.fontName = "Avenir-Black"
label.fontSize = 20
self.scaleToFitRect(label, rect: self.frame.insetBy(dx: 30, dy: 30))
totalHeight += label.frame.height + padding
label.position = CGPoint(x: self.frame.width / 2, y: (self.frame.height / 2))
label.updateShadow()
labels.append(label)
}
// Create the burst animation sequence
var burstSequence: [SKAction] = [
SKAction.scale(to: 1.2, duration: 0.4),
SKAction.scale(to: 0.8, duration: 0.2),
SKAction.scale(to: 1.0, duration: 0.2),
SKAction.wait(forDuration: 2.0),
SKAction.group([
SKAction.scale(to: 5.0, duration: 1.0),
SKAction.fadeOut(withDuration: 1.0)
])
]
// Append the action parameter, if provided
if (action != nil) {
burstSequence.append(action!)
}
let burstAnimation = SKAction.sequence(burstSequence)
var verticalOffset:CGFloat = 0
for label in labels {
label.position.y = (self.frame.height / 2) - (totalHeight / 2) + (label.frame.height / 2) + verticalOffset
verticalOffset += padding + label.frame.height
label.setScale(0)
SceneHelper.instance.gameScene.addChild(label)
label.run(burstAnimation)
}
}
func initGameOver() {
let label = ShadowLabelNode(text: "GAME OVER")
label.fontColor = UIColor.white
label.fontSize = 64 * self.uiTextScale
label.zPosition = 1000
label.fontName = "Avenir-Black"
self.scaleToFitRect(label, rect: self.frame.insetBy(dx: 30, dy: 30))
label.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
label.updateShadow()
self.gameOverLabel = label;
}
func showGameOver() {
// Play game over sound
self.run(SoundHelper.instance.gameover)
// Disable Undo
self.undoButton!.hidden = true
self.undoState = nil
// Create game over label
self.initGameOver()
// Show game over message and display Game Over label afterward
self.burstMessage("NO MOVES REMAINING", action: SKAction.run({
SceneHelper.instance.gameScene.addChild(self.gameOverLabel!)
}))
// Send score to game center
GameStats.instance!.updateGameCenter()
}
func hideGameOver() {
if (self.gameOverLabel != nil && self.gameOverLabel!.parent != nil) {
self.gameOverLabel!.removeFromParent()
}
}
/**
Generates a point value and applies it to self.score, based on the piece specified.
- Parameters:
- hexPiece: The piece for which points are being awarded.
*/
func awardPointsForPiece(_ hexPiece: HexPiece) {
var modifier = self.mergingPieces.count-1
if (modifier < 1) {
modifier = 1
}
self.awardPoints(hexPiece.getPointValue() * modifier * (self.mergesCurrentTurn > 0 ? self.mergesCurrentTurn : 1))
}
func awardPoints(_ points: Int) {
self.lastPointsAwarded = points
self.score += lastPointsAwarded
// Bank 1%
self.bankPoints += Int(Double(points) * 0.01)
self.checkForUnlocks()
}
func checkForUnlocks() {
// Debug Level
/*if (!GameState.instance!.unlockedLevels.contains(.Debug)) {
GameState.instance!.unlockedLevels.append(.Debug)
}*/
if ((LevelHelper.instance.mode == .hexagon || LevelHelper.instance.mode == .welcome) && !GameState.instance!.unlockedLevels.contains(.pit) && self.score >= 500000) {
GameState.instance!.unlockedLevels.append(.pit)
self.burstMessage("New Map Unlocked\nTHE PIT")
}
if (LevelHelper.instance.mode == .pit && !GameState.instance!.unlockedLevels.contains(.moat) && self.score >= 1000000) {
GameState.instance!.unlockedLevels.append(.moat)
self.burstMessage("New Map Unlocked\nTHE MOAT")
}
// Check for goal reached
if (self.score >= GameState.instance!.goalScore) {
let bankPoints = Int(Double(GameState.instance!.goalScore) * 0.05)
self.burstMessage("GOAL REACHED\nEarned "+HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: bankPoints))!+" Bank Points")
self.bankPoints += bankPoints
self.updateBankPoints()
GameState.instance!.goalScore *= 2;
self.goalScoreDisplay!.text = "Goal " + HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.goalScore))!;
}
}
/**
Gets the next piece from the level helper and assigns it to GameState.instance!.currentPiece. This is the piece which will be placed if the player
touches a valid cell on the gameboard.
*/
func generateCurrentPiece() {
GameState.instance!.currentPiece = LevelHelper.instance.popPiece()
}
func setCurrentPiece(_ hexPiece: HexPiece) {
if (GameState.instance!.currentPiece!.sprite != nil) {
GameState.instance!.currentPiece!.sprite!.removeFromParent()
}
GameState.instance!.currentPiece = hexPiece
self.updateCurrentPieceSprite()
}
func spendBankPoints(_ points: Int) {
self.bankPoints -= points
}
func updateCurrentPieceSprite(_ relocate: Bool = true) {
var position: CGPoint?
if (GameState.instance!.currentPiece != nil) {
if (!relocate) {
position = self.currentPieceSprite!.position
}
// Sprite to go in the GUI
if (GameState.instance!.currentPiece!.sprite != nil && GameState.instance!.currentPiece!.sprite!.parent != nil) {
GameState.instance!.currentPiece!.sprite!.removeFromParent()
}
// Generate sprite
GameState.instance!.currentPiece!.sprite = GameState.instance!.currentPiece!.createSprite()
// Ignore touches
GameState.instance!.currentPiece!.sprite!.ignoreTouches = true
GameState.instance!.currentPiece!.sprite!.position = self.currentPieceHome
GameState.instance!.currentPiece!.sprite!.zPosition = 10
guiLayer.addChild(GameState.instance!.currentPiece!.sprite!)
// Sprite to go on the game board
if (self.currentPieceSprite != nil) {
self.currentPieceSprite!.removeFromParent()
}
// Create sprite
self.currentPieceSprite = GameState.instance!.currentPiece!.createSprite()
// Ignore touches
self.currentPieceSprite!.ignoreTouches = true
// fix z position
self.currentPieceSprite!.zPosition = 999
// Pulsate
self.currentPieceSprite!.run(SKAction.repeatForever(SKAction.sequence([
SKAction.scale(to: 1.4, duration: 0.4),
SKAction.scale(to: 0.8, duration: 0.4)
])))
if (relocate || position == nil) {
var targetCell: HexCell?
// Either use last placed piece, or center of game board, for target position
if (GameState.instance!.lastPlacedPiece != nil && GameState.instance!.lastPlacedPiece!.hexCell != nil) {
targetCell = GameState.instance!.lastPlacedPiece!.hexCell!
} else {
targetCell = HexMapHelper.instance.hexMap!.cell(Int(HexMapHelper.instance.hexMap!.width/2), Int(HexMapHelper.instance.hexMap!.height/2))!
}
// Get a random open cell near the target position
let boardCell = HexMapHelper.instance.hexMap!.getRandomCellNear(targetCell!)
// Get cell position
if (boardCell != nil) {
position = HexMapHelper.instance.hexMapToScreen(boardCell!.position)
}
}
// Position sprite
if (position != nil) { // position will be nil if board is full
self.currentPieceSprite!.position = position!
self.gameboardLayer.addChild(self.currentPieceSprite!)
}
// Update caption, if any
if (self.currentPieceCaption != nil) {
if (GameState.instance!.currentPiece!.caption != "") {
self.currentPieceCaption!.isHidden = false
self.updateCurrentPieceCaption(GameState.instance!.currentPiece!.caption)
} else {
self.currentPieceCaption!.isHidden = true
self.currentPieceCaptionText = ""
}
}
self.updateProgression()
}
}
func updateProgression() {
// Update progression sprites
if (self.currentPieceSpriteProgressionLeft != nil) {
let progressionRight = GameState.instance!.currentPiece!.createMergedSprite()
if (progressionRight == nil) {
self.currentPieceSpriteProgressionLeft!.isHidden = true
self.currentPieceSpriteProgressionArrow!.isHidden = true
self.currentPieceSpriteProgressionRight!.isHidden = true
} else {
if (GameState.instance!.currentPiece!.sprite != nil) {
self.currentPieceSpriteProgressionLeft!.texture = GameState.instance!.currentPiece!.sprite!.texture
self.currentPieceSpriteProgressionLeft!.isHidden = false
self.currentPieceSpriteProgressionArrow!.isHidden = false
self.currentPieceSpriteProgressionRight!.texture = progressionRight!.texture
self.currentPieceSpriteProgressionRight!.isHidden = false
}
}
}
}
func updateCurrentPieceCaption(_ caption: String) {
self.currentPieceCaptionText = caption
self.currentPieceCaption!.removeAllChildren()
let tokens = caption.components(separatedBy: " ")
var idx = 0
var token = ""
var label = self.createUILabel("", baseFontSize: 14)
var priorText = ""
var verticalOffset:CGFloat = self.currentPieceCaption!.frame.height / 2
let horizontalOffset:CGFloat = self.currentPieceCaption!.frame.width / 2
var lineHeight:CGFloat = 0
var totalHeight:CGFloat = 0
while (idx < tokens.count) {
token = tokens[idx]
priorText = label.text!
label.text = label.text!+" "+token
if (label.frame.width > (self.currentPieceCaption!.frame.width) - 20) {
label.text = priorText
label.horizontalAlignmentMode = .center
label.position = CGPoint(x: horizontalOffset,y: verticalOffset)
self.currentPieceCaption!.addChild(label)
verticalOffset -= 20
totalHeight += label.frame.height
label = self.createUILabel("", baseFontSize: 14)
} else {
idx += 1
}
if (lineHeight == 0) {
lineHeight = label.frame.height
}
}
if (label.text != "") {
label.horizontalAlignmentMode = .center
label.position = CGPoint(x: horizontalOffset,y: verticalOffset)
self.currentPieceCaption!.addChild(label)
totalHeight += label.frame.height
}
// Vertically center the entire block
for label in self.currentPieceCaption!.children {
label.position.y += (totalHeight / 2) - (lineHeight / 2)
}
}
/**
Swaps GameState.instance!.currentPiece with the piece currently in the stash, if any. If no piece is in the stash, a new currentPiece is geneated and the old currentPiece is placed in the stash.
*/
func swapStash() {
// Clear any caption when piece is going to be swapped in to stash
GameState.instance!.currentPiece!.caption = ""
// Handle the swap
if (GameState.instance!.stashPiece != nil) {
let tempPiece = GameState.instance!.currentPiece!
GameState.instance!.currentPiece = GameState.instance!.stashPiece
GameState.instance!.stashPiece = tempPiece
GameState.instance!.currentPiece!.sprite!.run(SKAction.move(to: self.currentPieceHome, duration: 0.1))
GameState.instance!.stashPiece!.sprite!.run(SKAction.sequence([SKAction.move(to: self.stashPieceHome, duration: 0.1),SKAction.run({
self.updateCurrentPieceSprite(false)
})]))
} else {
GameState.instance!.stashPiece = GameState.instance!.currentPiece
GameState.instance!.stashPiece!.sprite!.run(SKAction.sequence([SKAction.move(to: self.stashPieceHome, duration: 0.1),SKAction.run({
self.generateCurrentPiece()
self.updateCurrentPieceSprite(false)
})]))
self.generateCurrentPiece()
}
}
}
|
2b465b6e52663c33f4b836c27edf669a
| 39.707541 | 252 | 0.590924 | false | false | false | false |
s-aska/Justaway-for-iOS
|
refs/heads/master
|
Justaway/MentionsTableViewController.swift
|
mit
|
1
|
//
// MentionsTableViewController.swift
// Justaway
//
// Created by Shinichiro Aska on 5/22/16.
// Copyright © 2016 Shinichiro Aska. All rights reserved.
//
import Foundation
import KeyClip
import Async
class MentionsTableViewController: StatusTableViewController {
override func saveCache() {
if self.adapter.rows.count > 0 {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let key = "mentions:\(account.userID)"
let statuses = self.adapter.statuses
let dictionary = ["statuses": ( statuses.count > 100 ? Array(statuses[0 ..< 100]) : statuses ).map({ $0.dictionaryValue })]
KeyClip.save(key, dictionary: dictionary as NSDictionary)
NSLog("notifications saveCache.")
}
}
override func loadCache(_ success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
adapter.activityMode = true
Async.background {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let key = "mentions:\(account.userID)"
if let cache = KeyClip.load(key) as NSDictionary? {
if let statuses = cache["statuses"] as? [[String: AnyObject]] {
success(statuses.map({ TwitterStatus($0) }))
return
}
}
success([TwitterStatus]())
Async.background(after: 0.4, { () -> Void in
self.refresh()
})
}
}
override func loadData(_ maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
Twitter.getMentionTimeline(maxID: maxID, success: success, failure: failure)
}
override func loadData(sinceID: String?, maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
Twitter.getMentionTimeline(maxID: maxID, sinceID: sinceID, success: success, failure: failure)
}
override func accept(_ status: TwitterStatus) -> Bool {
if let accountSettings = AccountSettingsStore.get() {
for mention in status.mentions {
if accountSettings.isMe(mention.userID) {
return true
}
}
}
return false
}
}
|
dac6631444de76b6c9b359d2b0c62bdb
| 36.089552 | 171 | 0.577465 | false | false | false | false |
alblue/swift
|
refs/heads/master
|
validation-test/Sema/type_checker_perf/fast/rdar22770433.swift
|
apache-2.0
|
2
|
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 5 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-types
// REQUIRES: tools-release,no_asserts
func test(n: Int) -> Int {
return n == 0 ? 0 : (0..<n).reduce(0) {
($0 > 0 && $1 % 2 == 0) ? ((($0 + $1) - ($0 + $1)) / ($1 - $0)) + (($0 + $1) / ($1 - $0)) : $0
}
}
|
708b87f17b93b533b11c0dc0e8c34285
| 50.75 | 200 | 0.586957 | false | true | false | false |
Asky314159/jrayfm-controlboard
|
refs/heads/main
|
ios/JRay FM/SecondViewController.swift
|
mit
|
1
|
//
// SecondViewController.swift
// JRay FM
//
// Created by Jonathan Ray on 4/10/16.
// Copyright © 2016 Jonathan Ray. All rights reserved.
//
import MediaPlayer
import UIKit
class SecondViewController: UITableViewController, MPMediaPickerControllerDelegate {
@IBOutlet var editButton: UIBarButtonItem!
@IBOutlet var doneButton: UIBarButtonItem!
private var engine: JRayFMEngine!
private var defaultEntryImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let appDelegate = UIApplication.shared.delegate as! AppDelegate
self.engine = appDelegate.engine
self.defaultEntryImage = UIImage(systemName: "tv.music.note.fill")
self.editButtonVisible(animate: false);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addLibraryItem(_ sender: AnyObject) {
let mediaPicker = MPMediaPickerController(mediaTypes: MPMediaType.music)
mediaPicker.allowsPickingMultipleItems = true
mediaPicker.showsCloudItems = true
mediaPicker.delegate = self
mediaPicker.prompt = "Add songs to library"
self.present(mediaPicker, animated: true, completion: nil)
}
func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
self.dismiss(animated: true, completion: nil)
engine.addItemsToLibrary(items: mediaItemCollection.items)
tableView.reloadData()
}
func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) {
self.dismiss(animated: true, completion: nil)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return engine.getSectionCount()
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return engine.getSectionTitle(section: section)
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return engine.getSectionTitles()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return engine.getItemCount(section: section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let entry = engine.getItemAtIndex(section: indexPath.section, index: indexPath.item)
cell.textLabel?.text = entry.name
cell.detailTextLabel?.text = entry.artist
if entry.image != nil {
cell.imageView?.image = entry.image
}
else {
cell.imageView?.image = self.defaultEntryImage
cell.imageView?.tintColor = UIColor.label
}
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
engine.removeItemAtIndex(section: indexPath.section, index: indexPath.item)
tableView.reloadData()
}
}
@IBAction func editButtonPressed(_ sender: Any) {
self.doneButtonVisible(animate: true)
tableView.setEditing(true, animated: true)
}
@IBAction func doneButtonPressed(_ sender: Any) {
self.editButtonVisible(animate: true)
tableView.setEditing(false, animated: true)
}
func editButtonVisible(animate: Bool) {
self.navigationItem.setLeftBarButtonItems([editButton], animated: animate)
}
func doneButtonVisible(animate:Bool) {
self.navigationItem.setLeftBarButtonItems([doneButton], animated: animate)
}
}
|
c794f2d73e9291eeca5d3d4cfdbc5608
| 34.438596 | 137 | 0.679208 | false | false | false | false |
PrinceChen/DouYu
|
refs/heads/master
|
DouYu/DouYu/Classes/Main/ViewModel/BaseViewModel.swift
|
mit
|
1
|
//
// BaseViewModel.swift
// DouYu
//
// Created by prince.chen on 2017/3/3.
// Copyright © 2017年 prince.chen. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroups:[AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel {
func loadAnchorData(isGroupData: Bool, URLString: String, parameters: [String: Any]? = nil, finishedCallback: @escaping () -> ()) {
NetworkTools.requestData(type: .get, URLString: URLString) { (result) in
guard let resultDict = result as? [String : Any] else { return }
guard let dataArray = resultDict["data"] as? [[String : Any]] else {return}
if isGroupData {
for dict in dataArray {
self.anchorGroups.append(AnchorGroup(dict: dict))
}
} else {
let group = AnchorGroup()
for dict in dataArray {
group.anchors.append(AnchorModel(dict: dict))
}
self.anchorGroups.append(group)
}
finishedCallback()
}
}
}
|
fce476203e9ed9504f033611804f131b
| 26.5 | 135 | 0.514876 | false | false | false | false |
crazymaik/AssertFlow
|
refs/heads/master
|
Sources/Matcher/CollectionTypeMatcher.swift
|
mit
|
1
|
import Foundation
public extension MatcherType where Element: Collection, Element.Iterator.Element: Equatable {
typealias Item = Element.Iterator.Element
@discardableResult
public func contains(_ expected: Item) -> Self {
if unpack() {
for e in actual {
if expected == e {
return self
}
}
fail("Expected \(Element.self) to contain:", expected: expected, actualMsg: "But was: ", actual: actual)
}
return self
}
@discardableResult
public func containsInOrder(_ expected: Item...) -> Self {
if unpack() {
var g = expected.makeIterator()
var next = g.next()
for e in actual {
if next == e {
next = g.next()
if next == nil {
return self
}
}
}
fail("Expected sequence to contain in order \(expected)")
}
return self
}
@discardableResult
public func containsOneOf(_ expected: Item...) -> Self {
if unpack() {
for e in expected {
for a in actual {
if (a == e) {
return self
}
}
}
fail("Expected sequence to contain one of \(expected)")
}
return self
}
@discardableResult
public func isEmpty() -> Self {
if unpack() {
if !actual.isEmpty {
fail("Expected collection to be empty")
}
}
return self
}
@discardableResult
public func hasCount(_ expected: Element.IndexDistance) -> Self {
if unpack() {
let count = actual.count
if count != expected {
fail("Expected collection count to be \(expected), but was \(count)")
}
}
return self
}
}
|
1852c35733735947700228952dc3c3c8
| 26.851351 | 116 | 0.454634 | false | false | false | false |
Clean-Swift/CleanStore
|
refs/heads/master
|
CleanStore/Scenes/CreateOrder/CreateOrderRouter.swift
|
mit
|
1
|
//
// CreateOrderRouter.swift
// CleanStore
//
// Created by Raymond Law on 2/12/19.
// Copyright (c) 2019 Clean Swift LLC. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
@objc protocol CreateOrderRoutingLogic
{
func routeToListOrders(segue: UIStoryboardSegue?)
func routeToShowOrder(segue: UIStoryboardSegue?)
}
protocol CreateOrderDataPassing
{
var dataStore: CreateOrderDataStore? { get }
}
class CreateOrderRouter: NSObject, CreateOrderRoutingLogic, CreateOrderDataPassing
{
weak var viewController: CreateOrderViewController?
var dataStore: CreateOrderDataStore?
// MARK: Routing
func routeToListOrders(segue: UIStoryboardSegue?)
{
if let segue = segue {
let destinationVC = segue.destination as! ListOrdersViewController
var destinationDS = destinationVC.router!.dataStore!
passDataToListOrders(source: dataStore!, destination: &destinationDS)
} else {
let index = viewController!.navigationController!.viewControllers.count - 2
let destinationVC = viewController?.navigationController?.viewControllers[index] as! ListOrdersViewController
var destinationDS = destinationVC.router!.dataStore!
passDataToListOrders(source: dataStore!, destination: &destinationDS)
navigateToListOrders(source: viewController!, destination: destinationVC)
}
}
func routeToShowOrder(segue: UIStoryboardSegue?)
{
if let segue = segue {
let destinationVC = segue.destination as! ShowOrderViewController
var destinationDS = destinationVC.router!.dataStore!
passDataToShowOrder(source: dataStore!, destination: &destinationDS)
} else {
let index = viewController!.navigationController!.viewControllers.count - 2
let destinationVC = viewController?.navigationController?.viewControllers[index] as! ShowOrderViewController
var destinationDS = destinationVC.router!.dataStore!
passDataToShowOrder(source: dataStore!, destination: &destinationDS)
navigateToShowOrder(source: viewController!, destination: destinationVC)
}
}
// MARK: Navigation
func navigateToListOrders(source: CreateOrderViewController, destination: ListOrdersViewController)
{
source.navigationController?.popViewController(animated: true)
}
func navigateToShowOrder(source: CreateOrderViewController, destination: ShowOrderViewController)
{
source.navigationController?.popViewController(animated: true)
}
// MARK: Passing data
func passDataToListOrders(source: CreateOrderDataStore, destination: inout ListOrdersDataStore)
{
}
func passDataToShowOrder(source: CreateOrderDataStore, destination: inout ShowOrderDataStore)
{
destination.order = source.orderToEdit
}
}
|
1f3eda9b99f8141bccb430d9ed399e1f
| 33 | 115 | 0.75917 | false | false | false | false |
hongyuanjiang/Tipping-O
|
refs/heads/master
|
Calculator/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// Calculator
//
// Created by Hongyuan Jiang on 2/4/17.
// Copyright © 2017 Hongyuan Jiang. All rights reserved.
//
import UIKit
class ViewController: UIViewController, AKPickerViewDataSource, AKPickerViewDelegate {
@IBOutlet var pickerView: AKPickerView!
let tiptitles = ["10%", "15%", "18%", "20%", "30%"]
let tippercents = [0.1, 0.15, 0.18, 0.2, 0.3]
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var billField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.pickerView.delegate = self
self.pickerView.dataSource = self
self.pickerView.font = UIFont(name: "HelveticaNeue-Light", size: 20)!
self.pickerView.highlightedFont = UIFont(name: "HelveticaNeue-Light", size: 20)!
self.pickerView.pickerViewStyle = .flat
self.pickerView.maskDisabled = false
self.pickerView.reloadData()
self.view.layer.insertSublayer(CAGradientLayer(), at:0)
self.pickerView.selectItem(1)
self.billField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func calculateTip(_ sender: Any) {
let bill = Double(billField.text!) ?? 0
let tip = bill * tippercents[self.pickerView.selectedItem]
let total = bill + tip
totalLabel.text = String(format: "$%.2f", total)
tipLabel.text = String(format: "$%.2f + $%.2f", bill, tip)
}
func numberOfItemsInPickerView(_ pickerView: AKPickerView) -> Int {
return self.tiptitles.count
}
func pickerView(_ pickerView: AKPickerView, titleForItem item: Int) -> String {
return self.tiptitles[item]
}
func pickerView(_ pickerView: AKPickerView, didSelectItem item: Int) {
self.calculateTip(pickerView)
var background = CAGradientLayer()
if item == 0 {
background = CAGradientLayer().blueColor()
} else if item == 1 {
background = CAGradientLayer().turquoiseColor()
} else if item == 2 {
background = CAGradientLayer().purpleColor()
} else if item == 3 {
background = CAGradientLayer().pinkColor()
} else if item == 4 {
background = CAGradientLayer().orangeColor()
}
background.frame = self.view.bounds
self.view.layer.replaceSublayer((self.view.layer.sublayers?[0])!, with: background)
}
func pickerView(_ pickerView: AKPickerView, configureLabel label: UILabel, forItem item: Int) {
label.textColor = UIColor(red:(255/255.0),green:(255/255.0), blue: (255/255.0), alpha:0.5)
label.highlightedTextColor = UIColor(red:(255/255.0),green:(255/255.0), blue: (255/255.0), alpha:1)
}
func pickerView(_ pickerView: AKPickerView, marginForItem item: Int) -> CGSize {
return CGSize(width: 40, height: 20)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// println("\(scrollView.contentOffset.x)")
}
}
|
f0e720f5d2fcbd7dc9a478f14524aac7
| 28.818966 | 104 | 0.601908 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKit/Components/WebView/Router/WebViewRouter.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import RxCocoa
import RxRelay
import RxSwift
import UIComponentsKit
public final class WebViewRouter: WebViewRouterAPI {
// MARK: - Exposed
public let launchRelay = PublishRelay<TitledLink>()
// MARK: - Private
private var launch: Signal<TitledLink> {
launchRelay.asSignal()
}
private let disposeBag = DisposeBag()
// MARK: - Injected
private let topMostViewControllerProvider: TopMostViewControllerProviding
private let webViewServiceAPI: WebViewServiceAPI
// MARK: - Setup
public init(
topMostViewControllerProvider: TopMostViewControllerProviding = resolve(),
webViewServiceAPI: WebViewServiceAPI = resolve()
) {
self.topMostViewControllerProvider = topMostViewControllerProvider
self.webViewServiceAPI = webViewServiceAPI
launch
.map(\.url)
.emit(onNext: { [weak self] url in
guard let self = self else { return }
guard let topViewController = self.topMostViewControllerProvider.topMostViewController else {
return
}
self.webViewServiceAPI.openSafari(url: url, from: topViewController)
})
.disposed(by: disposeBag)
}
}
|
3fadc9de6d42719ea955eb1c8f690b2a
| 26.979167 | 109 | 0.661206 | false | false | false | false |
PJayRushton/stats
|
refs/heads/master
|
Stats/HomeViewController.swift
|
mit
|
1
|
//
// HomeViewController.swift
// St@s
//
// Created by Parker Rushton on 1/26/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import UIKit
import IGListKit
import Kingfisher
import Presentr
class HomeViewController: Component, AutoStoryboardInitializable {
// MARK: - IBOutlets
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet var emptyStateView: UIView!
@IBOutlet weak var newGameButton: UIButton!
// MARK: - Properties
fileprivate let gridLayout = ListCollectionViewLayout(stickyHeaders: false, topContentInset: 0, stretchToEdge: false)
fileprivate let feedbackGenerator = UISelectionFeedbackGenerator()
fileprivate var isPresentingOnboarding = false
fileprivate var hasSeenNotificationPrompt = false
var currentTeam: Team? {
return core.state.teamState.currentTeam
}
fileprivate lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self, workingRangeSize: 0)
}()
let presenter: Presentr = {
let presenter = Presentr(presentationType: .alert)
presenter.transitionType = TransitionType.coverHorizontalFromRight
return presenter
}()
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
collectionView.collectionViewLayout = gridLayout
adapter.collectionView = collectionView
adapter.dataSource = self
feedbackGenerator.prepare()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
adapter.performUpdates(animated: true)
core.fire(event: Updated<StatsViewType>(.trophies))
core.fire(command: UpdateBadgeCount())
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: - IBActions
@IBAction func createTeamButtonPressed(_ sender: UIButton) {
feedbackGenerator.selectionChanged()
let teamCreationVC = TeamCreationViewController.initializeFromStoryboard().embededInNavigationController
teamCreationVC.modalPresentationStyle = .overFullScreen
present(teamCreationVC, animated: true, completion: nil)
}
@IBAction func addTeamButtonPressed(_ sender: UIButton) {
feedbackGenerator.selectionChanged()
let addTeamVC = AddTeamViewController.initializeFromStoryboard().embededInNavigationController
addTeamVC.modalPresentationStyle = .overFullScreen
present(addTeamVC, animated: true, completion: nil)
}
@IBAction func newTeamButtonPressed(_ sender: UIButton) {
pushGames(new: true)
}
// MARK: - Subscriber
override func update(with state: AppState) {
if state.userState.currentUser == nil, state.userState.isLoaded, !isPresentingOnboarding {
isPresentingOnboarding = true
let newUserVC = NewUserViewController.initializeFromStoryboard().embededInNavigationController
newUserVC.modalPresentationStyle = .overFullScreen
present(newUserVC, animated: true)
}
if let user = state.userState.currentUser {
let currentTeam = state.teamState.currentTeam
newGameButton.isHidden = currentTeam == nil || !user.isOwnerOrManager(of: currentTeam!)
}
if let _ = state.teamState.currentTeam, !hasSeenNotificationPrompt {
hasSeenNotificationPrompt = true
NotificationController.shared.requestAccessIfNeeded(from: self)
}
adapter.performUpdates(animated: true)
}
}
extension HomeViewController {
func presentSettings() {
feedbackGenerator.selectionChanged()
let settingsVC = SettingsViewController.initializeFromStoryboard().embededInNavigationController
settingsVC.modalPresentationStyle = .overFullScreen
present(settingsVC, animated: true, completion: nil)
}
func presentTeamSwitcher() {
feedbackGenerator.selectionChanged()
let teamListVC = TeamListViewController.initializeFromStoryboard()
teamListVC.isSwitcher = true
let teamListInNav = teamListVC.embededInNavigationController
teamListInNav.modalTransitionStyle = .flipHorizontal
teamListInNav.modalPresentationStyle = .fullScreen
present(teamListInNav, animated: true)
}
func presentTeamEdit() {
feedbackGenerator.selectionChanged()
let creationVC = TeamCreationViewController.initializeFromStoryboard()
creationVC.editingTeam = currentTeam
let creationVCWithNav = creationVC.embededInNavigationController
creationVCWithNav.modalPresentationStyle = .overFullScreen
present(creationVCWithNav, animated: true, completion: nil)
}
func presentSeasonManager() {
feedbackGenerator.selectionChanged()
let seasonsVC = SeasonsViewController.initializeFromStoryboard()
seasonsVC.isModal = true
let seasonsNav = seasonsVC.embededInNavigationController
seasonsNav.modalPresentationStyle = .overFullScreen
present(seasonsNav, animated: true, completion: nil)
}
fileprivate func pushGames(new: Bool = false) {
let gamesVC = GamesViewController.initializeFromStoryboard()
gamesVC.new = new
navigationController?.pushViewController(gamesVC, animated: true)
}
fileprivate func pushStats() {
let statsVC = StatsViewController.initializeFromStoryboard()
navigationController?.pushViewController(statsVC, animated: true)
if core.state.statState.currentTrophies.isEmpty {
core.fire(command: UpdateTrophies())
}
}
func pushRoster() {
let rosterVC = RosterViewController.initializeFromStoryboard()
navigationController?.pushViewController(rosterVC, animated: true)
}
func pushShareTeamRoles() {
if let user = core.state.userState.currentUser, let team = core.state.teamState.currentTeam, user.isOwnerOrManager(of: team) {
presentShareRoles()
let shareTeamRolesVC = ShareTeamRolesViewController.initializeFromStoryboard()
navigationController?.pushViewController(shareTeamRolesVC, animated: true)
} else {
presentTeamShare(withType: .fan)
}
}
fileprivate func presentShareRoles() {
let alert = Presentr.alertViewController(title: "Share Team", body: "Which would you like to add?")
alert.addAction(AlertAction(title: "St@ Keeper", style: .default) { _ in
self.dismiss(animated: true, completion: {
self.presentTeamShare(withType: .managed)
})
})
alert.addAction(AlertAction(title: "Player/Fan", style: .default) { _ in
self.dismiss(animated: true, completion: {
self.presentTeamShare(withType: .fan)
})
})
customPresentViewController(alertPresenter, viewController: alert, animated: true, completion: nil)
}
fileprivate func presentTeamShare(withType type: TeamOwnershipType) {
let shareTeamVC = ShareTeamViewController.initializeFromStoryboard()
shareTeamVC.modalPresentationStyle = .overFullScreen
shareTeamVC.ownershipType = type
present(shareTeamVC, animated: false, completion: nil)
}
func didSelectItem(_ item: HomeMenuItem) {
feedbackGenerator.selectionChanged()
core.fire(event: Selected<HomeMenuItem>(item))
switch item {
case .newGame:
pushGames(new: true)
case .stats:
pushStats()
case .games:
pushGames()
case .roster:
pushRoster()
case .share:
pushShareTeamRoles()
}
}
}
// MARK: - IGListKitDataSource
extension HomeViewController: ListAdapterDataSource {
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
guard let currentTeam = currentTeam else { return [] }
var objects: [ListDiffable] = [TeamHeaderSection(team: currentTeam, season: core.state.seasonState.currentSeason)]
let items = HomeMenuItem.allValues
items.forEach { item in
let section = TeamActionSection(team: currentTeam, menuItem: item)
switch item {
case .stats:
section.badgeCount = core.state.hasSeenLatestStats ? nil : 0
case .games:
let count = core.state.gameState.currentOngoingGames.count
section.badgeCount = count == 0 ? nil : count
default:
break
}
objects.append(section)
}
return objects
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
switch object {
case _ as TeamHeaderSection:
let headerController = TeamHeaderSectionController()
headerController.settingsPressed = presentSettings
headerController.switchTeamPressed = presentTeamSwitcher
headerController.seasonPressed = presentSeasonManager
return headerController
case _ as TeamActionSection:
let actionController = TeamActionSectionController()
actionController.didSelectItem = didSelectItem
return actionController
default:
fatalError()
}
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
return emptyStateView
}
}
|
d9b20d88152a6acb7ee1eadc07d749d3
| 35.39781 | 134 | 0.669107 | false | false | false | false |
davecom/SwiftGraph
|
refs/heads/master
|
Examples/SwiftGraph-master/Sources/SwiftGraph/Queue.swift
|
apache-2.0
|
2
|
//
// Queue.swift
// SwiftGraph
//
// Copyright (c) 2014-2019 David Kopec
//
// 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.
/// Implements a queue - helper class that uses an array internally.
public class Queue<T> {
private var container = [T]()
private var head = 0
public init() {}
public var isEmpty: Bool {
return count == 0
}
public func push(_ element: T) {
container.append(element)
}
public func pop() -> T {
let element = container[head]
head += 1
// If queue has more than 50 elements and more than 50% of allocated elements are popped.
// Don't calculate the percentage with floating point, it decreases the performance considerably.
if container.count > 50 && head * 2 > container.count {
container.removeFirst(head)
head = 0
}
return element
}
public var front: T {
return container[head]
}
public var count: Int {
return container.count - head
}
}
extension Queue where T: Equatable {
public func contains(_ thing: T) -> Bool {
let content = container.dropFirst(head)
if content.firstIndex(of: thing) != nil {
return true
}
return false
}
}
|
3a6b05eb53a05223549752170dc596bf
| 26.257576 | 105 | 0.632574 | false | false | false | false |
nmdias/DefaultsKit
|
refs/heads/master
|
Tests/DefaultsKey + keys.swift
|
mit
|
1
|
//
// DefaultsKey + keys.swift
//
// Copyright (c) 2017 - 2018 Nuno Manuel Dias
//
// 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
@testable import DefaultsKit
extension DefaultsKey {
static let integerKey = Key<Int>("integerKey")
static let floatKey = Key<Float>("floatKey")
static let doubleKey = Key<Double>("doubleKey")
static let stringKey = Key<String>("stringKey")
static let boolKey = Key<Bool>("boolKey")
static let dateKey = Key<Date>("dateKey")
static let enumKey = Key<EnumMock>("enumKey")
static let optionSetKey = Key<OptionSetMock>("optionSetKey")
static let arrayOfIntegersKey = Key<[Int]>("arrayOfIntegersKey")
static let personMockKey = Key<PersonMock>("personMockKey")
}
|
105378ceaa8a37c1b55f3cf6691e5659
| 45 | 82 | 0.736343 | false | false | false | false |
aapierce0/MatrixClient
|
refs/heads/master
|
MatrixClient/ImageProvider.swift
|
apache-2.0
|
1
|
/*
Copyright 2017 Avery Pierce
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import SwiftMatrixSDK
struct UnknownError : Error {
var localizedDescription: String {
return "error object was unexpectedly nil"
}
}
/// Downloads images and provides them.
class ImageProvider {
var semaphores: [URL: DispatchSemaphore] = [:]
var cache: [URL: NSImage] = [:]
func semaphore(for url: URL) -> DispatchSemaphore {
if let semaphore = self.semaphores[url] { return semaphore }
let newSemaphore = DispatchSemaphore(value: 1)
self.semaphores[url] = newSemaphore
return newSemaphore
}
func cachedImage(for url: URL) -> NSImage? {
return cache[url]
}
func image(for url: URL, completion: @escaping (_ response: MXResponse<NSImage>) -> Void) {
// Get the semaphore for this url
let semaphore = self.semaphore(for: url)
// This operation needs to be performed on a background thread
let queue = DispatchQueue(label: "Image Provider")
queue.async {
// Wait until any downloads are complete
semaphore.wait()
// If the image already exists in the cache, return it.
if let image = self.cache[url] {
completion(.success(image))
semaphore.signal()
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
// The request is complete, so make sure to signal
defer { semaphore.signal() }
// Create a result object from the URLSession response
let result: MXResponse<NSImage>
if let data = data, let image = NSImage(data: data) {
self.cache[url] = image
result = .success(image)
} else if let error = error {
result = .failure(error)
} else {
result = .failure(UnknownError())
}
// Perform the completion block on the main thread.
DispatchQueue.main.async { completion(result) }
}.resume()
}
}
}
|
1b5e85fbdb987e172293851f81d1050d
| 32.337209 | 95 | 0.574468 | false | false | false | false |
chrisjmendez/swift-exercises
|
refs/heads/master
|
Animation/Flicker/Carthage/Checkouts/SYBlinkAnimationKit/Example/SYBlinkAnimationKit/CollectionViewController.swift
|
mit
|
2
|
//
// CollectionViewController.swift
// SYBlinkAnimationKit
//
// Created by Shohei Yokoyama on 2016/07/31.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
import SYBlinkAnimationKit
class CollectionViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let cellIdentifier = "CollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
configure()
registerNib()
}
}
// MARK: - Fileprivate Methods -
fileprivate extension CollectionViewController {
func configure() {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor(red: 236/255, green: 236/255, blue: 236/255, alpha: 1)
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 5
layout.minimumInteritemSpacing = 5
collectionView.collectionViewLayout = layout
}
func registerNib() {
let nib = UINib(nibName: cellIdentifier, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
}
func configure(cell: CollectionViewCell, at indexPath: IndexPath) {
switch (indexPath as NSIndexPath).row {
case 0:
cell.titileLabel.text = "Border Animation"
cell.animationType = .border
case 1:
cell.titileLabel.text = "BorderWithShadow\nAnimation"
cell.animationType = .borderWithShadow
cell.titileLabel.textAlignmentMode = .center
case 2:
cell.titileLabel.text = "Background Animation"
cell.animationType = .background
case 3:
cell.titileLabel.text = "ripple Animation"
cell.animationType = .ripple
default:
cell.titileLabel.text = "SYCollectionViewCell"
cell.titileLabel.animationType = .text
cell.titileLabel.startAnimating()
}
cell.startAnimating()
}
}
// MARK: - UICollectionViewDataSource
extension CollectionViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CollectionViewCell
configure(cell: cell, at: indexPath)
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension CollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let margin: CGFloat = 5
let height: CGFloat = 150
let rowCount: CGFloat = 2
return CGSize(width: view.frame.width / rowCount - (margin * (rowCount - 1) / rowCount), height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 5, right: 0)
}
}
|
3e0ee794e1c925985f44fe688e6f93a4
| 33.485437 | 162 | 0.669482 | false | false | false | false |
a2/ParksAndRecreation
|
refs/heads/master
|
Localize.playground/Sources/Localize.swift
|
mit
|
1
|
import Foundation
private typealias LocalizationSegment = (String, [NSString])
private func +(lhs: LocalizationSegment, rhs: LocalizationSegment) -> LocalizationSegment {
return (lhs.0 + rhs.0, lhs.1 + rhs.1)
}
private func +(lhs: LocalizationSegment, rhs: LocalizableText) -> LocalizationSegment {
return lhs + rhs.localizationSegments
}
private extension LocalizableText {
private var localizationSegments: LocalizationSegment {
switch self {
case .Tree(let segments):
return segments.reduce(("", []), combine: +)
case .Segment(let element):
return (element, [])
case .Expression(let value):
return ("%@", [ value ])
}
}
}
public func localize(text: LocalizableText, tableName: String? = nil, bundle: NSBundle = NSBundle.mainBundle(), value: String = "", comment: String) -> String {
let (key, strings) = text.localizationSegments
let format = bundle.localizedStringForKey(key, value: value, table: tableName)
guard !strings.isEmpty else { return format }
let args = strings.map {
Unmanaged.passRetained($0).toOpaque()
} as [CVarArgType]
let formatted = String(format: format, arguments: args)
for ptr in args {
Unmanaged<NSString>.fromOpaque(ptr as! COpaquePointer).release()
}
return formatted
}
|
0627340f58837fbd6d552f7767ccc67a
| 32.365854 | 160 | 0.658626 | false | false | false | false |
wangweicheng7/ClouldFisher
|
refs/heads/master
|
CloudFisher/Class/Square/View/PWSquareTableViewCell.swift
|
mit
|
1
|
//
// PWSquareTableViewCell.swift
// firimer
//
// Created by 王炜程 on 2016/11/29.
// Copyright © 2016年 wangweicheng. All rights reserved.
//
import UIKit
import Kingfisher
class PWSquareTableViewCell: UITableViewCell {
class func IdeSquareTableViewCell() -> String {
return "PWSquareTableViewCellIdentify"
}
fileprivate var _model: PWAppInfoModel?
var model: PWAppInfoModel? {
get {
return _model
}
set (m) {
_model = m
if let build = _model?.build {
buildLabel.text = "\(build)"
}
if let version = _model?.version {
versionLabel.text = "\(version)"
}
if let type = _model?.type {
typeLabel.text = (type == 1) ? " 测试版 " : " 线上版 " // 边距用空格占位
}
if let time = _model?.create_time {
let date = Date(timeIntervalSince1970: time)
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm MM.dd"
timeLabel.text = formatter.string(from: date)
}
noteLabel.text = _model?.note
if let icon = _model?.appid {
let url = URL(string: Api.baseUrl + Api.image + "\(icon).png")
iconImageView.kf.setImage(with: url, placeholder: UIImage(named: "icon"))
}
}
}
@IBOutlet weak var infoView: UIView!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var buildLabel: UILabel!
@IBOutlet weak var platformLabel: UILabel!
@IBOutlet weak var noteLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
infoView.layer.cornerRadius = 3
infoView.layer.masksToBounds = true
}
@IBAction func installAction(_ sender: Any) {
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func downloadAction(_ sender: UIButton) {
guard let name = model?.name else {
print("文件名为空")
return
}
let urlString = "itms-services://?action=download-manifest&url=" + Api.baseUrl + Api.file + (model?.name)! + ".plist"
if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}else{
print("下载失败")
}
}
}
|
bfd717b3a2778032529b522714d1cd73
| 28.776596 | 125 | 0.547338 | false | false | false | false |
muukii/PhotosPicker
|
refs/heads/master
|
PhotosPicker/Sources/PhotosPickerCollectionsItem.swift
|
mit
|
2
|
// PhotosPickerCollection.swift
//
// Copyright (c) 2015 muukii
//
// 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
import Photos
public class PhotosPickerCollectionsItem {
public private(set) var title: String
public private(set) var numberOfAssets: Int
public var assets: PhotosPickerAssets {
didSet {
self.cachedDividedAssets = nil
self.cachedTopImage = nil
}
}
public typealias SelectionHandler = ((collectionsController: PhotosPickerCollectionsController, item: PhotosPickerCollectionsItem) -> Void)
public var selectionHandler: SelectionHandler?
public func requestDividedAssets(result: ((dividedAssets: DividedDayPhotosPickerAssets) -> Void)?) {
if let dividedAssets = self.cachedDividedAssets {
result?(dividedAssets: dividedAssets)
return
}
self.assets.requestDividedAssets { (dividedAssets) -> Void in
self.cachedDividedAssets = dividedAssets
result?(dividedAssets: dividedAssets)
}
}
public func requestTopImage(result: ((image: UIImage?) -> Void)?) {
if let image = self.cachedTopImage {
result?(image: image)
return
}
self.requestDividedAssets { (dividedAssets) -> Void in
if let topAsset: PhotosPickerAsset = dividedAssets.first?.assets.first {
topAsset.requestImage(CGSize(width: 100, height: 100), result: { (image) -> Void in
self.cachedTopImage = image
result?(image: image)
return
})
}
}
}
public init(title: String, numberOfAssets: Int, assets: PhotosPickerAssets) {
self.title = title
self.numberOfAssets = numberOfAssets
self.assets = assets
}
// TODO: Cache
private var cachedTopImage: UIImage?
private var cachedDividedAssets: DividedDayPhotosPickerAssets?
}
|
6b6c7c4f49a1b38e8df2d86e758fe8a0
| 34.32967 | 143 | 0.639079 | false | false | false | false |
crescentflare/AppConfigSwift
|
refs/heads/master
|
AppConfigSwift/Classes/Model/AppConfigModelMapper.swift
|
mit
|
1
|
//
// AppConfigModelMapper.swift
// AppConfigSwift Pod
//
// Library model: mapping between dictionary and model
// Used to map values dynamically between the custom model and internally stored dictionaries (for overriding settings)
// Also provides optional categorization
//
// Enum for mapping mode
public enum AppConfigModelMapperMode {
case collectKeys
case toDictionary
case fromDictionary
}
// Mapping class
public class AppConfigModelMapper {
// --
// MARK: Members
// --
var categorizedFields: AppConfigOrderedDictionary<String, [String]> = AppConfigOrderedDictionary()
var globalCategorizedFields: AppConfigOrderedDictionary<String, [String]> = AppConfigOrderedDictionary()
var rawRepresentableFields: [String] = []
var rawRepresentableFieldValues: [String: [String]] = [:]
var dictionary: [String: Any] = [:]
var globalDictionary: [String: Any] = [:]
var mode: AppConfigModelMapperMode
// --
// MARK: Initialization
// --
// Initialization (for everything except FromDictionary mode)
public init(mode: AppConfigModelMapperMode) {
self.mode = mode
}
// Initialization (to be used with FromDictionary mode)
public init(dictionary: [String: Any], globalDictionary: [String: Any], mode: AppConfigModelMapperMode) {
self.dictionary = dictionary
self.globalDictionary = globalDictionary
self.mode = mode
}
// --
// MARK: Mapping
// --
// Map between key and value: boolean
public func map(key: String, value: inout Bool, category: String = "", global: Bool = false) {
if mode == .toDictionary {
if global {
globalDictionary[key] = value
} else {
dictionary[key] = value
}
} else if mode == .fromDictionary && global && globalDictionary[key] != nil {
value = globalDictionary[key] as! Bool
} else if mode == .fromDictionary && !global && dictionary[key] != nil {
value = dictionary[key] as! Bool
} else if mode == .collectKeys {
add(key: key, category: category, global: global)
}
}
// Map between key and value: int
public func map(key: String, value: inout Int, category: String = "", global: Bool = false) {
if mode == .toDictionary {
if global {
globalDictionary[key] = value
} else {
dictionary[key] = value
}
} else if mode == .fromDictionary && global && globalDictionary[key] != nil {
value = globalDictionary[key] as! Int
} else if mode == .fromDictionary && !global && dictionary[key] != nil {
value = dictionary[key] as! Int
} else if mode == .collectKeys {
add(key: key, category: category, global: global)
}
}
// Map between key and value: string
public func map(key: String, value: inout String, category: String = "", global: Bool = false) {
if mode == .toDictionary {
if global {
globalDictionary[key] = value
} else {
dictionary[key] = value
}
} else if mode == .fromDictionary && global && globalDictionary[key] != nil {
value = globalDictionary[key] as! String
} else if mode == .fromDictionary && !global && dictionary[key] != nil {
value = dictionary[key] as! String
} else if mode == .collectKeys {
add(key: key, category: category, global: global)
}
}
// Map between key and value: an enum containing a raw value (preferably string)
public func map<T: RawRepresentable>(key: String, value: inout T, fallback: T, allValues: [T], category: String = "", global: Bool = false) {
if mode == .toDictionary {
if global {
globalDictionary[key] = value.rawValue
} else {
dictionary[key] = value.rawValue
}
} else if mode == .fromDictionary && global && globalDictionary[key] != nil {
if let raw = globalDictionary[key] as? T.RawValue {
value = T(rawValue: raw)!
} else {
value = fallback
}
} else if mode == .fromDictionary && !global && dictionary[key] != nil {
if let raw = dictionary[key] as? T.RawValue {
value = T(rawValue: raw)!
} else {
value = fallback
}
} else if mode == .collectKeys {
var stringValues: [String] = []
for value in allValues {
if value.rawValue is String {
stringValues.append(value.rawValue as! String)
}
}
if stringValues.count > 0 {
rawRepresentableFieldValues[key] = stringValues
}
add(key: key, category: category, global: global, isRawRepresentable: true)
}
}
// After calling mapping on the model with to dictionary mode, retrieve the result using this function, for configuration settings
public func getDictionaryValues() -> [String: Any] {
return dictionary
}
// After calling mapping on the model with to dictionary mode, retrieve the result using this function, for global settings
public func getGlobalDictionaryValues() -> [String: Any] {
return globalDictionary
}
// --
// MARK: Field grouping
// --
// After calling mapping on the model with this object, retrieve the grouped/categorized fields, for configuration settings
public func getCategorizedFields() -> AppConfigOrderedDictionary<String, [String]> {
return categorizedFields
}
// After calling mapping on the model with this object, retrieve the grouped/categorized fields, for global settings
public func getGlobalCategorizedFields() -> AppConfigOrderedDictionary<String, [String]> {
return globalCategorizedFields
}
// After calling mapping on the model with this object, check if a given field is a raw representable class
public func isRawRepresentable(field: String) -> Bool {
return rawRepresentableFields.contains(field)
}
// After calling mapping on the model with this object, return a list of possible values (only for raw representable types)
public func getRawRepresentableValues(forField: String) -> [String]? {
return rawRepresentableFieldValues[forField]
}
// Internal method to keep track of keys and categories
private func add(key: String, category: String, global: Bool, isRawRepresentable: Bool = false) {
if global {
if globalCategorizedFields[category] == nil {
globalCategorizedFields[category] = []
}
globalCategorizedFields[category]!.append(key)
} else {
if categorizedFields[category] == nil {
categorizedFields[category] = []
}
categorizedFields[category]!.append(key)
}
if isRawRepresentable && !rawRepresentableFields.contains(key) {
rawRepresentableFields.append(key)
}
}
}
|
eccb17b23deeb319dd4e73830de67c1d
| 36.659794 | 145 | 0.600739 | false | true | false | false |
CosmicMind/Motion
|
refs/heads/develop
|
Pods/Motion/Sources/Preprocessors/IgnoreSubviewModifiersPreprocessor.swift
|
gpl-3.0
|
3
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class IgnoreSubviewTransitionsPreprocessor: MotionCorePreprocessor {
/**
Processes the transitionary views.
- Parameter fromViews: An Array of UIViews.
- Parameter toViews: An Array of UIViews.
*/
override func process(fromViews: [UIView], toViews: [UIView]) {
process(views: fromViews)
process(views: toViews)
}
/**
Process an Array of views for the cascade animation.
- Parameter views: An Array of UIViews.
*/
func process(views: [UIView]) {
for v in views {
guard let recursive = context[v]?.ignoreSubviewTransitions else {
continue
}
var parentView = v
if v is UITableView, let wrapperView = v.subviews.get(0) {
parentView = wrapperView
}
guard recursive else {
for subview in parentView.subviews {
context[subview] = nil
}
continue
}
cleanSubviewModifiers(for: parentView)
}
}
}
fileprivate extension IgnoreSubviewTransitionsPreprocessor {
/**
Clears the modifiers for a given view's subviews.
- Parameter for view: A UIView.
*/
func cleanSubviewModifiers(for view: UIView) {
for v in view.subviews {
context[v] = nil
cleanSubviewModifiers(for: v)
}
}
}
|
a667ba4bd9f92f05e898a3c8c8578d3f
| 30.607595 | 80 | 0.690028 | false | false | false | false |
mortorqrobotics/morscout-ios
|
refs/heads/master
|
MorScout/View Controllers/LoginVC.swift
|
mit
|
1
|
//
// LoginVC.swift
// MorScout
//
// Created by Farbod Rafezy on 1/16/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import Foundation
import UIKit
import SwiftyJSON
class LoginVC: UIViewController {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
usernameTextField.becomeFirstResponder()
}
func setupView() {
usernameTextField.delegate = self
passwordTextField.delegate = self
// set paddings for text fields
let usernamePaddingView = UIView(
frame: CGRect(x: 0, y: 0, width: 8, height: self.usernameTextField.frame.height))
let passwordPaddingView = UIView(
frame: CGRect(x: 0, y: 0, width: 8, height: self.passwordTextField.frame.height))
usernameTextField.leftView = usernamePaddingView
usernameTextField.leftViewMode = UITextFieldViewMode.always
passwordTextField.leftView = passwordPaddingView
passwordTextField.leftViewMode = UITextFieldViewMode.always
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func clickLogin(_ sender: UIButton) {
showLoading()
login()
}
func login() {
httpRequest(morTeamURL + "/login", type: "POST", data: [
"username": usernameTextField.text!,
"password": passwordTextField.text!,
"rememberMe": "true",
]) { responseText in
if responseText == "Invalid login credentials"{
DispatchQueue.main.async(execute: {
self.hideLoading()
alert(title: "Incorrect Username/Password", message: "This Username/Password combination does not exist.", buttonText: "OK", viewController: self)
})
} else {
//login successful
let user = parseJSON(responseText)
let storedUserProperties = [
"username", "firstname", "lastname",
"_id", "phone", "email", "profpicpath",]
//store user properties in storage
for (key, value):(String, JSON) in user {
if storedUserProperties.contains(key) {
storage.set(String(describing: value), forKey: key)
}
}
if user["team"].exists() {
storage.set(false, forKey: "noTeam")
storage.set(user["team"]["id"].stringValue, forKey: "team")
storage.set(user["position"].stringValue, forKey: "position")
self.goTo(viewController: "reveal")
} else {
storage.set(true, forKey: "noTeam")
self.goTo(viewController: "void") // this page gives users the option
// to join or create a team.
}
}
}
}
/**
Changes login button appearance to signify that
the user is in the process of being logged in
*/
func showLoading() {
loginButton.setTitle("Loading...", for: UIControlState())
loginButton.isEnabled = false
}
/**
Restores login button to original appearance.
*/
func hideLoading() {
self.loginButton.setTitle("Login", for: UIControlState())
self.loginButton.isEnabled = true
}
}
extension LoginVC: UITextFieldDelegate {
/*
This is called when the return button on
the keyboard is pressed.
*/
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.placeholder! == "Username/Email" {
passwordTextField.becomeFirstResponder()
} else if textField.placeholder! == "Password" {
showLoading()
login()
}
return true
}
}
|
eba441738c3cec649a5a4652bc50bc40
| 32.064 | 166 | 0.565449 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
refs/heads/master
|
Swift/LeetCode/记忆题 - 只需要记住最优解/362_Design Hit Counter.swift
|
mit
|
1
|
// 362_Design Hit Counter
// https://leetcode.com/problems/design-hit-counter/
//
// Created by Honghao Zhang on 10/9/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Design a hit counter which counts the number of hits received in the past 5 minutes.
//
//Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.
//
//It is possible that several hits arrive roughly at the same time.
//
//Example:
//
//HitCounter counter = new HitCounter();
//
//// hit at timestamp 1.
//counter.hit(1);
//
//// hit at timestamp 2.
//counter.hit(2);
//
//// hit at timestamp 3.
//counter.hit(3);
//
//// get hits at timestamp 4, should return 3.
//counter.getHits(4);
//
//// hit at timestamp 300.
//counter.hit(300);
//
//// get hits at timestamp 300, should return 4.
//counter.getHits(300);
//
//// get hits at timestamp 301, should return 3.
//counter.getHits(301);
//Follow up:
//What if the number of hits per second could be very large? Does your design scale?
//
// 返回过去5分钟内的hits的次数
import Foundation
class Num362 {
// MARK: - Use bucket
// https://leetcode.com/problems/design-hit-counter/discuss/83483/Super-easy-design-O(1)-hit()-O(s)-getHits()-no-fancy-data-structure-is-needed!
class HitCounter_Bucket {
// hits and timestamps have 300 size, like a circular array
// stores the hit count for an index
var hits: [Int]
// stores the time stamps for an index (index is the timestamp % 300)
var timestamps: [Int]
/** Initialize your data structure here. */
init() {
hits = Array(repeating: 0, count: 300)
timestamps = Array(repeating: 0, count: 300)
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
func hit(_ timestamp: Int) {
let index = timestamp % 300
if timestamps[index] != timestamp {
// if the timestamp at the index is not the same, this means a new cycle
// needs to reset the hits count to 1
timestamps[index] = timestamp
hits[index] = 1
}
else {
// if the timestamp is the same, we know this is duplicated hits at the same time
hits[index] += 1
}
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
func getHits(_ timestamp: Int) -> Int {
var count = 0
for i in 0..<300 {
// if the interval is within 300
if timestamp - timestamps[i] < 300 {
count += hits[i]
}
}
return count
}
}
// MARK: - Naive solution, use an array to store timestamps (use as a queue)
class HitCounter {
// stores the hit timestamp
var hits: [Int] = []
/** Initialize your data structure here. */
init() {
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
func hit(_ timestamp: Int) {
hits.append(timestamp)
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
func getHits(_ timestamp: Int) -> Int {
var count = 0
for h in hits.reversed() {
// 300
if h > timestamp - 300 {
count += 1
}
}
return count
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* let obj = HitCounter()
* obj.hit(timestamp)
* let ret_2: Int = obj.getHits(timestamp)
*/
}
|
2fd18a1c60f9875b1e085d30764835eb
| 27.076336 | 257 | 0.630234 | false | false | false | false |
moyazi/SwiftDayList
|
refs/heads/master
|
SwiftDayList/MainTableViewController.swift
|
mit
|
1
|
//
// MainTableViewController.swift
// SwiftDayList
//
// Created by leoo on 2017/5/27.
// Copyright © 2017年 Het. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
var dataSource:[String] = ["Day1","Day2","Day3","Day4","Day5","Day6","Day7","Day8"]
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
self.title = "Main Days"
self.clearsSelectionOnViewWillAppear = false
self.view.backgroundColor = UIColor(colorLiteralRed: 250/255.0, green: 250/255.0, blue: 225/255.0, alpha: 1)
self.tableView.tableHeaderView = UIView()
self.tableView.tableFooterView = UIView()
self.navigationController?.navigationBar.tintColor = UIColor.black
self.navigationController?.navigationBar.barTintColor = UIColor(colorLiteralRed: 250/255.0, green: 250/255.0, blue: 225/255.0, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCellIndentif", for: indexPath)
cell.textLabel?.text = self.dataSource[indexPath.row]
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.detailTextLabel?.textColor = UIColor.red
cell.backgroundColor = UIColor(colorLiteralRed: 250/255.0, green: 250/255.0, blue: 240/255.0, alpha: 0.8)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indef:String = self.dataSource[indexPath.row]
if indef == "Day2" {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "Day2MainViewController") as! Day2MainViewController
self.navigationController!.pushViewController(vc, animated: true)
return
}
if indef == "Day7" {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "Day7MainViewController") as! Day7MainViewController
self.navigationController!.pushViewController(vc, animated: true)
return
}
if indef == "Day8" {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "Day8MainViewController") as! Day8MainViewController
self.navigationController!.pushViewController(vc, animated: true)
return
}
if indef == "Day5" {
let vc = Day5MainViewController()
self.present(vc, animated: true, completion: nil)
return
}
//注意此处动态生成VC时必须要加上项目名 "SwiftDayList."
let VCClass = NSClassFromString("SwiftDayList."+indef+"MainViewController") as! UIViewController.Type
self.navigationController?.pushViewController(VCClass.init(), animated: true)
}
/*
// 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.
}
*/
}
|
13539ce2862ac5395d57fd0fbb9fdf08
| 39.69 | 144 | 0.664045 | false | false | false | false |
ikuehne/Papaya
|
refs/heads/master
|
Sources/Algorithms.swift
|
mit
|
1
|
/**
A file for basic graph algorithms, such as BFS, DFS, matchings, etc.
*/
/**
An array extension to pop the last element from an array.
*/
private extension Array {
mutating func pop() -> Element {
let element = self[self.count-1]
self.removeAtIndex(self.count-1)
return element
}
}
/**
A basic queue structure used by BFS algorithm.
*/
private struct Queue<Element> {
var items = [Element]()
mutating func enqueue(item: Element) {
items.insert(item, atIndex: 0)
}
mutating func dequeue() -> Element {
/*
let element = items[items.count-1]
items.removeAtIndex(items.count-1)
return element
*/
return items.pop()
}
var isEmpty : Bool {
return items.count == 0
}
}
/**
Creates a dictionary of successors in a graph, using the BFS algorithm and
starting at a given vertex.
- parameter graph: The graph to search in.
- parameter start: The vertex from which to begin the BFS.
- returns: A dictionary of each vertex's parent, or the vertex visited just
before the vertex.
*/
private func buildBFSParentDict<G: Graph, V: Hashable where V == G.Vertex>(
graph: G, start: V) -> [V: V] {
var queue = Queue<V>()
var visited = Set<V>()
var current: V
var result = [V: V]()
queue.enqueue(start)
visited.insert(start)
result[start] = start
while !queue.isEmpty {
current = queue.dequeue()
let neighbors = try! graph.neighbors(current)
for neighbor in neighbors {
if !visited.contains(neighbor) {
queue.enqueue(neighbor)
result[neighbor] = current
visited.insert(neighbor)
}
}
}
return result
}
/**
Gives the shortest path from one vertex to another in an unweighted graph.
- parameter graph: The graph in which to search.
- parameter start: The vertex from which to start the BFS.
- parameter end: The destination vertex.
- returns: An optional array that gives the shortest path from start to end.
returns nil if no such path exists.
*/
public func breadthFirstPath<G: Graph, V: Hashable where V == G.Vertex>(
graph: G, start: V, end: V) -> [V]? {
let parentsDictionary = buildBFSParentDict(graph, start: start)
var result: [V] = [end]
if end == start {
return result
}
if let first = parentsDictionary[end] {
var current = first
while current != start {
result.insert(current, atIndex: 0)
current = parentsDictionary[current]!
}
} else {
return nil
}
result.insert(start, atIndex: 0)
return result
}
// Idea- When lots of shortest paths queries are expected, there should be a
// way to store the parentsDictionary so it's only computed once.
/**
A structure describing a weighted edge. Prim's algorithm priority queue
holds these.
*/
private struct WeightedEdge<Vertex> {
let from: Vertex
let to: Vertex
let weight: Double
}
/**
Runs Prim's algorithm on a weighted undirected graph.
- parameter graph: A weighted undirected graph for which to create a minimum
spanning tree.
- returns: A minimum spanning tree of the input graph.
*/
public func primsSpanningTree<G: WeightedGraph where G.Vertex: Hashable>(
graph: G) -> G {
var tree = G()
var addedVerts = Set<G.Vertex>()
var queue = PriorityHeap<WeightedEdge<G.Vertex>>()
{ $0.weight < $1.weight }
let firstVertex = graph.vertices[0]
try! tree.addVertex(firstVertex)
addedVerts.insert(firstVertex)
for neighbor in try! graph.neighbors(firstVertex) {
let weight = try! graph.weight(firstVertex, to: neighbor)!
queue.insert(WeightedEdge<G.Vertex>(from: firstVertex, to: neighbor,
weight: weight))
}
var currentEdge: WeightedEdge<G.Vertex>
let target = graph.vertices.count
// currently, vertices is computed many times for each graph.
// trade some space for time and store sets of vertices?
while addedVerts.count < target {
repeat {
currentEdge = queue.extract()!
} while addedVerts.contains(currentEdge.to)
// can cause infinite loop?
// can cause unwrapping of nil?
try! tree.addVertex(currentEdge.to)
try! tree.addEdge(currentEdge.from, to: currentEdge.to,
weight: currentEdge.weight)
addedVerts.insert(currentEdge.to)
for neighbor in try! graph.neighbors(currentEdge.to) {
let weight = try! graph.weight(currentEdge.to, to: neighbor)
queue.insert(WeightedEdge<G.Vertex>(from: currentEdge.to,
to: neighbor, weight: weight!))
}
}
return tree
}
/*
/**
A structure used for storing shortest-path estimates for vertices in a graph.
*/
private struct WeightedVertex<V: Hashable>: Hashable {
let vertex: V
// The path weight bound and parent may be updated, or 'relaxed'
var bound: Double
var parent: V?
var hashValue : Int {
return vertex.hashValue
}
/*func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.vertex == rhs.vertex
}*/
}
private func ==<V: Hashable>(lhs: WeightedVertex<V>,
rhs: WeightedVertex<V>) -> Bool {
return lhs.vertex == rhs.vertex
}
*/
/**
A class for running Dijkstra's algorithm on weighted graphs.
It stores the .d and .pi attributes for the graph's vertices, as described in
CLRS, and handles procedures such as initialize single source and relax.
Note that Dijkstra assumes a positive-weight graph.
*/
private class DijkstraController<G: WeightedGraph,
V: Hashable where G.Vertex == V> {
var distances = [V: Double]()
var parents = [V: V]()
var graph: G
var start: V
/**
Initialize single source (see CLRS) - gives each vertex a distance
estimate of infinity (greater than the total weight of all edges in the
graph), and a parent value of nil (not in the dictionary).
- parameter g: A weighted graph on which we will be searching for shortest
paths.
- parameter start: the vertex to start from - this will get a distance
estimate of 0.
*/
init(g: G, s: V) {
graph = g
start = s
let totalweights = g.totalWeight + 1.0
for vertex in g.vertices {
distances[vertex] = totalweights
}
distances[start] = 0
}
/**
Relaxes the distance estimate of the second given vertex by way of the
first given vertex.
- parameter from: The vertex from which we relax the distance estimate.
- parameter to: the vertex for which we relax the distance estimate.
Note, this assumes that the edge and both vertices exist in the graph.
*/
func relax(from: V, to: V) {
let weight = try! graph.weight(from, to: to)!
if distances[to]! > distances[from]! + weight {
distances[to] = distances[from]! + weight
parents[to] = from
}
}
/**
Runs dijkstra's algorithm on the graph, as described in CLRS.
Just sets up the parent and distance bound dictionaries, does not return
any paths - that method is different.
*/
func dijkstra() {
var finished = Set<V>()
var queue = PriorityHeap<V>(items: graph.vertices) {
self.distances[$0]! <= self.distances[$1]!
}
while queue.peek() != nil {
let vertex = queue.extract()!
finished.insert(vertex)
for neighbor in try! graph.neighbors(vertex) {
relax(vertex, to: neighbor)
try! queue.increasePriorityMatching(neighbor,
matchingPredicate: { $0 == neighbor })
// this maintains the heap property - we may decrease the key
// of the neighbor
}
}
}
/**
Gives the shortest path to the given vertex.
- parameter to: The destination vertex of the path to find.
- returns: an array of vertices representing the shortest path, or nil if
no path exists in the graph.
*/
func dijkstraPath(to: V) -> [V]? {
if parents[to] == nil {
return nil
}
var result = [V]()
var current: V? = to
repeat {
result.insert(current!, atIndex: 0)
current = parents[current!]
} while current != nil && current != start
result.insert(start, atIndex: 0)
return result
}
}
public func dijkstraShortestPath<G: WeightedGraph,
V: Hashable where G.Vertex == V>(graph: G, start: V, end: V) -> [V]? {
let controller = DijkstraController<G, V>(g: graph, s: start)
controller.dijkstra()
return controller.dijkstraPath(end)
}
|
eb137c496d988dad73d75344a36d0748
| 28.174194 | 79 | 0.605705 | false | false | false | false |
googlecodelabs/admob-rewarded-video
|
refs/heads/master
|
ios/final/RewardedVideoExample/ViewController.swift
|
apache-2.0
|
1
|
//
// Copyright (C) 2017 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Firebase
import UIKit
class ViewController: UIViewController, GADRewardBasedVideoAdDelegate {
enum GameState: NSInteger {
case notStarted
case playing
case paused
case ended
}
/// Constant for coin rewards.
let gameOverReward = 1
/// Starting time for game counter.
let gameLength = 10
/// Number of coins the user has earned.
var coinCount = 0
/// The reward-based video ad.
var rewardBasedVideo: GADRewardBasedVideoAd!
/// The countdown timer.
var timer: Timer?
/// The game counter.
var counter = 10
/// The state of the game.
var gameState = GameState.notStarted
/// The date that the timer was paused.
var pauseDate: Date?
/// The last fire date before a pause.
var previousFireDate: Date?
/// In-game text that indicates current counter value or game over state.
@IBOutlet weak var gameText: UILabel!
/// Button to restart game.
@IBOutlet weak var playAgainButton: UIButton!
/// Text that indicates current coin count.
@IBOutlet weak var coinCountLabel: UILabel!
@IBOutlet weak var watchAdButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
rewardBasedVideo = GADRewardBasedVideoAd.sharedInstance()
rewardBasedVideo.delegate = self
coinCountLabel.text = "Coins: \(self.coinCount)"
// Pause game when application is backgrounded.
NotificationCenter.default.addObserver(self,
selector: #selector(ViewController.applicationDidEnterBackground(_:)),
name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
// Resume game when application is returned to foreground.
NotificationCenter.default.addObserver(self,
selector: #selector(ViewController.applicationDidBecomeActive(_:)),
name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
startNewGame()
}
// MARK: Game logic
fileprivate func startNewGame() {
gameState = .playing
counter = gameLength
playAgainButton.isHidden = true
watchAdButton.isHidden = true
rewardBasedVideo.load(GADRequest(),
withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
gameText.text = String(counter)
timer = Timer.scheduledTimer(timeInterval: 1.0,
target: self,
selector:#selector(ViewController.timerFireMethod(_:)),
userInfo: nil,
repeats: true)
}
func applicationDidEnterBackground(_ notification: Notification) {
// Pause the game if it is currently playing.
if gameState != .playing {
return
}
gameState = .paused
// Record the relevant pause times.
pauseDate = Date()
previousFireDate = timer?.fireDate
// Prevent the timer from firing while app is in background.
timer?.fireDate = Date.distantFuture
}
func applicationDidBecomeActive(_ notification: Notification) {
// Resume the game if it is currently paused.
if gameState != .paused {
return
}
gameState = .playing
// Calculate amount of time the app was paused.
let pauseTime = (pauseDate?.timeIntervalSinceNow)! * -1
// Set the timer to start firing again.
timer?.fireDate = (previousFireDate?.addingTimeInterval(pauseTime))!
}
func timerFireMethod(_ timer: Timer) {
counter -= 1
if counter > 0 {
gameText.text = String(counter)
} else {
endGame()
}
}
fileprivate func earnCoins(_ coins: NSInteger) {
coinCount += coins
coinCountLabel.text = "Coins: \(self.coinCount)"
}
fileprivate func endGame() {
gameState = .ended
gameText.text = "Game over!"
playAgainButton.isHidden = false
if rewardBasedVideo.isReady == true {
watchAdButton.isHidden = false
}
timer?.invalidate()
timer = nil
earnCoins(gameOverReward)
}
// MARK: Button actions
@IBAction func playAgain(_ sender: AnyObject) {
startNewGame()
}
@IBAction func watchAd(_ sender: Any) {
if rewardBasedVideo.isReady == true {
rewardBasedVideo.present(fromRootViewController: self)
}
}
// MARK: GADRewardBasedVideoAdDelegate implementation
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
didFailToLoadWithError error: Error) {
print("Reward based video ad failed to load: \(error.localizedDescription)")
}
func rewardBasedVideoAdDidReceive(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
print("Reward based video ad is received.")
}
func rewardBasedVideoAdDidOpen(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
print("Opened reward based video ad.")
}
func rewardBasedVideoAdDidStartPlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
print("Reward based video ad started playing.")
}
func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
print("Reward based video ad is closed.")
}
func rewardBasedVideoAdWillLeaveApplication(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
print("Reward based video ad will leave application.")
}
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
didRewardUserWith reward: GADAdReward) {
print("Reward received with currency: \(reward.type), amount \(reward.amount).")
earnCoins(NSInteger(reward.amount))
}
deinit {
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
}
|
1eee9cbe6f9a6b672f2ec17c28d96a46
| 28.252381 | 92 | 0.709914 | false | false | false | false |
brandonlee503/Atmosphere
|
refs/heads/master
|
Weather App/Forecast.swift
|
mit
|
2
|
//
// Forecast.swift
// Weather App
//
// Created by Brandon Lee on 8/17/15.
// Copyright (c) 2015 Brandon Lee. All rights reserved.
//
import Foundation
// Main purpose is to act as a wrapper for both the CurrentWeather and DailyWeather models
struct Forecast {
var currentWeather: CurrentWeather?
var weekly: [DailyWeather] = []
init(weatherDictionary: [String: AnyObject]?) {
// Parse the contents of dictionary and create populated instance of current weather
// Optional binding to make sure jsonDictionary returns non-nil value,
// if so cast it to a dictionary type and assign to variable
if let currentWeatherDictionary = weatherDictionary?["currently"] as? [String: AnyObject] {
currentWeather = CurrentWeather(weatherDictionary: currentWeatherDictionary)
}
// Because of the JSON nested dictionary response... And some pro optional chaining
if let weeklyWeatherArray = weatherDictionary?["daily"]?["data"] as? [[String: AnyObject]] {
// Iterate over weeklyWeatherArray and retrieve each object cast it to the daily local variable
for dailyWeather in weeklyWeatherArray {
// Create object for each day and append to weekly array
let daily = DailyWeather(dailyWeatherDict: dailyWeather)
weekly.append(daily)
}
}
}
}
|
5a0f5c64734ab699f5050d37cec42a18
| 39.277778 | 107 | 0.655172 | false | false | false | false |
jaynakus/Signals
|
refs/heads/master
|
SwiftSignalKit/Timer.swift
|
mit
|
1
|
import Foundation
public final class Timer {
private var timer: DispatchSourceTimer?
private var timeout: Double
private var `repeat`: Bool
private var completion: (Void) -> Void
private var queue: Queue
public init(timeout: Double, `repeat`: Bool, completion: @escaping(Void) -> Void, queue: Queue) {
self.timeout = timeout
self.`repeat` = `repeat`
self.completion = completion
self.queue = queue
}
deinit {
self.invalidate()
}
public func start() {
let timer = DispatchSource.makeTimerSource(queue: self.queue.queue)
timer.setEventHandler(handler: { [weak self] in
if let strongSelf = self {
strongSelf.completion()
if !strongSelf.`repeat` {
strongSelf.invalidate()
}
}
})
self.timer = timer
if self.`repeat` {
let time: DispatchTime = DispatchTime.now() + self.timeout
timer.scheduleRepeating(deadline: time, interval: self.timeout)
} else {
let time: DispatchTime = DispatchTime.now() + self.timeout
timer.scheduleOneshot(deadline: time)
}
timer.resume()
}
public func invalidate() {
if let timer = self.timer {
timer.cancel()
self.timer = nil
}
}
}
|
19e091d28643d38c273b662e7973a3a6
| 27.58 | 101 | 0.550035 | false | false | false | false |
lieonCX/TodayHeadline
|
refs/heads/master
|
TodayHealine/View/Main/PageTitleView.swift
|
mit
|
1
|
//
// PageTitleView.swift
// TodayHealine
//
// Created by lieon on 2017/1/16.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
private let scrollowLineH: CGFloat = 1.0
private let zoomScale: CGFloat = 1.2
private let labelCountPerPage: Int = 5
class PageTitleView: UIView {
var titleTapAction: ((_ index: Int) -> Void)?
var normalColor: (CGFloat, CGFloat, CGFloat) = (85, 85, 85) {
didSet {
for label in titleLabels {
label.textColor = UIColor(red: normalColor.0 / 255.0, green: normalColor.1 / 255.0, blue: normalColor.2 / 255.0, alpha: 1)
}
}
}
var selectColor: (CGFloat, CGFloat, CGFloat) = (255, 128, 0) {
didSet {
scrollLine.backgroundColor = UIColor(red: self.selectColor.0 / 255.0, green: self.selectColor.1 / 255.0, blue: self.selectColor.2 / 255.0, alpha: 1)
titleLabels[0].textColor = UIColor(red: selectColor.0 / 255.0, green: selectColor.1 / 255.0, blue: selectColor.2 / 255.0, alpha: 1)
}
}
fileprivate var currentIndex: Int = 0 {
didSet {
var offsetX: CGFloat = 0
if currentIndex > labelCountPerPage/2 {
offsetX = CGFloat(currentIndex) * labelWidth - bounds.width * 0.5 + labelWidth * 0.5
} else {
offsetX = 0
}
scrollView.setContentOffset(CGPoint(x:offsetX, y: 0), animated: true)
}
}
fileprivate var labelWidth: CGFloat = 0.0
fileprivate var titles: [String]
fileprivate var titleLabels: [UILabel] = [UILabel]()
fileprivate lazy var scrollView: UIScrollView = {
let sv = UIScrollView()
sv.showsHorizontalScrollIndicator = false
sv.showsVerticalScrollIndicator = false
sv.scrollsToTop = false
sv.bounces = true
return sv
}()
fileprivate lazy var scrollLine: UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor(red: self.selectColor.0 / 255.0, green: self.selectColor.1 / 255.0, blue: self.selectColor.2 / 255.0, alpha: 1)
return scrollLine
}()
init(frame: CGRect, titles: [String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
func setTitle(progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
let souceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
let offsetX = targetLabel.frame.origin.x - souceLabel.frame.origin.x
let totalX = offsetX * progress
scrollLine.frame.origin.x = souceLabel.frame.origin.x + totalX
let colorDelta = (selectColor.0 - normalColor.0, selectColor.1 - normalColor.1, selectColor.2 - normalColor.2)
souceLabel.textColor = UIColor(red: (selectColor.0 - colorDelta.0 * progress) / 255.0, green: (selectColor.1 - colorDelta.1 * progress) / 255.0, blue: (selectColor.2 - colorDelta.2 * progress) / 255.0, alpha: 1)
targetLabel.textColor = UIColor(red: (normalColor.0 + colorDelta.0 * progress) / 255.0, green: (normalColor.1 + colorDelta.1 * progress) / 255.0, blue: (normalColor.2 + colorDelta.2 * progress) / 255.0, alpha: 1)
currentIndex = targetIndex
}
}
extension PageTitleView {
fileprivate func setupUI() {
addSubview(scrollView)
scrollView.frame = bounds
scrollView.contentSize = CGSize(width: CGFloat(titles.count) * frame.width / CGFloat(labelCountPerPage), height: bounds.height)
setupTtitleLabels()
setupBottomLineAndScrollLine()
}
fileprivate func setupTtitleLabels() {
let labelW: CGFloat = frame.width / CGFloat(labelCountPerPage)
labelWidth = labelW
let labelH: CGFloat = frame.height
let labelY: CGFloat = 0.0
for (index, title) in titles.enumerated() {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(red: normalColor.0 / 255.0, green: normalColor.1 / 255.0, blue: normalColor.2 / 255.0, alpha: 1)
label.tag = index
label.textAlignment = .center
label.text = title
let labelX = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabels.append(label)
label.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(titleLabellCilck(tap:)))
label.addGestureRecognizer(tap)
}
}
fileprivate func setupBottomLineAndScrollLine() {
guard let firtLabel = titleLabels.first else { return }
firtLabel.textColor = UIColor(red: selectColor.0 / 255.0, green: selectColor.1 / 255.0, blue: selectColor.2 / 255.0, alpha: 1)
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: 0, y: frame.height - scrollowLineH, width: firtLabel.frame.width, height: scrollowLineH)
}
@objc private func titleLabellCilck(tap: UITapGestureRecognizer) {
guard let selectedLabel = tap.view as? UILabel else { return }
let oldLabel = titleLabels[currentIndex]
oldLabel.textColor = UIColor(red: normalColor.0 / 255.0, green: normalColor.1 / 255.0, blue: normalColor.2 / 255.0, alpha: 1)
selectedLabel.textColor = UIColor(red: selectColor.0 / 255.0, green: selectColor.1 / 255.0, blue: selectColor.2 / 255.0, alpha: 1)
currentIndex = selectedLabel.tag
let offsetX = CGFloat(currentIndex) * scrollLine.frame.width
UIView.animate(withDuration: 0.1) {
self.scrollLine.frame.origin.x = offsetX
}
if let block = titleTapAction {
block(selectedLabel.tag)
}
}
}
|
bcb452a12ecb6311dc98cdf1f79b8cb2
| 43.147059 | 220 | 0.634577 | false | false | false | false |
Huralnyk/rxswift
|
refs/heads/master
|
RxSwiftPlayground/RxSwift.playground/Pages/04. Filter Sequences.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import RxSwift
exampleOf(description: "filter") {
let disposeBag = DisposeBag()
let numbers = Observable.generate(initialState: 1, condition: { $0 < 101 }, iterate: { $0 + 1 })
numbers.filter { number in
guard number > 1 else { return false }
for i in 2 ..< number {
if number % i == 0 {
return false
}
}
return true
}.toArray()
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
exampleOf(description: "distinctUntilChange") {
let disposeBag = DisposeBag()
let searchString = Variable("")
searchString.asObservable().map {
$0.lowercased()
}.distinctUntilChanged().subscribe(onNext: {
print($0)
}).addDisposableTo(disposeBag)
searchString.value = "APPLE"
searchString.value = "apple"
searchString.value = "banana"
searchString.value = "apple"
}
exampleOf(description: "takeWhile") {
let disposeBag = DisposeBag()
let numbers = Observable.from([1, 2, 3, 4, 3, 2, 1])
numbers.takeWhile { $0 < 4 }
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
//: [Next](@next)
|
30ba111cf6a47de9787ce54915493707
| 26.222222 | 100 | 0.586939 | false | false | false | false |
tdquang/CarlWrite
|
refs/heads/master
|
CarlWrite/dataFile.swift
|
mit
|
1
|
//
// dataFile.swift
// This file contains all the information from the writing center that the app uses.
// WrittingApp
//
// Quang Tran & Anmol Raina
// Copyright (c) 2015 Quang Tran. All rights reserved.
//
import UIKit
class dataFile {
// The code below allows changing this file
class var sharedInstance: dataFile {
struct Static {
static var instance: dataFile?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = dataFile()
}
return Static.instance!
}
// Harcoded date. In the future these variables will use the GET command to get data from the Carleton Server
var listOfAppointments = [[String]]()
var tutorArray = ["Any Tutor", "Anna", "Dave", "Jeff", "Michael", "Sam"]
var formFields = ["Date", "Course", "Instructor", "Topic", "Type", "State", "Due Date", "Class year", "Major", "First Visit?", "Copy for Prof?"]
var paperLengthArray = ["1-2", "3-5", "6-10","11-20","20+"]
var currentStateArray = ["Brainstorming", "First Draft", "Second Draft", "Final Draft"]
var paperTypeArray = ["Essay", "Comps", "Resume", "Portfolio", "Application", "Other"]
var dueDateArray = ["Today", "Tomorrow", "2 days", "3-5 days", "A week", "1 week+"]
var goalsForVisit = ["Clarity", "Thesis/Flow", "Organization", "Citation", "Brainstorming", "Integrating evidence/support", "Learning how to proofread"]
var classYearArray = ["2016", "2017", "2018", "2019"]
var majorArray = ["English", "History", "Philosophy", "Economics", "Computer Science"]
var yesNoArray = ["Yes", "No"]
var visitSourceArray = ["Does not apply", "From an instructor", "From orientation", "From an advertisement", "From a student", "Other"]
var tutorDays = [[1,2,3,4,5,6], [2,4,5], [1,4,6], [2,3], [1,3,5], [1,2,5,6]]
func returnTutorDays(tutorName: String) -> [Int]{
for var index = 0; index < tutorArray.count; ++index{
if tutorArray[index] == tutorName{
return tutorDays[index]
}
}
return []
}
func returnAppointmentTimes(_: CVCalendarDayView) -> [String]{
return ["9:00", "9:20", "10:00", "10:20", "11:00", "11:20", "12:00"]
}
func returnListOfTutors() -> [String]{
return tutorArray
}
func returnPaperLengths() -> [String]{
return paperLengthArray
}
func returnListOfStates() -> [String]{
return currentStateArray
}
func returnPaperType() -> [String]{
return paperTypeArray
}
func returnDueDate() -> [String]{
return dueDateArray
}
func returnGoalsForVisit() -> [String]{
return goalsForVisit
}
func returnClassYear() -> [String]{
return classYearArray
}
func returnMajor() -> [String]{
return majorArray
}
func returnYesNo() -> [String]{
return yesNoArray
}
func returnVisitSource() -> [String]{
return visitSourceArray
}
func returnFormFields() -> [String]{
return formFields
}
func addAppointment(appointmentDetails: [String]){
listOfAppointments.append(appointmentDetails)
}
}
|
508f8c2ee1287f114166632625b7552e
| 33.638298 | 156 | 0.600123 | false | false | false | false |
Saturn-Five/ComicZipper
|
refs/heads/master
|
ComicZipper/Support/OperationError.swift
|
mit
|
2
|
//
// OperationError.swift
// ComicZipper
//
// Created by Ardalan Samimi on 04/01/16.
// Copyright © 2016 Ardalan Samimi. All rights reserved.
//
import Foundation
import ZipUtilities
public enum OperationError {
static func withCode(code: Int) -> String {
var error = "Error: "
switch (code) {
case NOZErrorCode.CompressFailedToOpenNewZipFile.rawValue:
error += "Could not create zip file."
case NOZErrorCode.CompressNoEntriesToCompress.rawValue:
error += "No files to compress."
case NOZErrorCode.CompressMissingEntryName.rawValue:
error += "Missing name for a file."
case NOZErrorCode.CompressEntryCannotBeZipped.rawValue:
error += "Failed to compress file(s)."
case NOZErrorCode.CompressFailedToAppendEntryToZip.rawValue:
error += "Failed to append file to zip."
case NOZErrorCode.CompressFailedToFinalizeNewZipFile.rawValue:
error += "Could not finalize archive."
default:
error += "Unknown error with code \(code)"
}
return error
}
}
|
92799dfef480edbce1284ebea0686d0c
| 28.222222 | 66 | 0.697719 | false | false | false | false |
jatraiz/IBFree
|
refs/heads/master
|
IBFree Project/IBFree/XiblessView.swift
|
mit
|
1
|
//
// XiblessView.swift
// XIBLessExample
//
// Created by John Stricker on 7/11/16.
import Anchorage
import UIKit
final class XiblessView: UIView {
enum ViewStyle {
case simpleButton
case cornerButtons
}
fileprivate let cornerButtons: [UIButton]?
fileprivate let button: UIButton = UIButton(type: .system)
init(style: ViewStyle) {
// Create the corner buttons if the style calls for it
if style == .cornerButtons {
var buttonArray = [UIButton]()
for _ in 0..<Constants.numberOfCornerButtons {
buttonArray.append(UIButton(type: .system))
}
cornerButtons = buttonArray
} else {
cornerButtons = nil
}
super.init(frame: CGRect.zero)
configureView()
}
@available(*, unavailable) override init(frame: CGRect) {
fatalError("init(frame:) has not been implemented")
}
@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Configure the view
private extension XiblessView {
struct Constants {
static let numberOfCornerButtons = 4
static let cornerButtonSize = CGSize(width: 60, height: 60)
static let cornerButtonBackgroundColor = UIColor.lightGray
}
enum ButtonPositions: Int {
case upperLeft = 0
case upperRight = 1
case lowerLeft = 2
case lowerRight = 3
}
func configureView() {
configureCenterButton()
if let buttons = cornerButtons {
configureCornerButtons(buttons)
}
}
func configureCenterButton() {
// View heirarchy
addSubview(button)
// Style
backgroundColor = UIColor.green
button.setTitle("This is a centered button without a XIB", for: UIControlState())
// Layout
// The button is centered in the view
button.centerXAnchor == centerXAnchor
button.centerYAnchor == centerYAnchor
}
func configureCornerButtons(_ buttons: [UIButton]) {
for (index, button) in buttons.enumerated() {
// First make sure that the button's index has a position defined for it
guard let position = ButtonPositions(rawValue: index) else {
debugPrint("Error: \(index) not defined in ButtonPositions")
continue
}
// View heirarchy
addSubview(button)
// Style & Layout
// Button content and style
button.setTitle(String(index + 1), for: UIControlState())
button.backgroundColor = Constants.cornerButtonBackgroundColor
// Height and width of corner buttons are set by a constant
button.heightAnchor == Constants.cornerButtonSize.height
button.widthAnchor == Constants.cornerButtonSize.width
// Place each button in its appropriate corner
switch position {
case .upperLeft:
button.leftAnchor == leftAnchor
button.topAnchor == topAnchor
case .upperRight:
button.rightAnchor == rightAnchor
button.topAnchor == topAnchor
case .lowerLeft:
button.leftAnchor == leftAnchor
button.bottomAnchor == bottomAnchor
case .lowerRight:
button.rightAnchor == rightAnchor
button.bottomAnchor == bottomAnchor
}
}
}
}
|
dfe45302a4b132eef00684222c9f0f63
| 26.549618 | 89 | 0.5913 | false | true | false | false |
EasySwift/EasySwift
|
refs/heads/master
|
Carthage/Checkouts/Bond/Sources/NSObject.swift
|
apache-2.0
|
6
|
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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
import ReactiveKit
public protocol Deallocatable: class {
var bnd_deallocated: Signal<Void, NoError> { get }
}
extension NSObject: Deallocatable {
private struct AssociatedKeys {
static var DeallocationSignalHelper = "DeallocationSignalHelper"
static var DisposeBagKey = "r_DisposeBagKey"
}
private class BNDDeallocationSignalHelper {
let subject = ReplayOneSubject<Void, NoError>()
deinit {
subject.completed()
}
}
/// A signal that fires completion event when the object is deallocated.
public var bnd_deallocated: Signal<Void, NoError> {
if let helper = objc_getAssociatedObject(self, &AssociatedKeys.DeallocationSignalHelper) as? BNDDeallocationSignalHelper {
return helper.subject.toSignal()
} else {
let helper = BNDDeallocationSignalHelper()
objc_setAssociatedObject(self, &AssociatedKeys.DeallocationSignalHelper, helper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return helper.subject.toSignal()
}
}
/// Use this bag to dispose disposables upon the deallocation of the receiver.
public var bnd_bag: DisposeBag {
if let disposeBag = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBagKey) {
return disposeBag as! DisposeBag
} else {
let disposeBag = DisposeBag()
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBagKey, disposeBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return disposeBag
}
}
/// Bind `signal` to `bindable` and dispose in `bnd_bag` of receiver.
@discardableResult
public func bind<O: SignalProtocol, B: BindableProtocol>(_ signal: O, to bindable: B) where O.Element == B.Element, O.Error == NoError {
signal.bind(to: bindable).disposeIn(bnd_bag)
}
/// Bind `signal` to `bindable` and dispose in `bnd_bag` of receiver.
@discardableResult
public func bind<O: SignalProtocol, B: BindableProtocol>(_ signal: O, to bindable: B) where B.Element: OptionalProtocol, O.Element == B.Element.Wrapped, O.Error == NoError {
signal.bind(to: bindable).disposeIn(bnd_bag)
}
}
|
8d4fc7378df3ad774fa744e3ab854a0e
| 40.025 | 175 | 0.735222 | false | false | false | false |
samsao/DataProvider
|
refs/heads/master
|
Pod/Classes/Provider/Provider.swift
|
mit
|
1
|
//
// Provider.swift
// Pods
//
// Created by Guilherme Silva Lisboa on 2015-12-22.
//
//
public typealias ProviderRemoveItemBlock = ((_ item : ProviderItem) -> Bool)
public typealias ProviderRemoveSectionBlock = ((_ section : ProviderSection) -> Bool)
public class Provider {
// MARK: Properties
public private(set) var sections : [ProviderSection]
// MARK: Initialization
/**
Initialize provider with array of elements
- parameter sections: sections for the provider.
- returns: instance of created provider.
*/
internal init(withSections sections : [ProviderSection]) {
self.sections = sections
}
// MARK: - Public API
// MARK: Data Methods
/**
Get the provider item at a specific index path
- parameter indexPath: index path of the desired item.
- returns: item at that index path.
*/
public func providerItemAtIndexPath(indexPath : IndexPath) -> ProviderItem? {
if(indexPath.section < self.sections.count) {
let section : ProviderSection = self.sections[indexPath.section]
if(indexPath.row < section.items.count) {
return section.items[indexPath.row]
}
}
return nil
}
// MARK: Sections
/**
Add sections to provider.
- parameter sections: sections to be added.
- returns: indexset with added sections range.
*/
internal func addSections(sections : [ProviderSection]) -> IndexSet{
var range : NSRange = NSRange()
range.location = self.sections.count
range.length = sections.count
let indexSet : IndexSet = IndexSet(integersIn: range.toRange() ?? 0..<0)
self.sections.append(contentsOf: sections)
return indexSet
}
/**
Add section to provider
- parameter section: section to be added.
- parameter index: index for the section to be added.
*/
internal func addSection(section : ProviderSection, index : Int) {
self.sections.insert(section, at: index)
}
/**
Remove sections with a index set.
- parameter indexes: index set with sections indexes to be deleted.
*/
internal func removeSections(indexes : IndexSet) {
self.sections.removeObjectsWith(indexSet: indexes)
}
/**
Remove sections of the provider.
- parameter sectionsToRemove: array of sections to remove in the provider.
- returns: index set of removed sections.
*/
internal func removeSections(_ removeBlock : ProviderRemoveSectionBlock) -> IndexSet {
var indexSet = IndexSet()
for (index, section) in self.sections.enumerated() {
if removeBlock(section) {
indexSet.insert(index)
}
}
self.sections.removeObjectsWith(indexSet: indexSet)
return indexSet
}
// MARK: Items
/**
Add Item to provider at a index path
- parameter item: item to be added.
- parameter indexPath: index path to add this item at.
*/
internal func addItemToProvider(item : ProviderItem, atIndexPath indexPath : IndexPath) {
self.sections[indexPath.section].items.insert(item, at: indexPath.row)
}
/**
Add an array of items in a section of the provider.
- parameter items: items to be added.
- parameter section: index of the provider section to add the items.
*/
internal func addItemsToProvider(items : [ProviderItem], inSection sectionIndex : Int) {
self.sections[sectionIndex].items.append(contentsOf: items)
}
/**
Remove items from provider
- parameter removeBlock: Block to remove the item.
- parameter sectionIndex: section index to remove this items from.
- returns: indexes of the deleted items in the section.
*/
internal func removeItems(removeBlock : ProviderRemoveItemBlock, inSection sectionIndex : Int) -> IndexSet{
var indexSet = IndexSet()
for (index, item) in self.sections[sectionIndex].items.enumerated() {
if removeBlock(item) {
indexSet.insert(index)
}
}
self.sections[sectionIndex].items.removeObjectsWith(indexSet: indexSet)
return indexSet
}
/**
Remove items at index paths
- parameter indexPaths: index paths to be removed.
*/
internal func removeItems(indexPaths : [IndexPath]) {
indexPaths.forEach { (indexPath) in
self.sections[indexPath.section].items.remove(at: indexPath.row);
}
}
// MARK: update Data
/**
Replace provider data with new one.
- parameter newSections: new provider data.
*/
internal func updateProviderData(newSections : [ProviderSection]) {
self.sections = newSections
}
/**
Replace the data in a specific section in the provider for the new one.
- parameter newItems: new section data.
- parameter sectionIndex: index of the section to replace the data.
*/
internal func updateSectionData(newItems : [ProviderItem], sectionIndexToUpdate sectionIndex : Int) {
self.sections[sectionIndex].items = newItems
}
internal func nullifyDelegates() {
return
}
}
|
1905cbdb568177aba3fd87f316fb8ff1
| 27.554974 | 111 | 0.620279 | false | false | false | false |
YMXian/Deliria
|
refs/heads/master
|
Deliria/UIKit/UIGeometry/UIOffset+Vector2DConvertible.swift
|
mit
|
1
|
//
// UIOffset+Vector2DConvertible.swift
// Deliria
//
// Created by Yanke Guo on 16/2/9.
// Copyright © 2016年 JuXian(Beijing) Technology Co., Ltd. All rights reserved.
//
import UIKit
extension UIOffset: Vector2DConvertible, ExpressibleByArrayLiteral {
public var x: CGFloat {
get {
return self.horizontal
}
set(value) {
self.horizontal = value
}
}
public var y: CGFloat {
get {
return self.vertical
}
set(value) {
self.vertical = value
}
}
public init(x: CGFloat, y: CGFloat) {
self.horizontal = x
self.vertical = y
}
public typealias Element = CGFloat
public init(arrayLiteral elements: CGPoint.Element...) {
self.init(horizontal: elements[0], vertical: elements[1])
}
}
extension Vector2DConvertible {
public var offset: UIOffset {
return UIOffset(horizontal: self.x, vertical: self.y)
}
}
|
0895cd61ea3d4b2d97545599c5bb82a3
| 17.1 | 79 | 0.648619 | false | false | false | false |
gssdromen/CedFilterView
|
refs/heads/master
|
FilterTest/ESFFilterItemModel.swift
|
gpl-3.0
|
1
|
//
// ESFFilterModel.swift
// JingJiRen_ESF_iOS
//
// Created by cedricwu on 12/29/16.
// Copyright © 2016 Cedric Wu. All rights reserved.
//
import ObjectMapper
extension ESFFilterItemModel {
class func getDepth(model: ESFFilterItemModel) -> Int {
var max = 0
guard model.subItems != nil else {
return max + 1
}
for item in model.subItems! {
let height = ESFFilterItemModel.getDepth(model: item)
if height > max {
max = height
}
}
return max + 1
}
}
extension ESFFilterItemModel {
func getDepth() -> Int {
var depth = 0
if subItems == nil {
return depth
}
for item in subItems! {
let height = item.getDepth()
depth = max(height, depth)
}
return depth + 1
}
}
class ESFFilterItemModel: NSObject, Mappable {
// var maxDepth = -1
var depth: Int?
var maxDepth: Int?
var displayText: String?
var filterKey: String?
var fullFilterKey: String?
var id: Int?
var multiple: Bool?
var selected: Bool?
var style: Int?
var extInfo: String?
var subItems: [ESFFilterItemModel]?
required init?(map: Map) {
}
func mapping(map: Map) {
depth <- map["depth"]
maxDepth <- map["maxDepth"]
displayText <- map["displayText"]
filterKey <- map["filterKey"]
fullFilterKey <- map["fullFilterKey"]
id <- map["id"]
multiple <- map["multiple"]
selected <- map["selected"]
style <- map["style"]
extInfo <- map["extInfo"]
subItems <- map["subItems"]
}
}
|
9ec4cc334dbae6a96d2ee9bc21543cf4
| 21.368421 | 65 | 0.548824 | false | false | false | false |
butterproject/butter-ios
|
refs/heads/master
|
Butter/API/ButterItem.swift
|
gpl-3.0
|
1
|
//
// ButterItem.swift
// Butter
//
// Created by DjinnGA on 24/07/2015.
// Copyright (c) 2015 Butter Project. All rights reserved.
//
import Foundation
import SwiftyJSON
class ButterItem {
var id: Int
var properties:[String:AnyObject] = [String:AnyObject]()
var torrents: [String:ButterTorrent] = [String:ButterTorrent]()
func setProperty(name:String, val:AnyObject) {
properties[name] = val
}
func getProperty(name:String) -> AnyObject? {
return properties[name]
}
func hasProperty(name: String) -> Bool {
return getProperty(name) != nil
}
init(id:Int,torrents: JSON) {
self.id = id
if (torrents != "") {
for (_, subJson) in torrents {
if let url = subJson["url"].string {
let tor = ButterTorrent(
url: url,
seeds: subJson["seeds"].int!,
peers: subJson["peers"].int!,
quality: subJson["quality"].string!,
size: subJson["size"].string!,
hash: subJson["hash"].string!)
self.torrents[subJson["quality"].string!] = tor
}
}
}
}
init(id:Int,torrentURL: String, quality: String, size: String) {
self.id = id
let tor = ButterTorrent(
url: torrentURL,
seeds: 0,
peers: 0,
quality: quality,
size: size,
hash: "")
self.torrents[quality] = tor
}
init(id:Int,torrents: [ButterTorrent]) {
self.id = id
for tor in torrents {
self.torrents[tor.quality] = tor
}
}
}
|
3bd5aea3f791825f62319c44e0656dc1
| 25.820896 | 68 | 0.488592 | false | false | false | false |
xiaoyangrun/DYTV
|
refs/heads/master
|
DYTV/DYTV/Classes/Home/Controller/HomeViewController.swift
|
mit
|
1
|
//
// HomeViewController.swift
// DYTV
//
// Created by 小羊快跑 on 2017/1/11.
// Copyright © 2017年 小羊快跑. All rights reserved.
//
import UIKit
// MARK: - 系统回调函数
class HomeViewController: UIViewController {
// MARK: - 懒加载属性
//闭包创建
private lazy var pageTitleView: PageTitleView = {
let titleFrame = CGRect.init(x: 0, y: 64, width: UIScreen.main.bounds.size.width, height: 44)
let titles = ["推荐", "游戏", "娱乐", "去玩"];
let titleView = PageTitleView.init(frame: titleFrame, titles: titles, isScrollEnable: false)
return titleView
}() //记得加上 ()
override func viewDidLoad() {
super.viewDidLoad()
//记得添加, 不添加就显示不出来
automaticallyAdjustsScrollViewInsets = false
//设置导航栏
setupNavigationBar()
//添加pageTitleView
view.addSubview(pageTitleView)
}
}
// MARK: - 设置导航栏内容
extension HomeViewController{
//设置导航设置导航栏内容
func setupNavigationBar(){
setupLeftNavigationBar()
setupRightNavigationBar()
}
//设置左边
func setupLeftNavigationBar(){
let btn = UIButton()
btn.setImage(UIImage(named: "logo"), for: .normal)
btn.sizeToFit()
btn.addTarget(self, action: #selector(leftItemClick), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: btn)
}
//设置右边
func setupRightNavigationBar(){
//0.确定uibutton的 尺寸
let size = CGSize.init(width: 40, height: 44)
//1.创建历史按钮
let historyItem = UIBarButtonItem.init(imageName: "Image_my_history", highImageName: "Image_my_history_click", size: size, target: self, action: #selector(historyItemClick))
//2.创建二维码按钮
let qrCodeItem = UIBarButtonItem.init(imageName: "Image_scan", highImageName: "Image_scan_click", size: size, target: self, action: #selector(qrCodeItemClick))
//3.创建搜索按钮
let searchItem = UIBarButtonItem.init(imageName: "btn_search", highImageName: "btn_search_clicked", size: size, target: self, action: #selector(searchItemClick))
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrCodeItem]
}
// MARK: 导航栏的事件处理
@objc private func leftItemClick() {
print("点击了logo")
}
@objc private func qrCodeItemClick() {
print("点击了二维码")
}
@objc private func searchItemClick() {
print("点击了搜索")
}
@objc private func historyItemClick() {
print("点击了历史")
}
}
|
3d7cfeca34fce452d72b45d954cdd816
| 30.935897 | 181 | 0.637094 | false | false | false | false |
pisrc/RxDobby
|
refs/heads/master
|
RxDobbyExample/MenuViewController.swift
|
mit
|
1
|
//
// MenuViewController.swift
// RxDobby
//
// Created by ryan on 9/8/16.
// Copyright © 2016 kimyoungjin. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addGestureRecognizer(
UIPanGestureRecognizer(target: self, action: #selector(MenuViewController.viewPannedLeft(_:))))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
weak var centerViewController: UIViewController?
var oldXPostion: CGFloat = 0.0
func viewPannedRight(_ recognizer: UIPanGestureRecognizer) {
guard let centerViewController = centerViewController else {
return
}
let leftToRight = (recognizer.velocity(in: view).x > 0)
switch recognizer.state {
case .began:
oldXPostion = view.frame.origin.x
case .changed:
let deltaX = recognizer.translation(in: view).x
recognizer.setTranslation(CGPoint.zero, in: view)
if view.frame.origin.x + deltaX > centerViewController.view.frame.width {
break
}
if view.frame.origin.x + view.frame.width + deltaX < centerViewController.view.frame.width {
break
}
view.frame.origin.x = view.frame.origin.x + deltaX
case .ended:
if leftToRight {
dismiss(animated: true, completion: nil)
} else {
// 처음 위치로 되돌아감
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0,
options: UIViewAnimationOptions(),
animations: {
self.view.frame.origin.x = self.oldXPostion
},
completion: nil)
}
default:
break
}
}
func viewPannedLeft(_ recognizer: UIPanGestureRecognizer) {
let rightToLeft = (recognizer.velocity(in: view).x < 0)
switch recognizer.state {
case .began:
oldXPostion = view.frame.origin.x
case .changed:
let deltaX = recognizer.translation(in: view).x
recognizer.setTranslation(CGPoint.zero, in: view)
if 0 < view.frame.origin.x + deltaX {
break
}
if view.frame.origin.x + view.frame.width + deltaX < 0 {
break
}
view.frame.origin.x = view.frame.origin.x + deltaX
case .ended:
if rightToLeft {
dismiss(animated: true, completion: nil)
} else {
// 처음 위치로 되돌아감
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0,
options: UIViewAnimationOptions(),
animations: {
self.view.frame.origin.x = self.oldXPostion
},
completion: nil)
}
default:
break
}
}
}
|
2230a598c6c834b833123f2029de9516
| 31.507937 | 107 | 0.493652 | false | false | false | false |
google/iosched-ios
|
refs/heads/master
|
Source/IOsched/Screens/Home/HomeMomentsDataSource.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public struct Moment {
enum CTA: String {
case viewLivestream = "LIVE_STREAM"
case viewMap = "MAP_LOCATION"
}
let attendeeRequired: Bool
let cta: CTA?
let displayDate: String // Ignored. Using Date formatter instead.
let startTime: Date
let endTime: Date
let featureID: String?
let featureName: String?
let imageURL: URL
let imageURLDarkTheme: URL
let streamURL: URL?
let textColor: String
let timeVisible: Bool
let title: String
var formattedDateInterval: String {
return Moment.dateIntervalFormatter.string(from: startTime, to: endTime)
}
var accessibilityLabel: String? {
switch self {
case .keynote:
return NSLocalizedString("Watch the Google I/O keynote.",
comment: "Accessibility label for keynote moment")
case .developerKeynote:
return NSLocalizedString("Watch the Google I/O developer keynote.",
comment: "Accessibility label for keynote moment")
case .lunchDayOne, .lunchDayTwo, .lunchDayThree:
return NSLocalizedString("Visit one of the EATS food stands to grab some lunch.",
comment: "Accessibility label for lunch moment")
case .sessionsDayOne, .sessionsDayTwoMorning, .sessionsDayTwoAfternoon,
.sessionsDayThreeMorning, .sessionsDayThreeAfternoon:
return NSLocalizedString("Tune in to live sessions on the I/O livestream.",
comment: "Accessibility label for sessions moment")
case .afterHoursDinner:
return NSLocalizedString("Eat dinner after hours at the I/O venue.",
comment: "Accessibility label for dinner moment")
case .dayOneWrap:
return NSLocalizedString("Day one of Google I/O has concluded.",
comment: "Accessibility label for end of day 1")
case .dayTwoMorning:
return NSLocalizedString("Get ready for day two of Google I/O.",
comment: "Accessibility label for day 2 morning moment")
case .concert:
return NSLocalizedString("Join the I/O concert in person or remotely via livestream.",
comment: "Accessibility label for concert moment")
case .dayTwoWrap:
return NSLocalizedString("Day two of Google I/O has concluded.",
comment: "Accessibility label for end of day 2")
case .dayThreeMorning:
return NSLocalizedString("Get ready for day three of Google I/O.",
comment: "Accessibility label for day 3 morning moment")
case .dayThreeWrap:
return NSLocalizedString("This year's Google I/O has concluded. See you next year!",
comment: "Accessibility label for end of day 3")
case _:
break
}
return nil
}
var accessibilityHint: String? {
if cta == .viewLivestream, self == .keynote || self == .developerKeynote {
return NSLocalizedString("Double-tap to open keynote details",
comment: "Accessibility hint for activatable cell")
}
if cta == .viewLivestream {
return NSLocalizedString("Double-tap to open livestream link",
comment: "Accessibility hint for activatable cell")
}
if cta == .viewMap {
return NSLocalizedString("Double-tap to open in map",
comment: "Accessibility hint for activatable cell")
}
return nil
}
private static let dateFormatter: DateFormatter = {
// Example date: "2019-05-07 11:30:00 -0700"
let formatter = TimeZoneAwareDateFormatter()
formatter.timeZone = TimeZone.userTimeZone()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
return formatter
}()
private static let dateIntervalFormatter: DateIntervalFormatter = {
let formatter = DateIntervalFormatter()
formatter.timeZone = TimeZone.userTimeZone()
formatter.dateStyle = .none
formatter.timeStyle = .short
registerForTimeZoneUpdates()
return formatter
}()
private static func registerForTimeZoneUpdates() {
_ = NotificationCenter.default.addObserver(forName: .timezoneUpdate,
object: nil,
queue: nil) { _ in
dateIntervalFormatter.timeZone = TimeZone.userTimeZone()
}
}
// MARK: - Moment constants
static let keynote = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 7th",
startTime: dateFormatter.date(from: "2019-05-07 10:00:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-07 11:30:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHome-GoogleKeynote%402x.png?alt=media&token=0df80e81-5bea-4171-9016-4f1e3dcfc7f9")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-GoogleKeynote%402x.png?alt=media&token=bfd169ae-f501-4cf8-94be-462682d40fd7")!,
streamURL: URL(string: "https://youtu.be/JuMbOCQu-XM"),
textColor: "#ffffff",
timeVisible: true,
title: "Keynote"
)
static let lunchDayOne = Moment(
attendeeRequired: true,
cta: .viewMap,
displayDate: "May 7th",
startTime: dateFormatter.date(from: "2019-05-07 11:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-07 12:45:00 -0700")!,
featureID: "eats",
featureName: "EATS",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FSchedule-Lunch-1%402X.png?alt=media&token=0bdab2ab-b1ac-4c70-8ffb-4f3f317f5531")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Schedule-Lunch-1%402X.png?alt=media&token=21ab538e-a791-49c5-b3d8-cc0c92b6f460")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: true,
title: "Lunch"
)
static let developerKeynote = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 7th",
startTime: dateFormatter.date(from: "2019-05-07 12:45:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-07 14:00:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHome-DevKeynote%402x.png?alt=media&token=d11ff5ac-0bda-46cb-b730-761494207979")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-DevKeynot%402x.png?alt=media&token=069779b3-ddba-421d-86c0-090f7b3f1692")!,
streamURL: URL(string: "https://youtu.be/lyRPyRKHO8M"),
textColor: "#ffffff",
timeVisible: true,
title: "Developer keynote"
)
static let sessionsDayOne = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 7th",
startTime: dateFormatter.date(from: "2019-05-07 14:00:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-07 18:30:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!,
streamURL: URL(string: "https://youtu.be/e0B28zBn9JE"),
textColor: "#ffffff",
timeVisible: true,
title: "Live show (sessions)"
)
static let afterHoursDinner = Moment(
attendeeRequired: false,
cta: .viewMap,
displayDate: "May 7th",
startTime: dateFormatter.date(from: "2019-05-07 18:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-07 22:00:00 -0700")!,
featureID: nil,
featureName: "View Map",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-AfterDark-Text%402x.png?alt=media&token=f863a425-cb3b-4430-a8c6-8364d00c8363")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-AfterDark-Text%402x.png?alt=media&token=f863a425-cb3b-4430-a8c6-8364d00c8363")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: true,
title: "Live show (sessions)"
)
static let dayOneWrap = Moment(
attendeeRequired: false,
cta: nil,
displayDate: "May 7th",
startTime: dateFormatter.date(from: "2019-05-07 22:00:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-08 06:00:00 -0700")!,
featureID: nil,
featureName: nil,
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day1%402x.png?alt=media&token=173d3868-0c25-4da2-8f25-8d814490559e")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day1-dm%402x.png?alt=media&token=abc8e4cc-463b-4685-8c4b-f1b4664f3134")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: false,
title: "Day 1: wrap"
)
static let dayTwoMorning = Moment(
attendeeRequired: false,
cta: nil,
displayDate: "May 8th",
startTime: dateFormatter.date(from: "2019-05-08 06:00:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-08 08:30:00 -0700")!,
featureID: nil,
featureName: nil,
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FAPP-day02%402x.png?alt=media&token=cc5556c0-d125-4619-b3e4-6ca39b5bb09c")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-APP-day02%402x.png?alt=media&token=136d1308-cc70-4bc4-9320-535aa196387e")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: true,
title: "Day 2: morning"
)
static let sessionsDayTwoMorning = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 8th",
startTime: dateFormatter.date(from: "2019-05-08 08:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-08 11:30:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!,
streamURL: URL(string: "https://youtu.be/irpNzosHbPU"),
textColor: "#ffffff",
timeVisible: true,
title: "Live show (sessions)"
)
static let lunchDayTwo = Moment(
attendeeRequired: true,
cta: .viewMap,
displayDate: "May 8th",
startTime: dateFormatter.date(from: "2019-05-08 11:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-08 14:30:00 -0700")!,
featureID: "eats",
featureName: "EATS",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FSchedule-Lunch-2%402X.png?alt=media&token=8e54b7a8-f72f-4803-8d93-ddb3c78694a7")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Schedule-Lunch-2%402X.png?alt=media&token=dba29718-437f-4d38-ae5f-93fed2f7cab2")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: true,
title: "Lunch"
)
static let sessionsDayTwoAfternoon = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 8th",
startTime: dateFormatter.date(from: "2019-05-08 14:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-08 19:30:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!,
streamURL: URL(string: "https://youtu.be/irpNzosHbPU"),
textColor: "#ffffff",
timeVisible: true,
title: "Live show (sessions)"
)
static let concert = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 8th",
startTime: dateFormatter.date(from: "2019-05-08 19:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-08 22:00:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-Concert-Text-v2.png?alt=media&token=cf913585-65b7-4fb7-958c-5e333e6ee85f")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-Concert-Text-v2.png?alt=media&token=cf913585-65b7-4fb7-958c-5e333e6ee85f")!,
streamURL: URL(string: "https://youtu.be/Z9WusLkJ01s"),
textColor: "#ffffff",
timeVisible: true,
title: "Concert"
)
static let dayTwoWrap = Moment(
attendeeRequired: false,
cta: nil,
displayDate: "May 8th",
startTime: dateFormatter.date(from: "2019-05-08 22:00:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-09 06:00:00 -0700")!,
featureID: nil,
featureName: nil,
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day2%402x.png?alt=media&token=37ac81db-b334-4c05-8448-4b1d139d711b")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day2-dm%402x.png?alt=media&token=0a40d99f-39b1-4936-8967-0319039e05cd")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: false,
title: "Day 2: wrap"
)
static let dayThreeMorning = Moment(
attendeeRequired: false,
cta: nil,
displayDate: "May 9th",
startTime: dateFormatter.date(from: "2019-05-09 06:00:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-09 08:30:00 -0700")!,
featureID: nil,
featureName: nil,
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FAPP-day03%402x.png?alt=media&token=2a7e37e3-3138-43a2-acef-ff3ce44664a3")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-APP-day03%402x.png?alt=media&token=5527c547-ac01-40e5-ac12-f99cf5e2e110")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: true,
title: "Day 3: morning"
)
static let sessionsDayThreeMorning = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 9th",
startTime: dateFormatter.date(from: "2019-05-09 08:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-09 11:30:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!,
streamURL: URL(string: "https://youtu.be/WQklcSsYdu4"),
textColor: "#ffffff",
timeVisible: true,
title: "Live show (sessions)"
)
static let lunchDayThree = Moment(
attendeeRequired: true,
cta: .viewMap,
displayDate: "May 9th",
startTime: dateFormatter.date(from: "2019-05-09 11:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-09 14:30:00 -0700")!,
featureID: "eats",
featureName: "EATS",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FSchedule-Lunch-3%402X.png?alt=media&token=e4079280-f497-460c-bb89-51746c4d9e13")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Schedule-Lunch-3%402X.png?alt=media&token=2ac97cb7-2e4c-41fd-bd37-5594251158cc")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: true,
title: "Lunch"
)
static let sessionsDayThreeAfternoon = Moment(
attendeeRequired: false,
cta: .viewLivestream,
displayDate: "May 9th",
startTime: dateFormatter.date(from: "2019-05-09 14:30:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-09 17:00:00 -0700")!,
featureID: nil,
featureName: "Watch Livestream",
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!,
streamURL: URL(string: "https://youtu.be/WQklcSsYdu4"),
textColor: "#ffffff",
timeVisible: true,
title: "Live show (sessions)"
)
static let dayThreeWrap = Moment(
attendeeRequired: false,
cta: nil,
displayDate: "May 9th",
startTime: dateFormatter.date(from: "2019-05-09 17:00:00 -0700")!,
endTime: dateFormatter.date(from: "2019-05-09 22:00:00 -0700")!,
featureID: nil,
featureName: nil,
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day3%402x.png?alt=media&token=9f7c2a81-ebe5-473b-ab05-529093a201e4")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day3-dm%402x.png?alt=media&token=f4d4fdb6-9e13-4e96-bb0e-c6b990ceacf8")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: false,
title: "That’s a wrap…thanks!"
)
static let evergreenBranding = Moment(
attendeeRequired: false,
cta: nil,
displayDate: "May 10th",
startTime: dateFormatter.date(from: "2019-05-09 22:00:00 -0700")!,
endTime: dateFormatter.date(from: "2025-01-01 09:00:00 -0800")!,
featureID: nil,
featureName: nil,
imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHome-Evergreen2%402x.png?alt=media&token=35c71f46-818c-41c1-b58a-94be038221a2")!,
imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-Evergreen2%402x.png?alt=media&token=95022ef8-0fdb-4fb5-8f4a-0acc6ea59825")!,
streamURL: nil,
textColor: "#ffffff",
timeVisible: false,
title: "Evergreen branding"
)
static let allMoments: [Moment] = [
.keynote,
.lunchDayOne,
.developerKeynote,
.sessionsDayOne,
.afterHoursDinner,
.dayOneWrap,
.dayTwoMorning,
.sessionsDayTwoMorning,
.lunchDayTwo,
.sessionsDayTwoAfternoon,
.concert,
.dayTwoWrap,
.dayThreeMorning,
.sessionsDayThreeMorning,
.lunchDayThree,
.sessionsDayThreeAfternoon,
.dayThreeWrap
]
static func currentMoment(for date: Date = Date()) -> Moment? {
for moment in allMoments where moment.startTime <= date && moment.endTime > date {
return moment
}
return nil
}
}
extension Moment: Equatable {}
public func == (lhs: Moment, rhs: Moment) -> Bool {
return lhs.title == rhs.title && lhs.cta == rhs.cta && lhs.startTime == rhs.startTime &&
lhs.endTime == rhs.endTime && lhs.imageURL == rhs.imageURL && lhs.streamURL == rhs.streamURL
}
|
3d4afdbc4ed5c1d40197b6db76429601
| 44.416851 | 202 | 0.696773 | false | false | false | false |
talentsparkio/Pong
|
refs/heads/master
|
Pong/ViewController.swift
|
bsd-3-clause
|
1
|
//
// ViewController.swift
// Pong
//
// Created by Nick Chen on 8/19/15.
// Copyright © 2015 TalentSpark. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollisionBehaviorDelegate {
let DIAMETER = CGFloat(50.0)
let PADDLE_WIDTH = CGFloat(100.0)
let PADDLE_HEIGHT = CGFloat(25.0)
let NUM_BRICKS = 20
var BRICK_SIZE: CGSize {
let size = UIScreen.mainScreen().bounds.size.width / CGFloat(NUM_BRICKS)
return CGSize(width: size, height: size)
}
var orangeBall: UIView!
var paddle: UIView!
var animator: UIDynamicAnimator!
var bricks = [UIView]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
orangeBall = UIView(frame: CGRectMake(0.0, 0.0, DIAMETER, DIAMETER))
orangeBall.center = CGPointMake(UIScreen.mainScreen().bounds.size.width / 2, 300)
orangeBall.backgroundColor = UIColor.orangeColor()
orangeBall.layer.cornerRadius = 25.0;
view.addSubview(orangeBall)
paddle = UIView(frame:CGRectMake(0.0, 0.0, PADDLE_WIDTH, PADDLE_HEIGHT))
paddle.center = CGPointMake(UIScreen.mainScreen().bounds.size.width / 2, UIScreen.mainScreen().bounds.size.height - PADDLE_HEIGHT / 2)
paddle.backgroundColor = UIColor.grayColor()
view.addSubview(paddle)
for var i = 0; i < NUM_BRICKS; i++ {
var frame = CGRect(origin: CGPointZero, size: BRICK_SIZE)
frame.origin.y = 200
frame.origin.x = CGFloat(i) * BRICK_SIZE.width
let dropView = UIView(frame: frame)
dropView.backgroundColor = UIColor.random
bricks.append(dropView)
view.addSubview(dropView)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.initBehaviors()
}
@IBAction func movePaddle(sender: UIPanGestureRecognizer) {
let translationPoint = sender.locationInView(self.view)
paddle.center = CGPointMake(translationPoint.x, paddle.center.y)
animator.updateItemUsingCurrentState(paddle)
}
func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item1: UIDynamicItem, withItem item2: UIDynamicItem, atPoint p: CGPoint) {
// Collision between ball and paddle
if(item1 === orangeBall && item2 === paddle) {
let pushBehavior = UIPushBehavior(items: [orangeBall], mode: .Instantaneous)
pushBehavior.pushDirection = CGVectorMake(0.0, -1.0)
pushBehavior.magnitude = 0.75
// Need to remove the behavior without causing circular reference
pushBehavior.action = { [unowned pushBehavior] in
if(!pushBehavior.active) {
pushBehavior.dynamicAnimator?.removeBehavior(pushBehavior)
}
}
animator.addBehavior(pushBehavior)
}
}
func initBehaviors() {
animator = UIDynamicAnimator(referenceView: self.view)
// Add gravity for ball
let gravityBehavior = UIGravityBehavior(items: [orangeBall])
animator.addBehavior(gravityBehavior)
// Add collision
let collisionBoundsBehavior = UICollisionBehavior(items: [orangeBall, paddle])
collisionBoundsBehavior.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collisionBoundsBehavior)
// Add physical properties for ball
let elasticityBehavior = UIDynamicItemBehavior(items: [orangeBall])
elasticityBehavior.elasticity = 1.0
animator.addBehavior(elasticityBehavior)
// Add physical properties for bricks
let brickBehavior = UIDynamicItemBehavior(items: bricks)
brickBehavior.allowsRotation = false
animator.addBehavior(brickBehavior)
// Add physical properties for paddle
let paddleBehavior = UIDynamicItemBehavior(items: [paddle])
paddleBehavior.density = 100.0
paddleBehavior.allowsRotation = false
animator.addBehavior(paddleBehavior)
// Add collision between ball and bricks (individually so there is no avalanche effect)
for brick in bricks {
let ballAndBrick: [UIDynamicItem] = [brick, orangeBall]
let collisionBallAndBricksBehavior = UICollisionBehavior(items: ballAndBrick)
animator.addBehavior(collisionBallAndBricksBehavior)
}
// Add collision between ball and paddle
let collisionBallAndPaddleBehavior = UICollisionBehavior(items: [orangeBall, paddle])
collisionBallAndPaddleBehavior.collisionDelegate = self
animator.addBehavior(collisionBallAndPaddleBehavior)
}
}
private extension UIColor {
class var random: UIColor {
switch arc4random() % 5 {
case 0: return UIColor.greenColor()
case 1: return UIColor.blueColor()
case 2: return UIColor.orangeColor()
case 3: return UIColor.redColor()
case 4: return UIColor.purpleColor()
default: return UIColor.blackColor()
}
}
}
|
6028ce219c99a885bb1c7467322746f1
| 36.230769 | 152 | 0.647446 | false | false | false | false |
objecthub/swift-lispkit
|
refs/heads/master
|
Sources/LispKit/Runtime/Features.swift
|
apache-2.0
|
1
|
//
// Feature.swift
// LispKit
//
// Created by Matthias Zenger on 15/10/2017.
// Copyright © 2017 ObjectHub. 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
public enum Feature: String {
case lispkit = "lispkit"
case r7rs = "r7rs"
case ratios = "ratios"
case complex = "complex"
case syntaxRules = "syntax-rules"
case littleEndian = "little-endian"
case bigEndian = "big-endian"
case dynamicLoading = "dynamic-loading"
case modules = "modules"
case threads = "threads"
case bit32 = "32bit"
case bit64 = "64bit"
case macos = "macos"
case macosx = "macosx"
case ios = "ios"
case linux = "linux"
case i386 = "i386"
case x8664 = "x86-64"
case arm64 = "arm64"
case arm = "arm"
public static let supported: Set<String> = {
var set = Set<String>()
set.insert(Feature.lispkit.rawValue)
set.insert(Feature.r7rs.rawValue)
set.insert(Feature.ratios.rawValue)
set.insert(Feature.complex.rawValue)
set.insert(Feature.syntaxRules.rawValue)
set.insert(Feature.dynamicLoading.rawValue)
set.insert(Feature.modules.rawValue)
set.insert(Feature.threads.rawValue)
set.insert(CFByteOrderGetCurrent() == 1 ? Feature.littleEndian.rawValue
: Feature.bigEndian.rawValue)
#if arch(i386)
set.insert(Feature.i386.rawValue)
set.insert(Feature.bit32.rawValue)
#elseif arch(x86_64)
set.insert(Feature.x8664.rawValue)
set.insert(Feature.bit64.rawValue)
#elseif arch(arm)
set.insert(Feature.arm.rawValue)
set.insert(Feature.bit32.rawValue)
#elseif arch(arm64)
set.insert(Feature.arm64.rawValue)
set.insert(Feature.bit64.rawValue)
#endif
#if os(macOS)
set.insert(Feature.macos.rawValue)
set.insert(Feature.macosx.rawValue)
#elseif os(iOS)
set.insert(Feature.ios.rawValue)
#elseif os(Linux)
set.insert(Feature.linux.rawValue)
#endif
return set
}()
}
|
35752fb65987e1b04142e02a5d679e22
| 30.575 | 76 | 0.680918 | false | false | false | false |
wj2061/ios7ptl-swift3.0
|
refs/heads/master
|
ch23-AdvGCD/DispatchDownload/DispatchDownload/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// DispatchDownload
//
// Created by WJ on 15/12/1.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
let kHeaderDelimiterString = "\r\n\r\n"
class ViewController: UIViewController {
lazy var headerDelimiter = kHeaderDelimiterString.data(using: String.Encoding.utf8)!
func htons(_ value: CUnsignedShort) -> CUnsignedShort {
return (value << 8) + (value >> 8);
}
func connectToHostName(_ hostName:String,port:Int) -> Int32{
let s = socket(PF_INET,SOCK_STREAM,0)
guard s >= 0 else { assert(false , "socket failed:\(errno)") }
var sa = sockaddr_in()
sa.sin_family = UInt8( AF_INET )
sa.sin_port = htons(CUnsignedShort(port))
let he = gethostbyname(hostName)
if he == nil{
assert(false , "gethostbyname failure:\(errno)")
}
bcopy(he?.pointee.h_addr_list[0], &sa.sin_addr,Int( (he?.pointee.h_length)!) )
let cn = withUnsafePointer(to: &sa) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(s, UnsafePointer($0), socklen_t(MemoryLayout.size(ofValue: sa)))
}
}
if cn < 0{
assert(false , "cn<0")
}
return s
}
func outputFilePathForPath(_ path:String)->String{
return (NSTemporaryDirectory() as NSString ).appendingPathComponent((path as NSString).lastPathComponent)
}
func writeToChannel(_ channel:DispatchIO,writeData:DispatchData,queue:DispatchQueue){
channel.write(offset: 0, data: writeData, queue: queue) { (done , remainingData, error) -> Void in
assert(error == 0, "File write error:\(error )")
var unwrittenDataLength = 0
if remainingData != nil{
unwrittenDataLength = (remainingData?.count)!
}
print("Wrote \(writeData.count - unwrittenDataLength) bytes")
}
}
func handleDoneWithChannels(_ channels:[DispatchIO]){
print("Done Downloading")
for channel in channels{
channel.close(flags: DispatchIO.CloseFlags(rawValue: 0))
}
}
func findHeaderInData(_ newData:DispatchData,
previousData:inout DispatchData,
writeChannel:DispatchIO,
queue:DispatchQueue)->DispatchData?{
let mappedData = __dispatch_data_create_concat(previousData as __DispatchData, newData as __DispatchData)
var headerData :__DispatchData?
var bodyData :__DispatchData?
__dispatch_data_apply(mappedData) { (region, offset, buffer, size) -> Bool in
var bf = buffer
let search = NSData(bytesNoCopy: &bf, length: size, freeWhenDone: false)
let r = search.range(of: self.headerDelimiter, options: [], in: NSMakeRange(0, search.length))
if r.location != NSNotFound{
headerData = __dispatch_data_create_subrange(region, 0, r.location)
let body_offset = NSMaxRange(r)
let body_size = size - body_offset
bodyData = __dispatch_data_create_subrange(region, body_offset, body_size)
}
return false
}
if bodyData != nil{
writeToChannel(writeChannel, writeData: bodyData! as DispatchData, queue: queue)
}
return headerData! as DispatchData
}
func printHeader(_ headerData:DispatchData){
print("\nHeader:\n\n")
__dispatch_data_apply(headerData as __DispatchData) { (region, offset, buffer, size) -> Bool in
fwrite(buffer, size, 1, stdout)
return true
}
print("\n\n")
}
func readFromChannel(_ readChannel:DispatchIO,writeChannel:DispatchIO,queue:DispatchQueue){
var previousData = DispatchData.empty
var headerData : DispatchData?
readChannel.read(offset: 0,length: Int.max, queue: queue) { (serverReadDone, serverReadData, serverReadError) -> Void in
assert(serverReadError == 0, "Server read error:\(serverReadError)")
if serverReadData != nil{
self.handleDoneWithChannels([writeChannel,readChannel])
}else{
if headerData == nil{
headerData = self.findHeaderInData(serverReadData!, previousData: &previousData, writeChannel: writeChannel, queue: queue)
if headerData != nil{
self.printHeader(headerData!)
}
}
else{
self.writeToChannel(writeChannel, writeData: serverReadData!, queue: queue)
}
}
}
}
func requestDataForHostName(_ hostName:String,path:String)->DispatchData{
let getString = "GET \(path) HTTP/1.1\r\nHost: \(hostName)\r\n\r\n"
print("Request:\n\(getString)" )
let getData = getString.data(using: String.Encoding.utf8)
return DispatchData(referencing:getData!)
}
func HTTPDownloadContentsFromHostName(_ hostName:String,port:Int,path:String){
let queue = DispatchQueue.main
let socket = connectToHostName(hostName, port: port)
let serverChannel = DispatchIO(__type: DispatchIO.StreamType.stream.rawValue, fd: socket, queue: queue) { (error) in
assert(error == 0, "Failed socket:\(error )")
print("Closing connection")
close(socket)
}
let requestData = requestDataForHostName(hostName, path: path)
let writePath = outputFilePathForPath(path)
print("Writing to \(writePath)")
let fileChannel = DispatchIO(__type: DispatchIO.StreamType.stream.rawValue, path: writePath, oflag: O_WRONLY|O_CREAT|O_TRUNC, mode: S_IRWXU, queue: queue) {(error) in
}
serverChannel.write(offset: 0, data: requestData, queue: queue) { (serverWriteDone, serverWriteData, error ) -> Void in
assert(error == 0, "Failed socket:\(error )")
if serverWriteDone{
self.readFromChannel(serverChannel, writeChannel: fileChannel, queue: queue)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
HTTPDownloadContentsFromHostName("upload.wikimedia.org",
port: 80,
path: "/wikipedia/commons/9/97/The_Earth_seen_from_Apollo_17.jpg")
}
}
extension DispatchData {
init(referencing data: Data) {
guard !data.isEmpty else {
self = .empty
return
}
// will perform a copy if needed
let nsData = data as NSData
if let dispatchData = ((nsData as AnyObject) as? DispatchData) {
self = dispatchData
} else {
self = .empty
nsData.enumerateBytes { (bytes, byteRange, _) in
let innerData = Unmanaged.passRetained(nsData)
let buffer = UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: byteRange.length)
let chunk = DispatchData(bytesNoCopy: buffer, deallocator: .custom(nil, innerData.release))
append(chunk)
}
}
}
}
|
51057c1c121e04004c59721925f8b56c
| 37.096939 | 174 | 0.577474 | false | false | false | false |
Contron/Dove
|
refs/heads/master
|
Dove/Dove.swift
|
mit
|
1
|
//
// Dove.swift
// Dove
//
// Created by Connor Haigh on 03/06/2016.
// Copyright © 2016 Connor Haigh. All rights reserved.
//
import Foundation
public typealias ActionBlock = () -> ()
public typealias ResultBlock = (Bool) -> ()
public typealias ProgressBlock = () -> Double
public let animationConstant = 0.3
public let shorterAnimationConstant = animationConstant / 2
public let longerAnimationConstant = animationConstant * 2
public let springDamping = CGFloat(0.5)
public let springInitialVelocity = CGFloat(0.1)
|
d1b4d97fb8a512395c047b935c8b100e
| 25.3 | 59 | 0.739544 | false | false | false | false |
Cellane/iWeb
|
refs/heads/master
|
Sources/App/Controllers/Web/Admin/AdminPostsController.swift
|
mit
|
1
|
import Vapor
import Paginator
extension Controllers.Web {
final class AdminPostsController {
private let droplet: Droplet
private let context = AdminContext()
init(droplet: Droplet) {
self.droplet = droplet
}
func addRoutes() {
let posts = droplet.grouped("admin", "posts")
let adminOrEditorAuthorized = posts.grouped(SessionRolesMiddleware(User.self, roles: [Role.admin, Role.editor]))
adminOrEditorAuthorized.get(handler: showPosts)
adminOrEditorAuthorized.get("new", handler: showNewPost)
adminOrEditorAuthorized.post("new", handler: createPost)
adminOrEditorAuthorized.get(Post.parameter, "edit", handler: showEditPost)
adminOrEditorAuthorized.post(Post.parameter, "edit", handler: editPost)
adminOrEditorAuthorized.get(Post.parameter, "delete", handler: deletePost)
adminOrEditorAuthorized.get(String.parameter, "restore", handler: restorePost)
}
func showPosts(req: Request) throws -> ResponseRepresentable {
let posts = try Post
.makeQuery()
.withSoftDeleted()
.sort(Post.createdAtKey, .descending)
.paginator(50, request: req)
return try droplet.view.makeDefault("admin/posts/list", for: req, [
"posts": posts.makeNode(in: context)
])
}
func showNewPost(req: Request) throws -> ResponseRepresentable {
return try droplet.view.makeDefault("admin/posts/edit", for: req)
}
func createPost(req: Request) throws -> ResponseRepresentable {
do {
let post = try req.post()
try post.save()
return Response(redirect: "/admin/posts")
.flash(.success, "Post created.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
func showEditPost(req: Request) throws -> ResponseRepresentable {
let post = try req.parameters.next(Post.self)
return try droplet.view.makeDefault("admin/posts/edit", for: req, [
"post": post
])
}
func editPost(req: Request) throws -> ResponseRepresentable {
do {
let post = try req.parameters.next(Post.self)
try post.update(for: req)
try post.save()
return Response(redirect: "/admin/posts")
.flash(.success, "Post edited.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
func deletePost(req: Request) throws -> ResponseRepresentable {
do {
let post = try req.parameters.next(Post.self)
try post.delete()
return Response(redirect: "/admin/posts")
.flash(.success, "Post deleted.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
func restorePost(req: Request) throws -> ResponseRepresentable {
do {
let postId = try req.parameters.next(String.self)
let post = try Post.withSoftDeleted().find(postId)!
try post.restore()
return Response(redirect: "/admin/posts")
.flash(.success, "Post restored.")
} catch {
return Response(redirect: "/admin/posts")
.flash(.error, "Unexpected error occurred.")
}
}
}
}
|
e8905597be04cef701549b30aebaeb41
| 27.37037 | 115 | 0.686031 | false | false | false | false |
HabitRPG/habitrpg-ios
|
refs/heads/develop
|
HabitRPG/Utilities/PurchaseHandler.swift
|
gpl-3.0
|
1
|
//
// PurchaseHandler.swift
// Habitica
//
// Created by Phillip Thelen on 20.01.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import SwiftyStoreKit
import StoreKit
import Keys
import Shared
class PurchaseHandler: NSObject, SKPaymentTransactionObserver {
@objc static let shared = PurchaseHandler()
static let IAPIdentifiers = ["com.habitrpg.ios.Habitica.4gems", "com.habitrpg.ios.Habitica.21gems",
"com.habitrpg.ios.Habitica.42gems", "com.habitrpg.ios.Habitica.84gems"
]
static let subscriptionIdentifiers = ["subscription1month", "com.habitrpg.ios.habitica.subscription.3month",
"com.habitrpg.ios.habitica.subscription.6month", "com.habitrpg.ios.habitica.subscription.12month"
]
static let noRenewSubscriptionIdentifiers = ["com.habitrpg.ios.habitica.norenew_subscription.1month", "com.habitrpg.ios.habitica.norenew_subscription.3month",
"com.habitrpg.ios.habitica.norenew_subscription.6month", "com.habitrpg.ios.habitica.norenew_subscription.12month"
]
private let itunesSharedSecret = HabiticaKeys().itunesSharedSecret
private let appleValidator: AppleReceiptValidator
private let userRepository = UserRepository()
var pendingGifts = [String: String]()
private var hasCompletionHandler = false
override private init() {
#if DEBUG
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#else
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#endif
}
@objc
func completionHandler() {
if !SKPaymentQueue.canMakePayments() {
return
}
if hasCompletionHandler {
return
}
hasCompletionHandler = true
//Workaround for SwiftyStoreKit.completeTransactions not correctly returning consumable IAPs
SKPaymentQueue.default().add(self)
SwiftyStoreKit.completeTransactions(atomically: false) { _ in
}
SwiftyStoreKit.restorePurchases(atomically: false) { results in
if results.restoreFailedPurchases.isEmpty == false {
print("Restore Failed: \(results.restoreFailedPurchases)")
} else if results.restoredPurchases.isEmpty == false {
for purchase in results.restoredPurchases {
// fetch content from your server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
print("Restore Success: \(results.restoredPurchases)")
} else {
print("Nothing to Restore")
}
}
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
if transactions.isEmpty == false {
for product in transactions {
RemoteLogger.shared.log(format: "Purchase: %@", arguments: getVaList([product.payment.productIdentifier]))
}
}
SwiftyStoreKit.fetchReceipt(forceRefresh: false) { result in
switch result {
case .success(let receiptData):
for transaction in transactions {
self.handleUnfinished(transaction: transaction, receiptData: receiptData)
}
case .error(let error):
RemoteLogger.shared.record(error: error)
}
}
}
func handleUnfinished(transaction: SKPaymentTransaction, receiptData: Data) {
let productIdentifier = transaction.payment.productIdentifier
if transaction.transactionState == .purchased || transaction.transactionState == .restored {
if self.isInAppPurchase(productIdentifier) {
self.activatePurchase(productIdentifier, receipt: receiptData) { status in
if status {
SwiftyStoreKit.finishTransaction(transaction)
}
}
} else if self.isSubscription(productIdentifier) {
self.userRepository.getUser().take(first: 1).on(value: {[weak self] user in
if !user.isSubscribed || user.purchased?.subscriptionPlan?.dateCreated == nil {
self?.applySubscription(transaction: transaction)
}
}).start()
} else if self.isNoRenewSubscription(productIdentifier) {
self.activateNoRenewSubscription(productIdentifier, receipt: receiptData, recipientID: self.pendingGifts[productIdentifier]) { status in
if status {
self.pendingGifts.removeValue(forKey: productIdentifier)
SwiftyStoreKit.finishTransaction(transaction)
}
}
}
} else if transaction.transactionState == .failed {
SwiftyStoreKit.finishTransaction(transaction)
}
}
func purchaseGems(_ identifier: String, applicationUsername: String, completion: @escaping (Bool) -> Void) {
SwiftyStoreKit.purchaseProduct(identifier, quantity: 1, atomically: false, applicationUsername: applicationUsername) { (result) in
switch result {
case .success(let product):
self.verifyPurchase(product)
completion(true)
case .error(let error):
RemoteLogger.shared.record(error: error)
completion(false)
}
}
}
func giftGems(_ identifier: String, applicationUsername: String, recipientID: String, completion: @escaping (Bool) -> Void) {
pendingGifts[identifier] = recipientID
SwiftyStoreKit.purchaseProduct(identifier, quantity: 1, atomically: false, applicationUsername: applicationUsername) { (result) in
switch result {
case .success(let product):
self.verifyPurchase(product)
completion(true)
case .error(let error):
RemoteLogger.shared.record(error: error)
completion(false)
}
}
}
func verifyPurchase(_ product: PurchaseDetails) {
SwiftyStoreKit.fetchReceipt(forceRefresh: false) { result in
switch result {
case .success(let receiptData):
// Verify the purchase of a Subscription
self.activatePurchase(product.productId, receipt: receiptData) { status in
if status {
if product.needsFinishTransaction {
SwiftyStoreKit.finishTransaction(product.transaction)
}
}
}
case .error(let error):
RemoteLogger.shared.record(error: error)
print("Receipt verification failed: \(error)")
}
}
}
func activatePurchase(_ identifier: String, receipt: Data, completion: @escaping (Bool) -> Void) {
var recipientID: String? = nil
if let id = pendingGifts[identifier] {
recipientID = id
}
userRepository.purchaseGems(receipt: ["receipt": receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))], recipient: recipientID).observeValues {[weak self] (result) in
if result != nil {
if recipientID != nil {
self?.pendingGifts.removeValue(forKey: identifier)
}
completion(true)
} else {
completion(false)
}
}
}
func activateNoRenewSubscription(_ identifier: String, receipt: Data, recipientID: String?, completion: @escaping (Bool) -> Void) {
pendingGifts[identifier] = recipientID
if (recipientID == nil) {
completion(false)
return
}
userRepository.purchaseNoRenewSubscription(identifier: identifier,
receipt: ["receipt": receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))],
recipient: recipientID).observeValues {[weak self] (result) in
if result != nil {
self?.pendingGifts.removeValue(forKey: identifier)
completion(true)
} else {
completion(false)
}
}
}
func isInAppPurchase(_ identifier: String) -> Bool {
return PurchaseHandler.IAPIdentifiers.contains(identifier)
}
func isValidPurchase(_ identifier: String, receipt: ReceiptInfo) -> Bool {
if !isInAppPurchase(identifier) {
return false
}
let purchaseResult = SwiftyStoreKit.verifyPurchase(productId: identifier, inReceipt: receipt)
switch purchaseResult {
case .purchased:
return true
case .notPurchased:
return false
}
}
func activateSubscription(_ identifier: String, receipt: ReceiptInfo, completion: @escaping (Bool) -> Void) {
if let lastReceipt = receipt["latest_receipt"] as? String {
userRepository.subscribe(sku: identifier, receipt: lastReceipt).observeResult { (result) in
switch result {
case .success:
completion(true)
case .failure:
completion(false)
}
}
}
}
func isSubscription(_ identifier: String) -> Bool {
return PurchaseHandler.subscriptionIdentifiers.contains(identifier)
}
func isNoRenewSubscription(_ identifier: String) -> Bool {
return PurchaseHandler.noRenewSubscriptionIdentifiers.contains(identifier)
}
func isValidSubscription(_ identifier: String, receipt: ReceiptInfo) -> Bool {
if !isSubscription(identifier) {
return false
}
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .autoRenewable,
productId: identifier,
inReceipt: receipt,
validUntil: Date()
)
switch purchaseResult {
case .purchased:
return true
case .expired:
return false
case .notPurchased:
return false
}
}
private func applySubscription(transaction: SKPaymentTransaction) {
SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: {[weak self] (verificationResult) in
switch verificationResult {
case .success(let receipt):
if self?.isValidSubscription(transaction.payment.productIdentifier, receipt: receipt) == true {
self?.activateSubscription(transaction.payment.productIdentifier, receipt: receipt) { status in
if status {
SwiftyStoreKit.finishTransaction(transaction)
}
}
} else {
SwiftyStoreKit.finishTransaction(transaction)
}
case .error(let error):
RemoteLogger.shared.record(error: error)
}
})
}
}
|
8bf2fd90c00d5bfa770a9f818fd9161f
| 40.405797 | 201 | 0.591617 | false | false | false | false |
cSquirrel/food-cam
|
refs/heads/develop
|
FoodCam/FoodCam/ExistingEntriesViewController.swift
|
apache-2.0
|
1
|
//
// ExistingEntriesViewController.swift
// FoodCam
//
// Created by Marcin Maciukiewicz on 03/11/2016.
// Copyright © 2016 Marcin Maciukiewicz. All rights reserved.
//
import UIKit
class ExistingEntriesViewController: UITableViewController {
fileprivate var dailyEntries:[DailyEntries]? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
doRefresh(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doRefresh(_ sender: Any) {
dailyEntries = DataSource().findAllFoodEntries()
tableView.reloadData()
}
@IBAction func doEditEntry(_ sender: Any) {
print("doEditEntry")
}
@IBAction func doSwipe(_ sender: Any) {
print("doSwipe")
}
/*
// 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.
}
*/
}
// MARK: - UITableViewDelegate
extension ExistingEntriesViewController {
// public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// guard let day = dailyEntries?[indexPath.section] else {
// return
// }
//
//// let entry = day.entries[indexPath.row]
//// if let detailsVC = self.storyboard?.instantiateViewController(withIdentifier: "addEntry") as? NewEntryViewController {
//// detailsVC.editMode(entry: entry)
//// navigationController?.pushViewController(detailsVC, animated: true)
//// }
// }
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
guard let day = dailyEntries?[indexPath.section] else {
return
}
let entry = day.entries[indexPath.row]
if let detailsVC = self.storyboard?.instantiateViewController(withIdentifier: "addEntry") as? NewEntryViewController {
detailsVC.editMode(entry: entry)
navigationController?.pushViewController(detailsVC, animated: true)
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true;
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let day = dailyEntries?[indexPath.section] {
let entry = day.entries[indexPath.row]
do {
try DataSource().delete(foodEntry: entry)
dailyEntries = DataSource().findAllFoodEntries()
tableView.deleteRows(at: [indexPath], with: .automatic)
} catch let error as NSError {
print(error)
}
}
}
}
}
// MARK: - UITableViewDataSource
extension ExistingEntriesViewController {
public override func numberOfSections(in tableView: UITableView) -> Int {
guard let e = dailyEntries else {
return 1
}
return e.count
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let de = dailyEntries else {
return 0
}
let e = de[section].entries
return e.count
}
public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let e = dailyEntries else {
return nil
}
let result:String?
let date = e[section].date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
result = dateFormatter.string(from: date)
return result
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = "EntryDetails"
let result = tableView.dequeueReusableCell(withIdentifier: cellID)
// if (result == nil) {
// result = UITableViewCell(style: .default, reuseIdentifier: cellID)
// }
if let day = dailyEntries?[indexPath.section] {
let entry = day.entries[indexPath.row]
result?.textLabel?.text = "\(entry.createdAt)"
}
return result!
}
}
|
9ff451586c5589a39405d406005bd47e
| 29.968553 | 136 | 0.609058 | false | false | false | false |
gerardogrisolini/iWebretail
|
refs/heads/master
|
iWebretail/MovementController.swift
|
apache-2.0
|
1
|
//
// MovementController.swift
// iWebretail
//
// Created by Gerardo Grisolini on 12/04/17.
// Copyright © 2017 Gerardo Grisolini. All rights reserved.
//
import UIKit
class MovementController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var amountLabel: UILabel!
var label: UILabel!
var movementArticles: [MovementArticle]
private var repository: MovementArticleProtocol
required init?(coder aDecoder: NSCoder) {
self.movementArticles = []
repository = IoCContainer.shared.resolve() as MovementArticleProtocol
super.init(coder: aDecoder)
}
override func viewDidLoad()
{
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
makeBar()
}
func makeBar() {
// badge label
label = UILabel(frame: CGRect(x: 8, y: -4, width: 29, height: 20))
label.layer.borderColor = UIColor.clear.cgColor
label.layer.borderWidth = 2
label.layer.cornerRadius = label.bounds.size.height / 2
label.textAlignment = .center
label.layer.masksToBounds = true
label.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight(rawValue: 600))
label.textColor = .darkText
if Synchronizer.shared.movement.completed {
label.backgroundColor = UIColor(name: "whitesmoke")
} else {
label.backgroundColor = UIColor(name: "lightgreen")
}
// button
let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 29, height: 29))
let basket = UIImage(named: "basket")?.withRenderingMode(.alwaysTemplate)
rightButton.setImage(basket, for: .normal)
rightButton.tintColor = UINavigationBar.appearance().tintColor
rightButton.addTarget(self, action: #selector(rightButtonTouched), for: .touchUpInside)
rightButton.addSubview(label)
// Bar button item
self.tabBarController?.tabBar.tintColor = UINavigationBar.appearance().tintColor
self.tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
}
@objc func rightButtonTouched(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "RegisterView") as! RegisterController
self.navigationController!.pushViewController(vc, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
self.movementArticles = try! repository.getAll(id: Synchronizer.shared.movement.movementId)
self.updateAmount()
tableView.reloadData()
}
@IBAction func stepperValueChanged(_ sender: UIStepper) {
let point = sender.convert(CGPoint(x: 0, y: 0), to: tableView)
let indexPath = self.tableView.indexPathForRow(at: point)!
let item = movementArticles[indexPath.row]
let cell = tableView.cellForRow(at: indexPath) as! ArticleCell
item.movementArticleQuantity = sender.value
cell.textQuantity.text = String(sender.value)
cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice)
try! repository.update(id: item.movementArticleId, item: item)
self.updateAmount()
}
@IBAction func textValueChanged(_ sender: UITextField) {
let point = sender.convert(CGPoint(x: 0, y: 0), to: tableView)
let indexPath = self.tableView.indexPathForRow(at: point)!
let item = movementArticles[indexPath.row]
let cell = tableView.cellForRow(at: indexPath) as! ArticleCell
if sender == cell.textQuantity {
item.movementArticleQuantity = Double(sender.text!)!
cell.stepperQuantity.value = item.movementArticleQuantity
} else {
item.movementArticlePrice = Double(sender.text!)!
}
cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice)
try! repository.update(id: item.movementArticleId, item: item)
self.updateAmount()
}
func updateAmount() {
let amount = movementArticles
.map { $0.movementArticleQuantity * $0.movementArticlePrice as Double }
.reduce (0, +)
amountLabel.text = amount.formatCurrency()
let quantity = movementArticles
.map { $0.movementArticleQuantity }
.reduce (0, +)
label.text = quantity.description
if Synchronizer.shared.movement.movementAmount != amount {
try! repository.updateAmount(item: Synchronizer.shared.movement, amount: amount)
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movementArticles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell", for: indexPath) as! ArticleCell
let index = (indexPath as NSIndexPath).row
let item = movementArticles[index]
cell.labelBarcode.text = item.movementArticleBarcode
cell.labelName.text = item.movementProduct
cell.textPrice.text = String(item.movementArticlePrice)
cell.textQuantity.text = String(item.movementArticleQuantity)
cell.textAmount.text = String(item.movementArticleQuantity * item.movementArticlePrice)
cell.stepperQuantity.value = item.movementArticleQuantity
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return !Synchronizer.shared.movement.completed
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
do {
try repository.delete(id: self.movementArticles[indexPath.row].movementArticleId)
self.movementArticles.remove(at: indexPath.row)
self.updateAmount()
tableView.deleteRows(at: [indexPath], with: .fade)
} catch {
self.navigationController?.alert(title: "Error".locale, message: "\(error)")
}
}
}
}
|
6abad016cc39a1c41d9dbcebe7f8ee05
| 37.970588 | 127 | 0.653887 | false | false | false | false |
mikewxk/DYLiveDemo_swift
|
refs/heads/master
|
DYLiveDemo/DYLiveDemo/Classes/Tools/Common.swift
|
unlicense
|
1
|
//
// Common.swift
// DYLiveDemo
//
// Created by xiaokui wu on 12/16/16.
// Copyright © 2016 wxk. All rights reserved.
//
import UIKit
let kStatusBarHeight: CGFloat = 20
let kNavigationBarHeight: CGFloat = 44
let kTabBarHeight: CGFloat = 44
let kScreenWidth = UIScreen.mainScreen().bounds.width
let kScreenHeight = UIScreen.mainScreen().bounds.height
|
2ea9c7b379167d396380e3b166628520
| 19.055556 | 55 | 0.736842 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
refs/heads/master
|
GoDToolCL/main.swift
|
gpl-2.0
|
1
|
//
// main.swift
// XGCommandLineTools
//
// Created by StarsMmd on 13/11/2015.
// Copyright © 2015 StarsMmd. All rights reserved.
//
//
import Foundation
ToolProcess.loadISO(exitOnFailure: true)
var countDownDate: Date?
var posterFile: XGFiles?
var musicScriptFile: XGFiles?
var iso: XGFiles?
var argsAreInvalid = false
let args = CommandLine.arguments
for i in 0 ..< args.count {
guard i < args.count - 1 else { continue }
let arg = args[i]
let next = args[i + 1]
if arg == "--launch-dpp-date" {
countDownDate = Date.fromString(next)
if countDownDate == nil {
let secondsToDecember: Double = 31_104_000
print("Invalid arg for \(arg) \(next)\nDate must be of format:", Date(timeIntervalSince1970: secondsToDecember).referenceString())
argsAreInvalid = true
}
} else if arg == "--launch-dpp-secs",
let seconds = next.integerValue {
countDownDate = Date(timeIntervalSinceNow: Double(seconds))
} else if arg == "-i" || arg == "--iso" {
let file = XGFiles.path(next)
if file.fileType == .iso {
iso = file
}
if !file.exists {
print("Invalid arg for \(arg).\nFile doesn't exist:", file.path)
argsAreInvalid = true
}
} else if arg == "-s" || arg == "--silent-logs" {
silentLogs = true
}
}
if argsAreInvalid {
ToolProcess.terminate()
}
if let isoFile = iso {
XGISO.loadISO(file: isoFile)
}
DiscordPlaysOrre().launch()
|
cdea0a9034e1f2c29bd87de933eb3c76
| 22.724138 | 133 | 0.672965 | false | false | false | false |
TwoRingSoft/shared-utils
|
refs/heads/master
|
Examples/Pippin/Pods/Closures/Xcode/Closures/Source/KVO.swift
|
mit
|
2
|
/**
The MIT License (MIT)
Copyright (c) 2017 Vincent Hesener
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
extension NSObject {
public var selfDeinits: (_KeyValueCodingAndObserving) -> Bool {
return { [weak self] _ in
return self == nil
}
}
}
extension _KeyValueCodingAndObserving {
/**
This convenience method puts only a tiny bit of polish on
Swift's latest closure-based KVO implementation. Although
there aren't many obvious differences between this
method and the one in `Foundation`, there are a few helpers, which
are describe below.
First, it passes a remove condition, `until`, which is simpy a closure
that gets called to determine whether to remove the observation
closure. Returning true will remove the observer, otherwise, the
observing will continue. `Foundation`'s method
automatically removes observation when the `NSKeyValueObservation`
is released, but this requires you to save it somewhere in your
view controller as a property, thereby cluttering up your view
controller with plumbing-only members.
Second, this method attempts to slightly improve the clutter. You
do not have to save the observer. `@discardableResult` allows you
to disregard the returned object entirely.
Finally, a typical pattern is to remove observers when deinit is
called on the object that owns the observed object.
For instance, if you are observing a model object property on your
view controller, you will probably want to stop observing when the
view controller gets released from memory. Because this is a
common pattern, there's a convenient var available on all subclasses
of NSObject named `selfDeinits`. Simply pass this as a parameter
into the `until` paramaeter, and the observation will be removed
when `self` is deallocated.
* * * *
#### An example of calling this method:
```swift
<#someObject#>.observe(\.<#some.key.path#>, until: selfDeinits) { obj,change in
<#do something#>
}
```
* parameter keyPath: The keyPath you wish to observe on this object
* parameter options: The observing options
* parameter until: The closure called when this handler should stop
observing. Return true if you want to forcefully stop observing.
* parameter changeHandler: The callback that will be called when
the keyPath change has occurred.
* returns: The observer object needed to remove observation
*/
@discardableResult
public func observe<Value>(
_ keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [],
until removeCondition: @escaping (Self) -> Bool,
changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void)
-> NSKeyValueObservation {
var observer: NSKeyValueObservation?
observer = self.observe(keyPath, options: options) { obj, change in
guard !removeCondition(obj) else {
observer?.invalidate()
observer = nil
return
}
changeHandler(obj, change)
}
return observer!
}
}
|
f1f8bcbe72a4072edc03870503283505
| 43.505155 | 98 | 0.697475 | false | false | false | false |
WIND-FIRE-WHEEL/WFWCUSTOMIM
|
refs/heads/master
|
IMDemo/IMDemo/Profile/Macros.swift
|
mit
|
1
|
//
// Macros.swift
// IMDemo
//
// Created by 徐往 on 2017/7/25.
// Copyright © 2017年 徐往. All rights reserved.
//
import Foundation
let IM = PublicTools()
class PublicTools:NSObject {
let screenSize:CGSize = UIScreen.main.bounds.size
let screenNavHeight:CGFloat = 64.0
let screenTabHeight:CGFloat = 49.0
let defaultKeyboardHeight:CGFloat = 50.0
}
enum SendMessage :NSInteger{
case otherSend = 0
case mineSend = 1
}
extension UIView {
var xw_width:CGFloat {
get {
return self.frame.size.width
}
}
var xw_height:CGFloat {
get {
return self.frame.size.height
}
}
var xw_y:CGFloat {
get {
return self.frame.origin.y
}
}
var xw_x:CGFloat {
get {
return self.frame.origin.x
}
}
}
|
1de974da486983b0732031f1eeee84f1
| 15.823529 | 53 | 0.56993 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
refs/heads/master
|
TranslationEditor/SquishableStackView.swift
|
mit
|
1
|
//
// SquishableStackView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 15.6.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
// These stack views can be squished a little when necessary
class SquishableStackView: UIStackView, Squishable
{
// ATTRIBUTES --------------
@IBInspectable var minSpacing: CGFloat = 0
private var originalSpacing: CGFloat?
// IMPLEMENTED METHODS ------
func setSquish(_ isSquished: Bool, along axis: UILayoutConstraintAxis)
{
// Can only be squished along it's own axis
if axis == self.axis
{
if isSquished
{
if originalSpacing == nil
{
originalSpacing = spacing
}
spacing = minSpacing
}
else if let originalSpacing = originalSpacing
{
spacing = originalSpacing
self.originalSpacing = nil
}
}
}
}
|
3adb6828ec8cdd41eb0b5fb9cb90d22d
| 18.465116 | 71 | 0.670251 | false | false | false | false |
AlexRamey/mbird-iOS
|
refs/heads/master
|
Pods/Nuke/Sources/Cache.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
/// In-memory image cache.
///
/// The implementation must be thread safe.
public protocol Caching: class {
/// Accesses the image associated with the given key.
subscript(key: AnyHashable) -> Image? { get set }
// unfortunately there is a lot of extra work happening here because key
// types are not statically defined, might be worth rethinking cache
}
public extension Caching {
/// Accesses the image associated with the given request.
public subscript(request: Request) -> Image? {
get { return self[request.cacheKey] }
set { self[request.cacheKey] = newValue }
}
}
/// Memory cache with LRU cleanup policy (least recently used are removed first).
///
/// The elements stored in cache are automatically discarded if either *cost* or
/// *count* limit is reached. The default cost limit represents a number of bytes
/// and is calculated based on the amount of physical memory available on the
/// device. The default count limit is set to `Int.max`.
///
/// `Cache` automatically removes all stored elements when it received a
/// memory warning. It also automatically removes *most* of cached elements
/// when the app enters background.
public final class Cache: Caching {
// We don't use `NSCache` because it's not LRU
private var map = [AnyHashable: LinkedList<CachedImage>.Node]()
private let list = LinkedList<CachedImage>()
private let lock = NSLock()
/// The maximum total cost that the cache can hold.
public var costLimit: Int {
didSet { lock.sync(_trim) }
}
/// The maximum number of items that the cache can hold.
public var countLimit: Int {
didSet { lock.sync(_trim) }
}
/// The total cost of items in the cache.
public private(set) var totalCost = 0
/// The total number of items in the cache.
public var totalCount: Int {
return map.count
}
/// Shared `Cache` instance.
public static let shared = Cache()
/// Initializes `Cache`.
/// - parameter costLimit: Default value representes a number of bytes and is
/// calculated based on the amount of the phisical memory available on the device.
/// - parameter countLimit: `Int.max` by default.
public init(costLimit: Int = Cache.defaultCostLimit(), countLimit: Int = Int.max) {
self.costLimit = costLimit
self.countLimit = countLimit
#if os(iOS) || os(tvOS)
NotificationCenter.default.addObserver(self, selector: #selector(removeAll), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: .UIApplicationDidEnterBackground, object: nil)
#endif
}
deinit {
#if os(iOS) || os(tvOS)
NotificationCenter.default.removeObserver(self)
#endif
}
/// Returns a recommended cost limit which is computed based on the amount
/// of the phisical memory available on the device.
public static func defaultCostLimit() -> Int {
let physicalMemory = ProcessInfo.processInfo.physicalMemory
let ratio = physicalMemory <= (536_870_912 /* 512 Mb */) ? 0.1 : 0.2
let limit = physicalMemory / UInt64(1 / ratio)
return limit > UInt64(Int.max) ? Int.max : Int(limit)
}
/// Accesses the image associated with the given key.
public subscript(key: AnyHashable) -> Image? {
get {
lock.lock(); defer { lock.unlock() } // slightly faster than `sync()`
guard let node = map[key] else {
return nil
}
// bubble node up to make it last added (most recently used)
list.remove(node)
list.append(node)
return node.value.image
}
set {
lock.lock(); defer { lock.unlock() } // slightly faster than `sync()`
if let image = newValue {
_add(CachedImage(image: image, cost: cost(image), key: key))
_trim() // _trim is extremely fast, it's OK to call it each time
} else {
if let node = map[key] {
_remove(node: node)
}
}
}
}
private func _add(_ element: CachedImage) {
if let existingNode = map[element.key] {
_remove(node: existingNode)
}
map[element.key] = list.append(element)
totalCost += element.cost
}
private func _remove(node: LinkedList<CachedImage>.Node) {
list.remove(node)
map[node.value.key] = nil
totalCost -= node.value.cost
}
/// Removes all cached images.
@objc public dynamic func removeAll() {
lock.sync {
map.removeAll()
list.removeAll()
totalCost = 0
}
}
private func _trim() {
_trim(toCost: costLimit)
_trim(toCount: countLimit)
}
@objc private dynamic func didEnterBackground() {
// Remove most of the stored items when entering background.
// This behavior is similar to `NSCache` (which removes all
// items). This feature is not documented and may be subject
// to change in future Nuke versions.
lock.sync {
_trim(toCost: Int(Double(costLimit) * 0.1))
_trim(toCount: Int(Double(countLimit) * 0.1))
}
}
/// Removes least recently used items from the cache until the total cost
/// of the remaining items is less than the given cost limit.
public func trim(toCost limit: Int) {
lock.sync { _trim(toCost: limit) }
}
private func _trim(toCost limit: Int) {
_trim(while: { totalCost > limit })
}
/// Removes least recently used items from the cache until the total count
/// of the remaining items is less than the given count limit.
public func trim(toCount limit: Int) {
lock.sync { _trim(toCount: limit) }
}
private func _trim(toCount limit: Int) {
_trim(while: { totalCount > limit })
}
private func _trim(while condition: () -> Bool) {
while condition(), let node = list.first { // least recently used
_remove(node: node)
}
}
/// Returns cost for the given image by approximating its bitmap size in bytes in memory.
public var cost: (Image) -> Int = {
#if os(macOS)
return 1
#else
// bytesPerRow * height gives a rough estimation of how much memory
// image uses in bytes. In practice this algorithm combined with a
// concervative default cost limit works OK.
guard let cgImage = $0.cgImage else {
return 1
}
return cgImage.bytesPerRow * cgImage.height
#endif
}
}
private struct CachedImage {
let image: Image
let cost: Int
let key: AnyHashable
}
|
07f6550ca02df3b6bec19200902d08cc
| 32.597156 | 150 | 0.615602 | false | false | false | false |
priya273/stockAnalyzer
|
refs/heads/master
|
Stock Analyzer/Stock Analyzer/ErrorLoginFaceBookViewController.swift
|
apache-2.0
|
1
|
//
// ErrorLoginFaceBookViewController.swift
// Stock Analyzer
//
// Created by Naga sarath Thodime on 3/16/16.
// Copyright © 2016 Priyadarshini Ragupathy. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import FBSDKCoreKit
class ErrorLoginFaceBookViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.alertTheUserSomethingWentWrong("Try again", message:"Something went Wrong", actionTitle: "okay")
ShowFaceBookLogin()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Mark :- Alert Controller
func alertTheUserSomethingWentWrong(titleforController: String, message : String, actionTitle: String)
{
let controller = UIAlertController(title: titleforController , message: message, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: actionTitle, style: UIAlertActionStyle.Cancel, handler: nil)
controller.addAction(action)
self.presentViewController(controller, animated: true, completion: nil)
}
func ShowFaceBookLogin()
{
FBSDKAccessToken.setCurrentAccessToken(nil)
let facebookloginpage = self.storyboard?.instantiateViewControllerWithIdentifier("FaceBookLoginViewController") as! FaceBookLoginViewController
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
appDel.window?.rootViewController = facebookloginpage
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
0e3d127e306101bb02ac2b70775162e1
| 33.810345 | 151 | 0.718673 | false | false | false | false |
thiagotmb/BEPiD-Challenges-2016
|
refs/heads/master
|
2016-04-06-Complications/WeatherForecasts/WeatherForecasts WatchKit Extension/ComplicationController.swift
|
mit
|
2
|
//
// ComplicationController.swift
// WeatherForecasts WatchKit Extension
//
// Created by Thiago-Bernardes on 4/8/16.
// Copyright © 2016 TB. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Forward, .Backward])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
let firstForecast = ForecastsModel.getArrayDictionary().firstObject
handler(firstForecast?["dateWind"] as? NSDate)
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
let lastForecast = ForecastsModel.getArrayDictionary().lastObject
handler(lastForecast?["dateWind"] as? NSDate)
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
// Call the handler with the current timeline entry
let currentComplication = getComplicationTemplateForDate(complication, date: NSDate())
let entry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: currentComplication)
handler(entry)
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
let foreCasts = ForecastsModel.getForecastsBefore(date)
let entries = foreCasts.flatMap { currentForecast in
CLKComplicationTimelineEntry(
date: currentForecast["dateWind"] as! NSDate,
complicationTemplate: getComplicationTemplateForDate(complication, date: currentForecast["dateWind"] as! NSDate))
}
handler(entries)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
let foreCasts = ForecastsModel.getForecastsAfter(date)
let entries = foreCasts.flatMap { currentForecast in
CLKComplicationTimelineEntry(
date: currentForecast["dateWind"] as! NSDate,
complicationTemplate: getComplicationTemplateForDate(complication, date: currentForecast["dateWind"] as! NSDate))
}
handler(entries)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
let oneDayInterval = NSTimeInterval(60*60*24)
handler(NSDate().dateByAddingTimeInterval(oneDayInterval));
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
let template = getComplicationTemplateForDate(complication, date: NSDate(),isTemplate: true)
handler(template)
}
func getComplicationTemplateForDate(complication: CLKComplication,date: NSDate, isTemplate: Bool = false) -> CLKComplicationTemplate{
var forecast = ["dateWind": NSDate(), "velocity": "30"]
if !isTemplate {
forecast = ForecastsModel.getForecastOf(date)
}
if complication.family == .ModularLarge {
let complicationTemplate = CLKComplicationTemplateModularLargeStandardBody()
complicationTemplate.headerTextProvider = CLKSimpleTextProvider(text: "Wind Forecasts")
complicationTemplate.body1TextProvider = CLKSimpleTextProvider(text: "Speed: \((forecast["velocity"] as! NSString))")
complicationTemplate.body2TextProvider = CLKSimpleTextProvider(text: "\((forecast["dateWind"] as! NSDate))")
return complicationTemplate
}
return CLKComplicationTemplate()
}
func getTimelineAnimationBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineAnimationBehavior) -> Void) {
handler(CLKComplicationTimelineAnimationBehavior.Grouped)
}
}
|
bc336aba490b8aa8237f2884189d4704
| 44.638889 | 178 | 0.706026 | false | false | false | false |
TCA-Team/iOS
|
refs/heads/master
|
TUM Campus App/News.swift
|
gpl-3.0
|
1
|
//
// News.swift
// TUM Campus App
//
// This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS
// Copyright (c) 2018 TCA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import Sweeft
final class News: DataElement {
let id: String
let source: Source
let date: Date
let title: String
let link: String
let imageUrl: String?
init(id: String, source: Source, date: Date, title: String, link: String, imageUrl: String? = nil) {
self.id = id
self.source = source
self.date = date
self.title = title
self.link = link
self.imageUrl = imageUrl
}
var text: String {
get {
return title
}
}
func getCellIdentifier() -> String {
return "news"
}
func open(sender: UIViewController? = nil) {
link.url?.open(sender: sender)
}
}
extension News: Deserializable {
convenience init?(from json: JSON) {
guard let title = json["title"].string,
let source = json["src"].string.flatMap(Int.init).map(News.Source.init(identifier:)),
let link = json["link"].string,
let date = json["date"].date(using: "yyyy-MM-dd HH:mm:ss"),
let id = json["news"].string else {
return nil
}
self.init(id: id, source: source, date: date, title: title, link: link, imageUrl: json["image"].string)
}
}
extension News: Equatable {
static func == (lhs: News, rhs: News) -> Bool {
return lhs.id == rhs.id
}
}
|
40aa1ae152ca795bab64e865b7fdfd29
| 26.987013 | 111 | 0.612529 | false | false | false | false |
barteljan/RocketChatAdapter
|
refs/heads/master
|
Pod/Classes/RocketChatAdapter.swift
|
mit
|
1
|
//
// RocketChatAdapter.swift
// Pods
//
// Created by Jan Bartel on 12.03.16.
//
//
import VISPER_CommandBus
import SwiftDDP
import XCGLogger
public enum RocketChatAdapterError : ErrorType {
case ServerDidResponseWithEmptyResult(fileName:String,function: String,line: Int,column: Int)
case RequiredResponseFieldWasEmpty(field:String,fileName:String,function: String,line: Int,column: Int)
}
public struct RocketChatAdapter : RocketChatAdapterProtocol{
let commandBus : CommandBusProtocol
let endPoint : String
/**
* initialiser
**/
public init(endPoint:String){
self.init(endPoint:endPoint,commandBus: nil)
}
public init(endPoint:String,commandBus: CommandBusProtocol?){
self.endPoint = endPoint
if(commandBus != nil){
self.commandBus = commandBus!
}else{
self.commandBus = CommandBus()
}
}
/**
* Connect to server
**/
public func connect(endpoint:String,callback:(() -> ())?){
Meteor.client.logLevel = .Info
Meteor.connect(endpoint,callback: callback)
}
/**
* Register user
**/
public func register(email: String,name: String,password: String,completion: ((userId: String?, error: ErrorType?) -> Void)?){
let command = RegisterCommand(email: email, name: name, password: password)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(RegisterCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(userId: result,error: error)
}
}
/**
* Get username suggestion
**/
public func usernameSuggestion(completion:((username: String?,error:ErrorType?)->Void)?){
let command = GetUserNameSuggestionCommand()
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetUserNameSuggestionCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(username: result,error: error)
}
}
/**
* Set username
**/
public func setUsername(username:String,completion:((username: String?,error:ErrorType?)->Void)?){
let command = SetUserNameCommand(username:username)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SetUsernameCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(username: result,error: error)
}
}
/**
* Send Forgot password email
**/
public func sendForgotPasswordEmail(usernameOrMail: String, completion:((result: Int?,error: ErrorType?)->Void)?){
let command = SendForgotPasswordEMailCommand(userNameOrMail: usernameOrMail)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SendForgotPasswordEMailCommandHandler())
}
try! self.commandBus.process(command) { (result: Int?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Logon
**/
public func login(userNameOrEmail: String, password: String, completion:((result: AuthorizationResultProtocol?,error:ErrorType?)->Void)?){
let command = LogonCommand(userNameOrEmail:userNameOrEmail,password: password)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(LogonCommandHandler())
}
try! self.commandBus.process(command) { (result: AuthorizationResultProtocol?, error: ErrorType?) -> Void in
completion?(result:result,error: error)
}
}
/**
* get all public channels
**/
public func channelList(completion:((result: [ChannelProtocol]?,error: ErrorType?)->Void)?){
let command = GetChannelsCommand()
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetChannelsCommandHandler())
}
try! self.commandBus.process(command) { (result: [ChannelProtocol]?, error: ErrorType?) -> Void in
completion?(result: result, error: error)
}
}
/**
* get a channels id by its name
*/
public func getChannelId(name:String, completion:((roomId:String?, error: ErrorType?)->Void)?){
let command = GetRoomIdCommand(roomName: name)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetRoomIdCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(roomId: result, error: error)
}
}
/**
* Join a channel
**/
public func joinChannel(channelId: String,completion:((error:ErrorType?)->Void)?){
let command = JoinChannelCommand(channelId: channelId)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(JoinChannelCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
/**
* Leave a channel
**/
public func leaveChannel(channelId: String,completion:((error:ErrorType?)->Void)?){
let command = LeaveChannelCommand(channelId: channelId)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(LeaveChannelCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
/**
* Get messages of a channel
**/
public func channelMessages(channelId : String, numberOfMessages:Int, start: NSDate?, end: NSDate?, completion: ((result: MessageHistoryResultProtocol?, error: ErrorType?)->Void)?){
let command = GetChannelHistoryCommand(channelId: channelId,numberOfMessages: numberOfMessages,start: start, end: end)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetChannelHistoryCommandHandler(parser: MessageParser()))
}
try! self.commandBus.process(command) { (result: MessageHistoryResult?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Send a message in a channel
**/
public func sendMessage(channelId : String,message: String, completion: ((result: Message?, error: ErrorType?) -> Void)?){
let command = SendMessageCommand(channelId: channelId, message: message)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SendMessageCommandHandler(parser:MessageParser()))
}
try! self.commandBus.process(command) { (result: Message?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Set user status
**/
public func setUserStatus(userStatus: UserStatus,completion: ((error:ErrorType?)->Void)?){
let command = SetUserStatusCommand(userStatus: userStatus)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(UserStatusCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
}
|
6c1674cdc76232562f8f082070200230
| 29.681992 | 185 | 0.600899 | false | false | false | false |
jad6/DataStore
|
refs/heads/master
|
Example/Places/PlacesViewController.swift
|
bsd-2-clause
|
1
|
//
// PlacesViewController.swift
// Places
//
// Created by Jad Osseiran on 20/06/2015.
// Copyright © 2015 Jad Osseiran. All rights reserved.
//
import UIKit
class PlacesViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: Actions
@IBAction func addPlaceOption(sender: AnyObject) {
let alertController = UIAlertController(title: "Add Place", message: "Add a place into Core Data. The number of places that will be added can be set in the \"Batches\" setting.", preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = "Coral Bay"
textField.autocapitalizationType = .Words
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let saveAction = UIAlertAction(title: "Save", style: .Default) { action in
// Do the actual saving here.
}
alertController.addAction(saveAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
|
d56c5ee0b8d2dabc6394fcff43db31ad
| 30.675676 | 210 | 0.680034 | false | false | false | false |
hGhostD/SwiftLearning
|
refs/heads/master
|
Swift设计模式/Swift设计模式/21 模板方法模式/21.playground/Contents.swift
|
apache-2.0
|
1
|
import Cocoa
/*
> 模板方法可以允许第三方开发者,以创建子类或者定义闭包的方式,替换一个算法的某些步骤的具体实现
*/
struct Donor {
let title: String
let firstName: String
let familyName: String
let lastDonation: Float
init(_ title: String, _ first: String, _ family: String, _ last: Float) {
self.title = title
self.firstName = first
self.familyName = family
self.lastDonation = last
}
}
class DonorDatabase {
private var donors: [Donor]
init() {
donors = [Donor("Ms","Anne","Jones",0),
Donor("Mr","Bob","Smith",100),
Donor("Dr","Alice","Doe",200),
Donor("Prof","Joe","Davis",320)]
}
func generateGalaInvitations(_ maxNumber: Int) -> [String] {
var targetDonors: [Donor] = donors.filter { $0.lastDonation > 0 }
targetDonors.sort { (first, second) -> Bool in
first.lastDonation > second.lastDonation
}
if (targetDonors.count > maxNumber) {
targetDonors = Array(targetDonors[0..<maxNumber])
}
return targetDonors.map {
return "Dear \($0.title). \($0.familyName)"
}
}
}
let donorDb = DonorDatabase()
let galaInvitations = donorDb.generateGalaInvitations(2)
galaInvitations.forEach { print($0)}
|
f8cf6bb5a59e32535c618511872d1586
| 25.42 | 77 | 0.569266 | false | false | false | false |
movielala/TVOSButton
|
refs/heads/master
|
TVOSButtonExample/TVOSButtonExample/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// TVOSButtonExample
//
// Created by Cem Olcay on 11/02/16.
// Copyright © 2016 MovieLaLa. All rights reserved.
//
import UIKit
import TVOSButton
// MARK: - PosterButton
class PosterButton: TVOSButton {
var posterImage: UIImage? {
didSet {
badgeImage = posterImage
}
}
var posterImageURL: String? {
didSet {
if let posterImageURL = posterImageURL {
NSURLSession.sharedSession().dataTaskWithURL(
NSURL(string: posterImageURL)!,
completionHandler: { data, response, error in
if error == nil {
if let data = data, image = UIImage(data: data) {
dispatch_async(dispatch_get_main_queue(), {
self.posterImage = image
})
}
}
}).resume()
}
}
}
override func tvosButtonStyleForState(tvosButtonState: TVOSButtonState) -> TVOSButtonStyle {
switch tvosButtonState {
case .Focused:
return TVOSButtonStyle(
scale: 1.1,
shadow: TVOSButtonShadow.Focused,
badgeStyle: TVOSButtonImage.Fill(adjustsImageWhenAncestorFocused: true),
titleStyle: TVOSButtonLabel.DefaultTitle(color: UIColor.whiteColor()))
case .Highlighted:
return TVOSButtonStyle(
scale: 0.95,
shadow: TVOSButtonShadow.Highlighted,
badgeStyle: TVOSButtonImage.Fill(adjustsImageWhenAncestorFocused: true),
titleStyle: TVOSButtonLabel.DefaultTitle(color: UIColor.whiteColor()))
default:
return TVOSButtonStyle(
badgeStyle: TVOSButtonImage.Fill(adjustsImageWhenAncestorFocused: true),
titleStyle: TVOSButtonLabel.DefaultTitle(color: UIColor.blackColor()))
}
}
}
// MARK: - IconButton
class IconButton: TVOSButton {
var iconName: String? {
didSet {
handleStateDidChange()
}
}
override func tvosButtonStyleForState(tvosButtonState: TVOSButtonState) -> TVOSButtonStyle {
// custom content
let icon = UIImageView(frame: CGRect(x: 20, y: 0, width: 40, height: 40))
icon.center.y = 50
if let iconName = iconName {
let color = tvosButtonState == .Highlighted || tvosButtonState == .Focused ? "Black" : "White"
icon.image = UIImage(named: "\(iconName)\(color)")
}
switch tvosButtonState {
case .Focused:
return TVOSButtonStyle(
backgroundColor: UIColor.whiteColor(),
cornerRadius: 10,
scale: 1.1,
shadow: TVOSButtonShadow.Focused,
contentView: icon,
textStyle: TVOSButtonLabel.DefaultText(color: UIColor.blackColor()))
case .Highlighted:
return TVOSButtonStyle(
backgroundColor: UIColor.whiteColor(),
cornerRadius: 10,
scale: 0.95,
shadow: TVOSButtonShadow.Highlighted,
contentView: icon,
textStyle: TVOSButtonLabel.DefaultText(color: UIColor.blackColor()))
default:
return TVOSButtonStyle(
backgroundColor: UIColor(red: 198/255.0, green: 44/255.0, blue: 48/255.0, alpha: 1),
cornerRadius: 10,
contentView: icon,
textStyle: TVOSButtonLabel.DefaultText(color: UIColor.whiteColor()))
}
}
}
// MARK: - View Controller
class ViewController: UIViewController {
@IBOutlet var posterButton: PosterButton!
@IBOutlet var toggleButton: TVOSToggleButton!
@IBOutlet var iconButton: IconButton!
override func viewDidLoad() {
super.viewDidLoad()
// Setup poster button
posterButton.titleLabelText = "Poster"
posterButton.posterImageURL = "https://placeholdit.imgix.net/~text?txtsize=33&txt=240x360&w=240&h=360"
posterButton.addTarget(self, action: "tvosButtonPressed", forControlEvents: .PrimaryActionTriggered)
// Setup toggle button
toggleButton.didToggledAction = toggleButtonDidToggledActionHandler
// Setup icon button
iconButton.textLabelText = "Share"
iconButton.iconName = "share"
}
func toggleButtonDidToggledActionHandler(
currentState: TVOSToggleButtonState,
updateNewState: (newState: TVOSToggleButtonState) -> Void) {
switch currentState {
case .Waiting:
toggleButton.textLabelText = "..."
requestSomething({
self.toggleButton.textLabelText = "Add"
self.toggleButton.toggleState = .On
}, failure: {
self.toggleButton.textLabelText = "Remove"
self.toggleButton.toggleState = .Off
})
case .On:
toggleButton.textLabelText = "Adding"
updateNewState(newState: .Waiting)
removeSomething({
self.toggleButton.textLabelText = "Remove"
updateNewState(newState: .Off)
}, failure: {
self.toggleButton.textLabelText = "Add"
updateNewState(newState: .On)
})
case .Off:
toggleButton.textLabelText = "Removing"
updateNewState(newState: .Waiting)
addSomethingToServer({
self.toggleButton.textLabelText = "Add"
updateNewState(newState: .On)
}, failure: {
self.toggleButton.textLabelText = "Remove"
updateNewState(newState: .Off)
})
}
}
// Example request methods for simulate waiting for network
func addSomethingToServer(success: () -> Void, failure: () -> Void) {
requestSomething(success, failure: failure)
}
func removeSomething(success: () -> Void, failure: () -> Void) {
requestSomething(success, failure: failure)
}
func requestSomething(success: () -> Void, failure: () -> Void) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(0.5 * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), success)
}
// Event handler
func tvosButtonPressed() {
print("tvos button pressed")
}
}
|
4e237c9dce20cdc4f0bfb9d6a5909d13
| 28.773196 | 106 | 0.649758 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/User Profile Sheet/UserProfileUserInfoCell.swift
|
gpl-2.0
|
2
|
class UserProfileUserInfoCell: UITableViewCell, NibReusable {
// MARK: - Properties
@IBOutlet weak var gravatarImageView: CircularImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userBioLabel: UILabel!
static let estimatedRowHeight: CGFloat = 200
// MARK: - View
override func awakeFromNib() {
super.awakeFromNib()
configureCell()
}
// MARK: - Public Methods
func configure(withUser user: LikeUser) {
nameLabel.text = user.displayName
usernameLabel.text = String(format: Constants.usernameFormat, user.username)
userBioLabel.text = user.bio
userBioLabel.isHidden = user.bio.isEmpty
downloadGravatarWithURL(user.avatarUrl)
}
}
// MARK: - Private Extension
private extension UserProfileUserInfoCell {
func configureCell() {
nameLabel.textColor = .text
nameLabel.font = WPStyleGuide.serifFontForTextStyle(.title3, fontWeight: .semibold)
usernameLabel.textColor = .textSubtle
userBioLabel.textColor = .text
}
func downloadGravatarWithURL(_ url: String?) {
// Always reset gravatar
gravatarImageView.cancelImageDownload()
gravatarImageView.image = .gravatarPlaceholderImage
guard let url = url,
let gravatarURL = URL(string: url) else {
return
}
gravatarImageView.downloadImage(from: gravatarURL, placeholderImage: .gravatarPlaceholderImage)
}
struct Constants {
static let usernameFormat = NSLocalizedString("@%1$@", comment: "Label displaying the user's username preceeded by an '@' symbol. %1$@ is a placeholder for the username.")
}
}
|
a747b76080ee99aff6f321b286db2475
| 27.803279 | 179 | 0.677291 | false | false | false | false |
ElijahButers/Swift
|
refs/heads/master
|
GestureDoubleTap/GestureDoubleTab/ViewController.swift
|
gpl-3.0
|
32
|
//
// ViewController.swift
// GestureDoubleTab
//
// Created by Carlos Butron on 01/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func handleTap(sender : UIGestureRecognizer) {
if (sender.view?.contentMode == UIViewContentMode.ScaleAspectFit){
sender.view?.contentMode = UIViewContentMode.Center
}
else{
sender.view?.contentMode = UIViewContentMode.ScaleAspectFit
} }
override func viewDidLoad() {
var tapGesture = UITapGestureRecognizer(target: self, action:
"handleTap:")
tapGesture.numberOfTapsRequired = 2;
image.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view, typically from a nib.
}
}
|
b55854ceb743a4bcb63a282b87c46ee8
| 33.24 | 121 | 0.6875 | false | false | false | false |
davidchiles/OSMKit-Swift
|
refs/heads/master
|
OSMKit/OSMKitTests/Tests/ParserDelegate.swift
|
mit
|
2
|
//
// ParserDelegate.swift
// OSMKit
//
// Created by David Chiles on 12/18/15.
// Copyright © 2015 David Chiles. All rights reserved.
//
import Foundation
import OSMKit_Swift
class ParserDelegate:OSMParserDelegate {
var startBlock:(parser:OSMParser) -> Void
var endBlock:(parser:OSMParser) -> Void
var nodeBlock:(parser:OSMParser,node:OSMNode) -> Void
var wayBlock:(parser:OSMParser,way:OSMWay) -> Void
var relationBlock:(parser:OSMParser,relation:OSMRelation) -> Void
var errorBlock:(parser:OSMParser,error:ErrorType?) -> Void
init(startBlock:(parser:OSMParser) -> Void,nodeBlock:(parser:OSMParser,node:OSMNode) -> Void,wayBlock:(parser:OSMParser,way:OSMWay) -> Void,relationBlock:(parser:OSMParser,relation:OSMRelation) -> Void,endBlock:(parser:OSMParser) -> Void,errorBlock:(parser:OSMParser,error:ErrorType?) -> Void) {
self.startBlock = startBlock
self.nodeBlock = nodeBlock
self.wayBlock = wayBlock
self.relationBlock = relationBlock
self.errorBlock = errorBlock
self.endBlock = endBlock
}
//MARK: OSMParserDelegate Methods
func didStartParsing(parser: OSMParser) {
self.startBlock(parser: parser)
}
func didFindElement(parser: OSMParser, element: OSMElement) {
switch element {
case let element as OSMNode:
self.nodeBlock(parser: parser, node: element)
case let element as OSMWay:
self.wayBlock(parser: parser, way: element)
case let element as OSMRelation:
self.relationBlock(parser: parser, relation: element)
default:
break
}
}
func didFinishParsing(parser: OSMParser) {
self.endBlock(parser: parser)
}
func didError(parser: OSMParser, error: ErrorType?) {
self.errorBlock(parser: parser, error: error)
}
}
|
d1dc85c64252296853e8898b6a0b1a08
| 33.363636 | 299 | 0.66702 | false | false | false | false |
PeterWinzell/vehicle-carsignal-examples
|
refs/heads/master
|
iphoneclient/W3CDemo_2/W3CDemo_2/W3CDemo_2/SocketIOManager.swift
|
gpl-3.0
|
1
|
//
// SocketIOManager.swift
// W3CDemo
//
//
// The MIT License (MIT)
// Copyright (c) <09/11/16> <Peter Winzell>
//
// 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
import Starscream
import SwiftyJSON
class SocketIOManager: WebSocketDelegate{
static let sharedInstance = SocketIOManager()
var socket: WebSocket!
// global access through singleton...darn ugly. Must be a better way of doing this.
var zespeed: Int!
init() {
}
func setURL(_ urlString: String){
print(urlString)
socket = WebSocket(url: URL(string: urlString)!)
socket.delegate = self
socket.connect()
}
// MARK: Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocket) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
// Post notification
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
let json = text;
let data = json.data(using: String.Encoding.utf8)
let jsonarray = JSON(data: data!)
let path = jsonarray["path"].string
print(text)
// check if path is correct
if (path == "Vehicle.speed"){
zespeed = jsonarray["value"].int!
if zespeed != nil{
// notify UI through notification center (GOTO ViewController)
print(zespeed)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateSpeed"), object: nil)
}
}
}
func websocketDidReceiveData(socket: WebSocket, data: Data) {
print("Received data: \(data.count)")
}
func sendMessage(message: String) {
socket.write(string: message)
}
}
|
3c6113c4efeeae73fe853345ac1b1028
| 32.152174 | 112 | 0.649508 | false | false | false | false |
soffes/Motivation
|
refs/heads/master
|
Motivation/AgeView.swift
|
mit
|
1
|
//
// AgeView.swift
// Motivation
//
// Created by Sam Soffes on 8/6/15.
// Copyright (c) 2015 Sam Soffes. All rights reserved.
//
import Foundation
import ScreenSaver
class AgeView: ScreenSaverView {
// MARK: - Properties
private let textLabel: NSTextField = {
let label = NSTextField()
label.translatesAutoresizingMaskIntoConstraints = false
label.editable = false
label.drawsBackground = false
label.bordered = false
label.bezeled = false
label.selectable = false
label.textColor = .whiteColor()
return label
}()
private lazy var configurationWindowController: NSWindowController = {
return ConfigurationWindowController()
}()
private var motivationLevel: MotivationLevel
private var birthday: NSDate? {
didSet {
updateFont()
}
}
// MARK: - Initializers
convenience init() {
self.init(frame: CGRectZero, isPreview: false)
}
override init!(frame: NSRect, isPreview: Bool) {
motivationLevel = Preferences().motivationLevel
super.init(frame: frame, isPreview: isPreview)
initialize()
}
required init?(coder: NSCoder) {
motivationLevel = Preferences().motivationLevel
super.init(coder: coder)
initialize()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - NSView
override func drawRect(rect: NSRect) {
let backgroundColor: NSColor = .blackColor()
backgroundColor.setFill()
NSBezierPath.fillRect(bounds)
}
// If the screen saver changes size, update the font
override func resizeWithOldSuperviewSize(oldSize: NSSize) {
super.resizeWithOldSuperviewSize(oldSize)
updateFont()
}
// MARK: - ScreenSaverView
override func animateOneFrame() {
if let birthday = birthday {
let age = ageForBirthday(birthday)
let format = "%0.\(motivationLevel.decimalPlaces)f"
textLabel.stringValue = String(format: format, age)
} else {
textLabel.stringValue = "Open Screen Saver Options to set your birthday."
}
}
override func hasConfigureSheet() -> Bool {
return true
}
override func configureSheet() -> NSWindow? {
return configurationWindowController.window
}
// MARK: - Private
/// Shared initializer
private func initialize() {
// Set animation time interval
animationTimeInterval = 1 / 30
// Recall preferences
birthday = Preferences().birthday
// Setup the label
addSubview(textLabel)
addConstraints([
NSLayoutConstraint(item: textLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: textLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0)
])
// Listen for configuration changes
NSNotificationCenter.defaultCenter().addObserver(self, selector: "motivationLevelDidChange:", name: Preferences.motivationLevelDidChangeNotificationName, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "birthdayDidChange:", name: Preferences.birthdayDidChangeNotificationName, object: nil)
}
/// Age calculation
private func ageForBirthday(birthday: NSDate) -> Double {
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
// An age is defined as the number of years you've been alive plus the number of days, seconds, and nanoseconds
// you've been alive out of that many units in the current year.
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Day, NSCalendarUnit.Second, NSCalendarUnit.Nanosecond], fromDate: birthday, toDate: now, options: [])
// We calculate these every time since the values can change when you cross a boundary. Things are too
// complicated to try to figure out when that is and cache them. NSCalendar is made for this.
let daysInYear = Double(calendar.daysInYear(now) ?? 365)
let hoursInDay = Double(calendar.rangeOfUnit(NSCalendarUnit.Hour, inUnit: NSCalendarUnit.Day, forDate: now).length)
let minutesInHour = Double(calendar.rangeOfUnit(NSCalendarUnit.Minute, inUnit: NSCalendarUnit.Hour, forDate: now).length)
let secondsInMinute = Double(calendar.rangeOfUnit(NSCalendarUnit.Second, inUnit: NSCalendarUnit.Minute, forDate: now).length)
let nanosecondsInSecond = Double(calendar.rangeOfUnit(NSCalendarUnit.Nanosecond, inUnit: NSCalendarUnit.Second, forDate: now).length)
// Now that we have all of the values, assembling them is easy. We don't get minutes and hours from the calendar
// since it will overflow nicely to seconds. We need days and years since the number of days in a year changes
// more frequently. This will handle leap seconds, days, and years.
let seconds = Double(components.second) + (Double(components.nanosecond) / nanosecondsInSecond)
let minutes = seconds / secondsInMinute
let hours = minutes / minutesInHour
let days = Double(components.day) + (hours / hoursInDay)
let years = Double(components.year) + (days / daysInYear)
return years
}
/// Motiviation level changed
@objc private func motivationLevelDidChange(notification: NSNotification?) {
motivationLevel = Preferences().motivationLevel
}
/// Birthday changed
@objc private func birthdayDidChange(notification: NSNotification?) {
birthday = Preferences().birthday
}
/// Update the font for the current size
private func updateFont() {
if birthday != nil {
textLabel.font = fontWithSize(bounds.width / 10)
} else {
textLabel.font = fontWithSize(bounds.width / 30, monospace: false)
}
}
/// Get a font
private func fontWithSize(fontSize: CGFloat, monospace: Bool = true) -> NSFont {
let font: NSFont
if #available(OSX 10.11, *) {
font = .systemFontOfSize(fontSize, weight: NSFontWeightThin)
} else {
font = NSFont(name: "HelveticaNeue-Thin", size: fontSize)!
}
let fontDescriptor: NSFontDescriptor
if monospace {
fontDescriptor = font.fontDescriptor.fontDescriptorByAddingAttributes([
NSFontFeatureSettingsAttribute: [
[
NSFontFeatureTypeIdentifierKey: kNumberSpacingType,
NSFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector
]
]
])
} else {
fontDescriptor = font.fontDescriptor
}
return NSFont(descriptor: fontDescriptor, size: fontSize)!
}
}
|
d404ac9bd8bf0f739cd70af79c0e90f3
| 30.566327 | 177 | 0.742686 | false | false | false | false |
littlelightwang/firefox-ios
|
refs/heads/master
|
Client/Frontend/Settings/SettingsViewController.swift
|
mpl-2.0
|
2
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class SettingsViewController: UIViewController, ToolbarViewProtocol,
UITableViewDataSource, UITableViewDelegate, FxASignInViewControllerDelegate
{
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var settingsTableView: UITableView!
@IBOutlet weak var signOutButton: UIButton!
var profile: Profile!
let SETTING_CELL_ID = "SETTING_CELL_ID"
lazy var panels: Panels = {
return Panels(profile: self.profile)
}()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
avatarImageView.layer.cornerRadius = 50
avatarImageView.layer.masksToBounds = true
avatarImageView.isAccessibilityElement = true
avatarImageView.accessibilityLabel = NSLocalizedString("Avatar", comment: "")
settingsTableView.delegate = self
settingsTableView.dataSource = self
settingsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
settingsTableView.separatorInset = UIEdgeInsetsZero
settingsTableView.editing = true
settingsTableView.allowsSelectionDuringEditing = true
settingsTableView.backgroundColor = view.backgroundColor
settingsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: SETTING_CELL_ID)
signOutButton.layer.borderColor = UIColor.whiteColor().CGColor
signOutButton.layer.borderWidth = 1.0
signOutButton.layer.cornerRadius = 6.0
signOutButton.addTarget(self, action: "didClickLogout", forControlEvents: UIControlEvents.TouchUpInside)
}
func signInViewControllerDidCancel(vc: FxASignInViewController) {
vc.dismissViewControllerAnimated(true, completion: nil)
}
// A temporary delegate which merely updates the displayed email address on
// succesful Firefox Accounts sign in.
func signInViewControllerDidSignIn(vc: FxASignInViewController, data: JSON) {
emailLabel.text = data["email"].asString
}
// Referenced as button selector. Temporarily, we show the Firefox
// Accounts sign in view.
func didClickLogout() {
let vc = FxASignInViewController()
vc.signInDelegate = self
presentViewController(vc, animated: true, completion: nil)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let cell = tableView.cellForRowAtIndexPath(indexPath)
if let sw = cell?.editingAccessoryView as? UISwitch {
sw.setOn(!sw.on, animated: true)
panels.enablePanelAt(sw.on, position: indexPath.item)
}
return indexPath;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Subtract one so that we don't show our own panel
return panels.count - 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(SETTING_CELL_ID, forIndexPath: indexPath) as UITableViewCell
if var item = panels[indexPath.item] {
cell.textLabel?.text = item.title
cell.textLabel?.font = UIFont(name: "FiraSans-Light", size: cell.textLabel?.font.pointSize ?? 0)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = self.view.backgroundColor
cell.separatorInset = UIEdgeInsetsZero
cell.selectionStyle = UITableViewCellSelectionStyle.None
let toggle: UISwitch = UISwitch()
toggle.on = item.enabled;
cell.editingAccessoryView = toggle
}
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
panels.moveItem(sourceIndexPath.item, to: destinationIndexPath.item)
settingsTableView.setNeedsDisplay();
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.editing {
for v in cell.subviews as [UIView] {
if v.frame.width == 1.0 {
v.backgroundColor = UIColor.clearColor()
}
}
}
}
}
|
836fc83ef43d7a9b69551ae02f92601e
| 39.355556 | 140 | 0.69163 | false | false | false | false |
tkach/SimpleRedditClient
|
refs/heads/master
|
SimpleRedditClient/Common/Router/AppRouter.swift
|
mit
|
1
|
//
// Created by Alexander Tkachenko on 9/9/17.
//
import UIKit
final class AppRouter {
struct Constants {
static let rootNavigationRestorationID = "RootNavigationController"
}
fileprivate let modulesAssembly: ModulesAssembly
fileprivate lazy var navigationController: UINavigationController = {
let controller = UINavigationController(rootViewController: self.modulesAssembly.entriesListViewController())
controller.restorationIdentifier = Constants.rootNavigationRestorationID
return controller
}()
init(modulesAssembly: ModulesAssembly) {
self.modulesAssembly = modulesAssembly
}
func rootViewController() -> UIViewController {
return navigationController
}
func restoreController(with identifier: String, coder: NSCoder) -> UIViewController? {
if (identifier == Constants.rootNavigationRestorationID) {
return navigationController
}
else {
return modulesAssembly.restoreController(with: identifier, coder: coder)
}
}
}
extension AppRouter: EntriesListRouter {
func route(to item: EntryItem) {
let controller = modulesAssembly.entryDetailsViewController(with: item)
navigationController.pushViewController(controller, animated: true)
}
}
|
c5f8012ac3157e85b110b01873bf567c
| 31.268293 | 117 | 0.71353 | false | false | false | false |
xuzhuoxi/SearchKit
|
refs/heads/master
|
Source/cs/cacheconfig/CacheConfig.swift
|
mit
|
1
|
//
// CacheConfig.swift
// SearchKit
//
// Created by 许灼溪 on 15/12/19.
//
//
import Foundation
/**
*
* @author xuzhuoxi
*
*/
open class CacheConfig {
open static let instance: CacheConfig = CacheConfig()
fileprivate var map = Dictionary<String, CacheInfo>()
fileprivate let currentBundle = Bundle(for: CacheConfig.self)
/**
* 缓存配置<br>
* resourcePath路径在实际使用时补充绝对路径,如要取消这种做法,请修改CachePool类<br>
* initialCapacity的配置应该根据实际情况进行配置<br>
* 计算方法:缓存数的下一个2的n次幂<br>
*/
fileprivate init(){
addConfig(CacheNames.PINYIN_WORD, "SearchKit.CharacterLibraryImpl", true, 32768, "word_pinyin", "UTF-8", ValueCodingType.pinyin_WORD)
addConfig(CacheNames.WUBI_WORD, "SearchKit.CharacterLibraryImpl", true, 8192, "word_wubi", "UTF-8", ValueCodingType.wubi_WORD)
}
fileprivate func toMultiPath(_ path: String?) ->[String]? {
if nil == path || path!.isEmpty {
return nil
}
return path!.components(separatedBy: ";")
}
fileprivate func addConfig(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourcePaths: String?, _ charsetName: String?, _ valueCodingType: ValueCodingType?) {
if map.has(cacheName) {
return
}
var urls : [URL]? = nil
if let paths = toMultiPath(resourcePaths) {
urls = []
for path in paths {
urls!.append(currentBundle.url(forResource: path, withExtension: "properites")!)
}
}
map[cacheName] = CacheInfo(cacheName, cacheClassName, isSingleton, initialCapacity, urls, charsetName, valueCodingType: valueCodingType)
}
fileprivate func addConfig(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourceURLs: [URL]?, _ charsetName: String?, valueCodingClassName: String?) {
if map.has(cacheName) {
return
}
map[cacheName] = CacheInfo(cacheName, cacheClassName, isSingleton, initialCapacity, resourceURLs, charsetName, valueCodingClassName:valueCodingClassName)
}
open func supplyConfig(_ cacheName: String, reflectClassName: String, isSingleton: Bool, initialCapacity: UInt, resourceURLs: [URL]?, charsetName: String?, valueCodingClassName: String?) {
addConfig(cacheName, reflectClassName, isSingleton, initialCapacity, resourceURLs, charsetName, valueCodingClassName: valueCodingClassName)
}
open func getCacheInfo(_ cacheName : String) ->CacheInfo? {
return map[cacheName]
}
open func getCacheInfos() ->[CacheInfo] {
return [CacheInfo](map.values)
}
}
|
bd159ded70f7aa8b1bb82de67d398998
| 36.583333 | 212 | 0.657428 | false | true | false | false |
JGiola/swift
|
refs/heads/main
|
test/Generics/derived_via_concrete_in_protocol.swift
|
apache-2.0
|
6
|
// RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-swift-frontend -debug-generic-signatures -typecheck %s 2>&1 | %FileCheck %s
protocol P24 {
associatedtype C: P20
}
protocol P20 { }
struct X24<T: P20> : P24 {
typealias C = T
}
protocol P26 {
associatedtype C: X3
}
struct X26<T: X3> : P26 {
typealias C = T
}
class X3 { }
// CHECK-LABEL: .P25a@
// CHECK-NEXT: Requirement signature: <Self where Self.[P25a]A == X24<Self.[P25a]B>, Self.[P25a]B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P25a]A == X24<τ_0_0.[P25a]B>, τ_0_0.[P25a]B : P20>
protocol P25a {
associatedtype A: P24 // expected-warning{{redundant conformance constraint 'X24<Self.B>' : 'P24'}}
associatedtype B: P20 where A == X24<B>
}
// CHECK-LABEL: .P25b@
// CHECK-NEXT: Requirement signature: <Self where Self.[P25b]A == X24<Self.[P25b]B>, Self.[P25b]B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P25b]A == X24<τ_0_0.[P25b]B>, τ_0_0.[P25b]B : P20>
protocol P25b {
associatedtype A
associatedtype B: P20 where A == X24<B>
}
// CHECK-LABEL: .P27a@
// CHECK-NEXT: Requirement signature: <Self where Self.[P27a]A == X26<Self.[P27a]B>, Self.[P27a]B : X3>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P27a]A == X26<τ_0_0.[P27a]B>, τ_0_0.[P27a]B : X3>
protocol P27a {
associatedtype A: P26 // expected-warning{{redundant conformance constraint 'X26<Self.B>' : 'P26'}}
associatedtype B: X3 where A == X26<B>
}
// CHECK-LABEL: .P27b@
// CHECK-NEXT: Requirement signature: <Self where Self.[P27b]A == X26<Self.[P27b]B>, Self.[P27b]B : X3>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.[P27b]A == X26<τ_0_0.[P27b]B>, τ_0_0.[P27b]B : X3>
protocol P27b {
associatedtype A
associatedtype B: X3 where A == X26<B>
}
|
15b259a89c418592e717b20f671a967a
| 32.436364 | 118 | 0.665579 | false | false | false | false |
mortorqrobotics/morscout-ios
|
refs/heads/master
|
MorScout/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// MorScout
//
// Created by Farbod Rafezy on 1/8/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import UIKit
import Kingfisher
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// set navigation bar color
UINavigationBar.appearance().barTintColor = UIColorFromHex("#FFC547")
UINavigationBar.appearance().tintColor = UIColor.black
UINavigationBar.appearance().isTranslucent = false
// this is so we can set the initial view controller to either
// the login screen on the home screen depending on login
// status upon opening the app.
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let revealVC : UIViewController! = mainStoryboard.instantiateViewController(withIdentifier: "reveal")
let loginVC : UIViewController! = mainStoryboard.instantiateViewController(withIdentifier: "login")
if let _ = storage.string(forKey: "connect.sid"){
//logged in
if storage.bool(forKey: "noTeam") {
logoutSilently()
self.window?.rootViewController = loginVC
} else {
self.window?.rootViewController = revealVC
}
} else {
//not logged in
self.window?.rootViewController = loginVC
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
23872f529eb952b9036a87cdfed98d5a
| 45.070423 | 285 | 0.7059 | false | false | false | false |
ibm-bluemix-push-notifications/bms-samples-swift-login
|
refs/heads/master
|
userIdBasedSwift/MessageViewController.swift
|
apache-2.0
|
1
|
//
// MessageViewController.swift
// userIdBasedSwift
//
// Created by Anantha Krishnan K G on 25/07/16.
// Copyright © 2016 Ananth. All rights reserved.
//
import UIKit
class MessageViewController: UIViewController, PopupContentViewController {
var closeHandler: (() -> Void)?
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
@IBOutlet var pushNotificationMessage: UILabel!
@IBOutlet weak var button: UIButton! {
didSet {
button.layer.borderColor = UIColor(red: 242/255, green: 105/255, blue: 100/255, alpha: 1.0).CGColor
button.layer.borderWidth = 1.5
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.frame.size = CGSizeMake(250,200)
pushNotificationMessage.text = appDelegate.message
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class func instance() -> MessageViewController {
let storyboard = UIStoryboard(name: "DemoPopupViewController1", bundle: nil)
return storyboard.instantiateInitialViewController() as! MessageViewController
}
func sizeForPopup(popupController: PopupController, size: CGSize, showingKeyboard: Bool) -> CGSize {
return CGSizeMake(300,300)
}
@IBAction func didTapCloseButton(sender: AnyObject) {
closeHandler?()
}
}
|
265c644165b0891e9fdd435a3e1fab25
| 29.96 | 111 | 0.669251 | false | false | false | false |
baodvu/dashtag
|
refs/heads/master
|
dashtag/RegisterViewController.swift
|
mit
|
1
|
//
// RegisterViewController.swift
// dashtag
//
// Created by Bao Vu on 10/16/16.
// Copyright © 2016 Dashtag. All rights reserved.
//
import UIKit
import FirebaseAuth
class RegisterViewController: UIViewController {
@IBOutlet weak var fullNameTF: UITextField!
@IBOutlet weak var emailTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var confirmPasswordTF: UITextField!
var fullName: String {
get {
return fullNameTF.text ?? ""
}
}
var email: String {
get {
let s = emailTF.text ?? ""
return isValidEmail(s) ? s : ""
}
}
var password: String {
get {
return (passwordTF.text ?? "" == confirmPasswordTF.text ?? "") ? passwordTF.text! : ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(testStr)
}
@IBAction func createAccount(sender: UIButton) {
if email == "" {
showAlert("Please check the email field")
return
}
if fullName == "" {
showAlert("Please check the name field")
return
}
if password == "" {
showAlert("Please check the password again")
return
}
FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
if (error != nil) {
print(error)
let alert = UIAlertController(title: "Registration failed", message: "Please make sure you entered all fields correctly", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
if let user = user {
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = self.fullName
changeRequest.commitChangesWithCompletion { error in
if error != nil {
// An error happened.
} else {
// Profile updated.
}
}
self.performSegueWithIdentifier("SegueRegisterToLogin", sender: self)
}
}
}
}
func showAlert(message: String) -> Void {
let alert = UIAlertController(title: "Registration failed", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
|
f7a12e57ffba49028d44ab0795fa3b3d
| 33.486726 | 183 | 0.573518 | false | false | false | false |
Eveets/cryptick
|
refs/heads/master
|
cryptick/Model/Ticker.swift
|
apache-2.0
|
1
|
//
// Ticker.swift
// cryptick
//
// Created by Steeve Monniere on 20-07-2017.
// Copyright © 2017 Steeve Monniere. All rights reserved.
//
import UIKit
class Ticker: NSObject {
//Pair Info
var base:String?
var quote:String?
var active : Bool = false
//Info
var price:Double?
var ask:Double?
var bid:Double?
var low:Double?
var high:Double?
var volume:Double?
var openPrice:Double?
var vwap:Double?
var unchanged:Bool = true
var up:Bool = false
//Calculated value
var pairName:String {
get{return String.localizedStringWithFormat("%@%@", base!, quote!)}
set{}
}
var percentChange:Double {
get{
if(price != nil && openPrice != nil && openPrice != 0.0){
return price!/openPrice!;
}
else
{
return 0.00
}
}
set{}
}
static func ticker (base:String, quote:String) -> Ticker
{
let t = Ticker.init()
t.base = base
t.quote = quote
return t
}
}
|
5664f91bb86ab6e5da6f16c9c912734b
| 18.20339 | 75 | 0.518976 | false | false | false | false |
BPerlakiH/Swift4Cart
|
refs/heads/master
|
SwiftCart/Model/FX.swift
|
mit
|
1
|
//
// FX.swift
// SwiftCart
//
// Created by Balazs Perlaki-Horvath on 07/07/2017.
// Copyright © 2017 perlakidigital. All rights reserved.
//
import Foundation
import UIKit
class FX {
let apiKey : String
let activeCurrencies : [String]
var response : FxResponse?
init() {
apiKey = Bundle.main.object(forInfoDictionaryKey: "FX_API_Key") as! String
activeCurrencies = Bundle.main.object(forInfoDictionaryKey: "FX_Active_Currencies") as! [String]
}
func all() -> Dictionary<String, Float>? {
return self.response?.quotes
}
func refresh(completion: () -> Void) {
let downloader = FXDownloader()
downloader.downloadRates(apiKey: apiKey, currencies: activeCurrencies) { (data, error) in
if let _ = error {
NSLog("other api error", error.debugDescription)
return
}
guard let jsonData = data else {
NSLog("no data has been returned")
return
}
let decoder = JSONDecoder()
self.response = try? decoder.decode(FxResponse.self, from: jsonData)
}
}
func rateOf(currency: String) -> Float? {
assert(currency.count == 3)
assert(activeCurrencies.contains(currency))
return self.response?.quotes["USD\(currency)"]
}
func priceOf(price: Float, inCurrency: String) -> Float {
assert(inCurrency.count == 3)
assert(inCurrency == "USD" || activeCurrencies.contains(inCurrency))
if let rate = self.response?.quotes["USD\(inCurrency)"] {
return rate * price
} else {
return price
}
}
func _getJsonData() -> Data {
let fxData = """
{
"success": true,
"terms": "https://currencylayer.com/terms",
"privacy": "https://currencylayer.com/privacy",
"timestamp": 1499431446,
"source": "USD",
"quotes": {
"USDAUD": 1.315016,
"USDCAD": 1.291402,
"USDCHF": 0.96167,
"USDEUR": 0.87505,
"USDGBP": 0.77495,
"USDHUF": 269.619995,
"USDPLN": 3.704299
}
}
""".data(using: .utf8)!
return fxData
}
}
|
9a4612fcbab634120a8043c45b7ad92c
| 27.573171 | 104 | 0.536492 | false | false | false | false |
airbnb/lottie-ios
|
refs/heads/master
|
Sources/Private/Model/DotLottie/Zip/ZipArchive.swift
|
apache-2.0
|
2
|
//
// Archive.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
// MARK: - ZipArchive
final class ZipArchive: Sequence {
// MARK: Lifecycle
/// Initializes a new ZIP `Archive`.
///
/// You can use this initalizer to create new archive files or to read and update existing ones.
/// - Parameters:
/// - url: File URL to the receivers backing file.
/// - Returns: An archive initialized with a backing file at the passed in file URL and the given access mode
/// or `nil` if the following criteria are not met:
init?(url: URL) {
self.url = url
guard let config = ZipArchive.makeBackingConfiguration(for: url) else { return nil }
archiveFile = config.file
endOfCentralDirectoryRecord = config.endOfCentralDirectoryRecord
zip64EndOfCentralDirectory = config.zip64EndOfCentralDirectory
setvbuf(archiveFile, nil, _IOFBF, Int(Self.defaultPOSIXBufferSize))
}
deinit {
fclose(self.archiveFile)
}
// MARK: Internal
typealias LocalFileHeader = ZipEntry.LocalFileHeader
typealias DataDescriptor = ZipEntry.DefaultDataDescriptor
typealias ZIP64DataDescriptor = ZipEntry.ZIP64DataDescriptor
typealias CentralDirectoryStructure = ZipEntry.CentralDirectoryStructure
/// An error that occurs during reading, creating or updating a ZIP file.
enum ArchiveError: Error {
/// Thrown when an archive file is either damaged or inaccessible.
case unreadableArchive
/// Thrown when an archive is either opened with AccessMode.read or the destination file is unwritable.
case unwritableArchive
/// Thrown when the path of an `Entry` cannot be stored in an archive.
case invalidEntryPath
/// Thrown when an `Entry` can't be stored in the archive with the proposed compression method.
case invalidCompressionMethod
/// Thrown when the stored checksum of an `Entry` doesn't match the checksum during reading.
case invalidCRC32
/// Thrown when an extract, add or remove operation was canceled.
case cancelledOperation
/// Thrown when an extract operation was called with zero or negative `bufferSize` parameter.
case invalidBufferSize
/// Thrown when uncompressedSize/compressedSize exceeds `Int64.max` (Imposed by file API).
case invalidEntrySize
/// Thrown when the offset of local header data exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderDataOffset
/// Thrown when the size of local header exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderSize
/// Thrown when the offset of central directory exceeds `Int64.max` (Imposed by file API).
case invalidCentralDirectoryOffset
/// Thrown when the size of central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectorySize
/// Thrown when number of entries in central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectoryEntryCount
/// Thrown when an archive does not contain the required End of Central Directory Record.
case missingEndOfCentralDirectoryRecord
}
struct EndOfCentralDirectoryRecord: DataSerializable {
let endOfCentralDirectorySignature = UInt32(endOfCentralDirectoryStructSignature)
let numberOfDisk: UInt16
let numberOfDiskStart: UInt16
let totalNumberOfEntriesOnDisk: UInt16
let totalNumberOfEntriesInCentralDirectory: UInt16
let sizeOfCentralDirectory: UInt32
let offsetToStartOfCentralDirectory: UInt32
let zipFileCommentLength: UInt16
let zipFileCommentData: Data
static let size = 22
}
// MARK: - Helpers
typealias EndOfCentralDirectoryStructure = (EndOfCentralDirectoryRecord, ZIP64EndOfCentralDirectory?)
struct BackingConfiguration {
let file: FILEPointer
let endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
let zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?
init(
file: FILEPointer,
endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord,
zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?)
{
self.file = file
self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord
self.zip64EndOfCentralDirectory = zip64EndOfCentralDirectory
}
}
static let defaultPOSIXBufferSize = Int(16 * 1024)
static let minEndOfCentralDirectoryOffset = Int64(22)
static let endOfCentralDirectoryStructSignature = 0x06054b50
/// The default chunk size when reading entry data from an archive.
static let defaultReadChunkSize = Int(16 * 1024)
/// URL of an Archive's backing file.
let url: URL
var archiveFile: FILEPointer
var endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
var zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?
var totalNumberOfEntriesInCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.totalNumberOfEntriesInCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.totalNumberOfEntriesInCentralDirectory)
}
var sizeOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.sizeOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.sizeOfCentralDirectory)
}
var offsetToStartOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.offsetToStartOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.offsetToStartOfCentralDirectory)
}
static func scanForEndOfCentralDirectoryRecord(in file: FILEPointer)
-> EndOfCentralDirectoryStructure?
{
var eocdOffset: UInt64 = 0
var index = minEndOfCentralDirectoryOffset
fseeko(file, 0, SEEK_END)
let archiveLength = Int64(ftello(file))
while eocdOffset == 0, index <= archiveLength {
fseeko(file, off_t(archiveLength - index), SEEK_SET)
var potentialDirectoryEndTag = UInt32()
fread(&potentialDirectoryEndTag, 1, MemoryLayout<UInt32>.size, file)
if potentialDirectoryEndTag == UInt32(endOfCentralDirectoryStructSignature) {
eocdOffset = UInt64(archiveLength - index)
guard let eocd: EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: eocdOffset) else {
return nil
}
let zip64EOCD = scanForZIP64EndOfCentralDirectory(in: file, eocdOffset: eocdOffset)
return (eocd, zip64EOCD)
}
index += 1
}
return nil
}
static func makeBackingConfiguration(for url: URL) -> BackingConfiguration? {
let fileManager = FileManager()
let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard
let archiveFile = fopen(fileSystemRepresentation, "rb"),
let (eocdRecord, zip64EOCD) = ZipArchive.scanForEndOfCentralDirectoryRecord(in: archiveFile) else
{
return nil
}
return BackingConfiguration(
file: archiveFile,
endOfCentralDirectoryRecord: eocdRecord,
zip64EndOfCentralDirectory: zip64EOCD)
}
func makeIterator() -> AnyIterator<ZipEntry> {
let totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var directoryIndex = offsetToStartOfCentralDirectory
var index = 0
return AnyIterator {
guard index < totalNumberOfEntriesInCD else { return nil }
guard
let centralDirStruct: CentralDirectoryStructure = Data.readStruct(
from: self.archiveFile,
at: directoryIndex) else
{
return nil
}
let offset = UInt64(centralDirStruct.effectiveRelativeOffsetOfLocalHeader)
guard
let localFileHeader: LocalFileHeader = Data.readStruct(
from: self.archiveFile,
at: offset) else { return nil }
var dataDescriptor: DataDescriptor?
var zip64DataDescriptor: ZIP64DataDescriptor?
if centralDirStruct.usesDataDescriptor {
let additionalSize = UInt64(localFileHeader.fileNameLength) + UInt64(localFileHeader.extraFieldLength)
let isCompressed = centralDirStruct.compressionMethod != 0
let dataSize = isCompressed
? centralDirStruct.effectiveCompressedSize
: centralDirStruct.effectiveUncompressedSize
let descriptorPosition = offset + UInt64(LocalFileHeader.size) + additionalSize + dataSize
if centralDirStruct.isZIP64 {
zip64DataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
} else {
dataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
}
}
defer {
directoryIndex += UInt64(CentralDirectoryStructure.size)
directoryIndex += UInt64(centralDirStruct.fileNameLength)
directoryIndex += UInt64(centralDirStruct.extraFieldLength)
directoryIndex += UInt64(centralDirStruct.fileCommentLength)
index += 1
}
return ZipEntry(
centralDirectoryStructure: centralDirStruct,
localFileHeader: localFileHeader,
dataDescriptor: dataDescriptor,
zip64DataDescriptor: zip64DataDescriptor)
}
}
/// Retrieve the ZIP `Entry` with the given `path` from the receiver.
///
/// - Note: The ZIP file format specification does not enforce unique paths for entries.
/// Therefore an archive can contain multiple entries with the same path. This method
/// always returns the first `Entry` with the given `path`.
///
/// - Parameter path: A relative file path identifying the corresponding `Entry`.
/// - Returns: An `Entry` with the given `path`. Otherwise, `nil`.
subscript(path: String) -> ZipEntry? {
first { $0.path == path }
}
/// Read a ZIP `Entry` from the receiver and write it to `url`.
///
/// - Parameters:
/// - entry: The ZIP `Entry` to read.
/// - url: The destination file URL.
/// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed).
/// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`.
/// - Throws: An error if the destination file cannot be written or the entry contains malformed content.
func extract(_ entry: ZipEntry, to url: URL, bufferSize: Int = defaultReadChunkSize) throws -> UInt32 {
guard bufferSize > 0 else { throw ArchiveError.invalidBufferSize }
let fileManager = FileManager()
try fileManager.createParentDirectoryStructure(for: url)
let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard let destinationFile: FILEPointer = fopen(destinationRepresentation, "wb+") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(destinationFile) }
guard bufferSize > 0 else { throw ArchiveError.invalidBufferSize }
guard entry.dataOffset <= .max else { throw ArchiveError.invalidLocalHeaderDataOffset }
fseeko(archiveFile, off_t(entry.dataOffset), SEEK_SET)
let attributes = FileManager.attributes(from: entry)
try fileManager.setAttributes(attributes, ofItemAtPath: url.path)
let size = entry.centralDirectoryStructure.effectiveCompressedSize
guard size <= .max else { throw ArchiveError.invalidEntrySize }
return try Data.decompress(size: Int64(size), bufferSize: bufferSize, provider: { _, chunkSize -> Data in
try Data.readChunk(of: chunkSize, from: self.archiveFile)
}, consumer: { data in
_ = try Data.write(chunk: data, to: destinationFile)
})
}
// MARK: Private
private static func scanForZIP64EndOfCentralDirectory(in file: FILEPointer, eocdOffset: UInt64)
-> ZIP64EndOfCentralDirectory?
{
guard UInt64(ZIP64EndOfCentralDirectoryLocator.size) < eocdOffset else {
return nil
}
let locatorOffset = eocdOffset - UInt64(ZIP64EndOfCentralDirectoryLocator.size)
guard UInt64(ZIP64EndOfCentralDirectoryRecord.size) < locatorOffset else {
return nil
}
let recordOffset = locatorOffset - UInt64(ZIP64EndOfCentralDirectoryRecord.size)
guard
let locator: ZIP64EndOfCentralDirectoryLocator = Data.readStruct(from: file, at: locatorOffset),
let record: ZIP64EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: recordOffset) else
{
return nil
}
return ZIP64EndOfCentralDirectory(record: record, locator: locator)
}
}
// MARK: - Zip64
extension ZipArchive {
struct ZIP64EndOfCentralDirectory {
let record: ZIP64EndOfCentralDirectoryRecord
let locator: ZIP64EndOfCentralDirectoryLocator
}
struct ZIP64EndOfCentralDirectoryRecord: DataSerializable {
let zip64EOCDRecordSignature = UInt32(zip64EOCDRecordStructSignature)
let sizeOfZIP64EndOfCentralDirectoryRecord: UInt64
let versionMadeBy: UInt16
let versionNeededToExtract: UInt16
let numberOfDisk: UInt32
let numberOfDiskStart: UInt32
let totalNumberOfEntriesOnDisk: UInt64
let totalNumberOfEntriesInCentralDirectory: UInt64
let sizeOfCentralDirectory: UInt64
let offsetToStartOfCentralDirectory: UInt64
let zip64ExtensibleDataSector: Data
static let size = 56
}
struct ZIP64EndOfCentralDirectoryLocator: DataSerializable {
let zip64EOCDLocatorSignature = UInt32(zip64EOCDLocatorStructSignature)
let numberOfDiskWithZIP64EOCDRecordStart: UInt32
let relativeOffsetOfZIP64EOCDRecord: UInt64
let totalNumberOfDisk: UInt32
static let size = 20
}
static let zip64EOCDRecordStructSignature = 0x06064b50
static let zip64EOCDLocatorStructSignature = 0x07064b50
}
extension ZipArchive.ZIP64EndOfCentralDirectoryRecord {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider _: (Int) throws -> Data) {
guard data.count == ZipArchive.ZIP64EndOfCentralDirectoryRecord.size else { return nil }
guard data.scanValue(start: 0) == zip64EOCDRecordSignature else { return nil }
sizeOfZIP64EndOfCentralDirectoryRecord = data.scanValue(start: 4)
versionMadeBy = data.scanValue(start: 12)
versionNeededToExtract = data.scanValue(start: 14)
// Version Needed to Extract: 4.5 - File uses ZIP64 format extensions
guard versionNeededToExtract >= 45 else { return nil }
numberOfDisk = data.scanValue(start: 16)
numberOfDiskStart = data.scanValue(start: 20)
totalNumberOfEntriesOnDisk = data.scanValue(start: 24)
totalNumberOfEntriesInCentralDirectory = data.scanValue(start: 32)
sizeOfCentralDirectory = data.scanValue(start: 40)
offsetToStartOfCentralDirectory = data.scanValue(start: 48)
zip64ExtensibleDataSector = Data()
}
init(
record: ZipArchive.ZIP64EndOfCentralDirectoryRecord,
numberOfEntriesOnDisk: UInt64,
numberOfEntriesInCD: UInt64,
sizeOfCentralDirectory: UInt64,
offsetToStartOfCD: UInt64)
{
sizeOfZIP64EndOfCentralDirectoryRecord = record.sizeOfZIP64EndOfCentralDirectoryRecord
versionMadeBy = record.versionMadeBy
versionNeededToExtract = record.versionNeededToExtract
numberOfDisk = record.numberOfDisk
numberOfDiskStart = record.numberOfDiskStart
totalNumberOfEntriesOnDisk = numberOfEntriesOnDisk
totalNumberOfEntriesInCentralDirectory = numberOfEntriesInCD
self.sizeOfCentralDirectory = sizeOfCentralDirectory
offsetToStartOfCentralDirectory = offsetToStartOfCD
zip64ExtensibleDataSector = record.zip64ExtensibleDataSector
}
// MARK: Internal
var data: Data {
var zip64EOCDRecordSignature = zip64EOCDRecordSignature
var sizeOfZIP64EOCDRecord = sizeOfZIP64EndOfCentralDirectoryRecord
var versionMadeBy = versionMadeBy
var versionNeededToExtract = versionNeededToExtract
var numberOfDisk = numberOfDisk
var numberOfDiskStart = numberOfDiskStart
var totalNumberOfEntriesOnDisk = totalNumberOfEntriesOnDisk
var totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var sizeOfCD = sizeOfCentralDirectory
var offsetToStartOfCD = offsetToStartOfCentralDirectory
var data = Data()
withUnsafePointer(to: &zip64EOCDRecordSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfZIP64EOCDRecord) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionMadeBy) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &versionNeededToExtract) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesOnDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesInCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetToStartOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(zip64ExtensibleDataSector)
return data
}
}
extension ZipArchive.ZIP64EndOfCentralDirectoryLocator {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider _: (Int) throws -> Data) {
guard data.count == ZipArchive.ZIP64EndOfCentralDirectoryLocator.size else { return nil }
guard data.scanValue(start: 0) == zip64EOCDLocatorSignature else { return nil }
numberOfDiskWithZIP64EOCDRecordStart = data.scanValue(start: 4)
relativeOffsetOfZIP64EOCDRecord = data.scanValue(start: 8)
totalNumberOfDisk = data.scanValue(start: 16)
}
// MARK: Internal
var data: Data {
var zip64EOCDLocatorSignature = zip64EOCDLocatorSignature
var numberOfDiskWithZIP64EOCD = numberOfDiskWithZIP64EOCDRecordStart
var offsetOfZIP64EOCDRecord = relativeOffsetOfZIP64EOCDRecord
var totalNumberOfDisk = totalNumberOfDisk
var data = Data()
withUnsafePointer(to: &zip64EOCDLocatorSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskWithZIP64EOCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetOfZIP64EOCDRecord) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
return data
}
}
extension ZipArchive.EndOfCentralDirectoryRecord {
// MARK: Lifecycle
init?(data: Data, additionalDataProvider provider: (Int) throws -> Data) {
guard data.count == ZipArchive.EndOfCentralDirectoryRecord.size else { return nil }
guard data.scanValue(start: 0) == endOfCentralDirectorySignature else { return nil }
numberOfDisk = data.scanValue(start: 4)
numberOfDiskStart = data.scanValue(start: 6)
totalNumberOfEntriesOnDisk = data.scanValue(start: 8)
totalNumberOfEntriesInCentralDirectory = data.scanValue(start: 10)
sizeOfCentralDirectory = data.scanValue(start: 12)
offsetToStartOfCentralDirectory = data.scanValue(start: 16)
zipFileCommentLength = data.scanValue(start: 20)
guard let commentData = try? provider(Int(zipFileCommentLength)) else { return nil }
guard commentData.count == Int(zipFileCommentLength) else { return nil }
zipFileCommentData = commentData
}
// MARK: Internal
var data: Data {
var endOfCDSignature = endOfCentralDirectorySignature
var numberOfDisk = numberOfDisk
var numberOfDiskStart = numberOfDiskStart
var totalNumberOfEntriesOnDisk = totalNumberOfEntriesOnDisk
var totalNumberOfEntriesInCD = totalNumberOfEntriesInCentralDirectory
var sizeOfCentralDirectory = sizeOfCentralDirectory
var offsetToStartOfCD = offsetToStartOfCentralDirectory
var zipFileCommentLength = zipFileCommentLength
var data = Data()
withUnsafePointer(to: &endOfCDSignature) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &numberOfDiskStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesOnDisk) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &totalNumberOfEntriesInCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &sizeOfCentralDirectory) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &offsetToStartOfCD) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
withUnsafePointer(to: &zipFileCommentLength) { data.append(UnsafeBufferPointer(start: $0, count: 1)) }
data.append(zipFileCommentData)
return data
}
}
|
39f23b7261d4b098feea5012a4134b18
| 42.683544 | 112 | 0.750797 | false | false | false | false |
khizkhiz/swift
|
refs/heads/master
|
test/SourceKit/CodeFormat/indent-basic.swift
|
apache-2.0
|
1
|
class Foo {
var test : Int
func foo() {
test = 1
}
}
func foo(a a: [Int: Int]) {}
foo(a: [
3: 3
])
// RUN: %sourcekitd-test -req=format -line=1 -length=1 %s >%t.response
// RUN: %sourcekitd-test -req=format -line=2 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=3 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=4 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=5 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=6 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=7 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=8 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=9 -length=1 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=13 -length=1 %s >>%t.response
// RUN: FileCheck --strict-whitespace %s <%t.response
// CHECK: key.sourcetext: "class Foo {"
// CHECK: key.sourcetext: " "
// CHECK: key.sourcetext: " var test : Int"
// CHECK: key.sourcetext: " "
// CHECK: key.sourcetext: " func foo() {"
// CHECK: key.sourcetext: " test = 1"
// CHECK: key.sourcetext: " }"
// CHECK: key.sourcetext: " "
// CHECK: key.sourcetext: "}"
// "foo(a: ["
// CHECK: key.sourcetext: " 3: 3"
|
6aa7c37bef40c135364efee0c9722077
| 33.394737 | 72 | 0.601377 | false | true | false | false |
haibtdt/FileTransfer
|
refs/heads/master
|
FileTransfer/DownloadTaskTracker.swift
|
mit
|
1
|
//
// DownloadTaskTracker.swift
// FileTransfer
//
// Created by Bui Hai on 10/11/15.
// Copyright © 2015 Hai Bui. All rights reserved.
//
import UIKit
protocol DownloadTaskTrackerObserver : class {
func downloadTaskMetaDataChanged (task: DownloadTask, tracker : DownloadTaskTracker)
}
/// Maintain download task's status
class DownloadTaskTracker : DownloadTaskObserver {
var downloadTask : DownloadTask? = nil
var downloadTaskMetaData : DownloadTaskMetaData? = nil
weak var trackerObserver : DownloadTaskTrackerObserver? = nil
init(task: DownloadTask, meta : DownloadTaskMetaData) {
downloadTask = task
downloadTaskMetaData = meta
task.observer = self
}
func taskStarted(task : DownloadTask) {
downloadTaskMetaData?.status = NSNumber(integer: TaskStatus.InProgress.rawValue)
trackerObserver?.downloadTaskMetaDataChanged(task, tracker: self)
}
func taskDone(task : DownloadTask) {
downloadTaskMetaData?.status = NSNumber(integer: TaskStatus.Done.rawValue)
trackerObserver?.downloadTaskMetaDataChanged(task, tracker: self)
}
func taskFailed(task : DownloadTask) {
downloadTaskMetaData?.status = NSNumber(integer: TaskStatus.Failed.rawValue)
trackerObserver?.downloadTaskMetaDataChanged(task, tracker: self)
}
}
|
cd730020cd0e567ef95135d4b69ab815
| 23.813559 | 88 | 0.665984 | false | false | false | false |
appcodev/Let-Swift-Code
|
refs/heads/master
|
BeyondTheBasic-Swift/BeyondTheBasic-Swift/main.swift
|
apache-2.0
|
1
|
//
// main.swift
// BeyondTheBasic-Swift
//
// Created by Chalermchon Samana on 6/6/14.
// Copyright (c) 2014 Onzondev Innovation Co., Ltd. All rights reserved.
//
import Foundation
println("Beyond the Basic")
var dic = ["A":"123","B":"122"]
let c:String? = dic["C"]
//let c = dic["C"]
//print(c)
//Unwrapping an Optional
if let cValue = c {
println(cValue)
}else{
println("c is nil")
}
let numberOfLegs = ["ant":6, "snake":0, "cheetah":4, "big":1]
//ถ้าเราดึงค่าของ key ที่ไม่มีอยู่ใน dictionary จะเกิดอะไรขึ้น?
println(numberOfLegs["dog"])
//output nil
//Querying an Optional
let possibleLegCount: Int? = numberOfLegs["dogg"]
println(possibleLegCount)
//output nil
if possibleLegCount == nil {
println("Not found")
}else {
let legCount: Int = possibleLegCount!
println(legCount)
}
/////// ? และ ! คืออะไร ใช้อย่างไร
//ลดการเขียนโค้ดจากด้านบน
if possibleLegCount {
let legCount = possibleLegCount!
println(legCount)
}
//Unwrapping an Optional
if let legCount = possibleLegCount {
println(legCount)
}
//IF Statement
var legCount = numberOfLegs["big"]
if legCount == 0 { //จะใช้แบบ if(legCount==0) ก็ได้
println("It slithers and slides around")
}else {
println("It walks")
}
//It walks
//More Complex If Statements
if legCount == 0 { //จะใช้แบบ if(legCount==0) ก็ได้
println("It slithers and slides around")
}else if legCount == 1 {
println("It hops")
}else {
println("It walks")
}
//It hops
//if-statement enum
enum Day {
case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
let myDay = Day.Monday
let yourDay = Day.Monday
if myDay == yourDay {
println("Same")
}else {
println("Difference")
}
let myName = "Swift"
if myName == "Swift" {
println("Equal")
}else{
println("Not Equal")
}
//Equal
//Switch
switch legCount! {
case 0:
println("It slither and slides around")
case "1":
println("It hop 1")
println("It hop 2")
println("It hop 3")
println("It hop 4")
case 1:
println("It hop 1 number")
println("It hop 2 number")
println("It hop 3 number")
default:
println("It walks")
}
/*
It hop 1 number
It hop 2 number
It hop 3 number
*/
//switch ต้องมี default ตลอดไม่ยังนั้นจะคอมไพล์ไม่ผ่าน error: switch muct be exhaustive [safe]
//switch สามารถเปรียบเทียบตัวแปรที่เป็น Object Class ก็ได้
//switch ใช้ กับจำนวนหรือ Object หลายๆ อันได้
var letter = "5K"
switch letter {
case "1","0",0:
println("member in 1 0 0")
case "5","5K",5:
println("member in 5 5K 5")
default:
println("not member")
}
//member in 5 5K 5
let myDay2 = Day.Friday
switch myDay2 {
case Day.Monday:
println("On Monday")
case Day.Tuesday:
println("On Tuesday")
case Day.Wednesday:
println("On Wednesday")
case Day.Thursday:
println("On Thursday")
case Day.Friday:
println("On Friday")
case Day.Saturday:
println("On Saturday")
case Day.Sunday:
println("On Sunday")
// default:
// println("On otherday")
}
println(myDay2)
//On Friday
//Matching Value Range
let myScore = 80
switch myScore {
case 80...100:
println("get A")
case 70..80:
println("get B")
case 60..70:
println("get C")
case 50..60:
println("get D")
default:
println("get E")
}
//49.0001 => get D
//49.0 => get E
//** การอัพเดทของ Range อัพเดทเป็นตัวเลขจำนวนเต็ม เท่านั้น
//Function
func sayHello(){
println("Hello")
}
//call
sayHello()
//Hello
func sayHello(name:String){
println("Hello \(name)")
}
sayHello("Let Swift")
//Hello Let Swift
//Returning Values
func buildGreeting(name:String = "Let Swift") -> String {
return "Hi! " + name
}
let greeting = buildGreeting()
let greet:String = buildGreeting(name:"Toa")//เวลาจะใส่พารามิเตอร์ ต้องใส่ชื่ออากูเมนลงไปด้วย
println("\(greeting) | \(greet)")
//Hi! Let Swift | Hi! Toa
//Tuples
//Tuples นี้สามารถเอามาเป็นค่าที่จะ return ออกไปได้ จะทำให้เราสามารถ return ออกไปได้หลายค่านั้นเอง
/*
(3.4,3.5,4.3) //(Double, Double, Double)
(404,"Not Found") //(Int, String)
(2,"banana",0.99) //(Int, String, Double)
*/
//Returning Multiple Values
func refreshWebPage() -> (code:Int, message:String) {
//...
return (404,"Not Found")
}
//Decomposition a Tuples
//var (code,desc) = refreshWebPage()
var (code:Int,desc:String) = refreshWebPage()
println("-- \(code) \(desc)")
//-- 404 Not Found
//ประกาศตัวแปรมารับค่า ค่าที่ return จาก tuples จะต้องใส่ชื่อในตัวแปรด้วยจะได้เรียกใช้ผ่านชื่อนั้นได้
let status = refreshWebPage()
println("received \(status.code) \(status.message)")
//received 404 Not Found
//Tuple Decomposition for Enumeration
let numbers = ["A":5, "B":19, "C":90]
for (alphabet,number) in numbers {
println("\(alphabet) ->> \(number)")
}
/*
output
C ->> 90
A ->> 5
B ->> 19
*/
//Closures
let greetingPrinter = {
println("Let Swift!")
}
//Closures จะคล้ายกับการประกาศฟังก์ชั่น ดังนั้นเวลาเรียกใช้จึงเรียกเหมือนฟังก์ชั่น ไม่ใช่เรียกเป็นตัวแปร
/*
let greetingPrinter: ()->() = {
}
same
func greetingPrinter() -> (){
}
*/
greetingPrinter()
//Let Swift!
//Closures as Parameters
//การส่งค่า Closures ไปเป็นพารามิเตอร์ของฟังก์ชั่น
func repeat(count: Int, task: ()->()) {
for i in 0..count {
task()
}
}
repeat(4,{
println("Hello!!")
});
/*
Hello!!
Hello!!
Hello!!
Hello!!
*/
//Closure ใช้ประโยชน์อย่างไรบ้าง Closure มีพารามิเตอร์ได้มั้ย มีรูปแบบอย่างไรหากมีพารามิเตอร์ ใช้งานอย่างไร
|
94cff56fdc0f17537b484fa224d6a4d1
| 18.64539 | 107 | 0.626715 | false | false | false | false |
D8Ge/Jchat
|
refs/heads/master
|
Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/Google_Protobuf_Timestamp_Extensions.swift
|
mit
|
1
|
// ProtobufRuntime/Sources/Protobuf/Google_Protobuf_Timestamp_Extensions.swift - Timestamp extensions
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// Extend the generated Timestamp message with customized JSON coding,
/// arithmetic operations, and convenience methods.
///
// -----------------------------------------------------------------------------
import Swift
// TODO: Add convenience methods to interoperate with standard
// date/time classes: an initializer that accepts Unix timestamp as
// Int or Double, an easy way to convert to/from Foundation's
// NSDateTime (on Apple platforms only?), others?
private func FormatInt(n: Int32, digits: Int) -> String {
if n < 0 {
return FormatInt(n: -n, digits: digits)
} else if digits <= 0 {
return ""
} else if digits == 1 && n < 10 {
return ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][Int(n)]
} else {
return FormatInt(n: n / 10, digits: digits - 1) + ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][Int(n % 10)]
}
}
private func fromAscii2(_ digit0: Int, _ digit1: Int) throws -> Int {
let zero = Int(48)
let nine = Int(57)
if digit0 < zero || digit0 > nine || digit1 < zero || digit1 > nine {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return digit0 * 10 + digit1 - 528
}
private func fromAscii4(_ digit0: Int, _ digit1: Int, _ digit2: Int, _ digit3: Int) throws -> Int {
let zero = Int(48)
let nine = Int(57)
if (digit0 < zero || digit0 > nine
|| digit1 < zero || digit1 > nine
|| digit2 < zero || digit2 > nine
|| digit3 < zero || digit3 > nine) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return digit0 * 1000 + digit1 * 100 + digit2 * 10 + digit3 - 53328
}
// Parse an RFC3339 timestamp into a pair of seconds-since-1970 and nanos.
private func parseTimestamp(s: String) throws -> (Int64, Int32) {
// Convert to an array of integer character values
let value = s.utf8.map{Int($0)}
if value.count < 20 {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Since the format is fixed-layout, we can just decode
// directly as follows.
let zero = Int(48)
let nine = Int(57)
let dash = Int(45)
let colon = Int(58)
let plus = Int(43)
let letterT = Int(84)
let letterZ = Int(90)
let period = Int(46)
// Year: 4 digits followed by '-'
let year = try fromAscii4(value[0], value[1], value[2], value[3])
if value[4] != dash || year < Int(1) || year > Int(9999) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Month: 2 digits followed by '-'
let month = try fromAscii2(value[5], value[6])
if value[7] != dash || month < Int(1) || month > Int(12) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Day: 2 digits followed by 'T'
let mday = try fromAscii2(value[8], value[9])
if value[10] != letterT || mday < Int(1) || mday > Int(31) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Hour: 2 digits followed by ':'
let hour = try fromAscii2(value[11], value[12])
if value[13] != colon || hour > Int(23) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Minute: 2 digits followed by ':'
let minute = try fromAscii2(value[14], value[15])
if value[16] != colon || minute > Int(59) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Second: 2 digits (following char is checked below)
let second = try fromAscii2(value[17], value[18])
if second > Int(61) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// timegm() is almost entirely useless. It's nonexistent on
// some platforms, broken on others. Everything else I've tried
// is even worse. Hence the code below.
// (If you have a better way to do this, try it and see if it
// passes the test suite on both Linux and OS X.)
// Day of year
let mdayStart: [Int] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
var yday = Int64(mdayStart[month - 1])
let isleap = (year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))
if isleap && (month > 2) {
yday += 1
}
yday += Int64(mday - 1)
// Days since start of epoch (including leap days)
var daysSinceEpoch = yday
daysSinceEpoch += Int64(365 * year) - Int64(719527)
daysSinceEpoch += Int64((year - 1) / 4)
daysSinceEpoch -= Int64((year - 1) / 100)
daysSinceEpoch += Int64((year - 1) / 400)
// Second within day
var daySec = Int64(hour)
daySec *= 60
daySec += Int64(minute)
daySec *= 60
daySec += Int64(second)
// Seconds since start of epoch
let t = daysSinceEpoch * Int64(86400) + daySec
// After seconds, comes various optional bits
var pos = 19
var nanos: Int32 = 0
if value[pos] == period { // "." begins fractional seconds
pos += 1
var digitValue = 100000000
while pos < value.count && value[pos] >= zero && value[pos] <= nine {
nanos += digitValue * (value[pos] - zero)
digitValue /= 10
pos += 1
}
}
var seconds: Int64 = 0
if value[pos] == plus || value[pos] == dash { // "+" or "-" starts Timezone offset
if pos + 6 > value.count {
throw ProtobufDecodingError.malformedJSONTimestamp
}
let hourOffset = try fromAscii2(value[pos + 1], value[pos + 2])
let minuteOffset = try fromAscii2(value[pos + 4], value[pos + 5])
if hourOffset > Int(13) || minuteOffset > Int(59) || value[pos + 3] != colon {
throw ProtobufDecodingError.malformedJSONTimestamp
}
var adjusted: Int64 = t
if value[pos] == plus {
adjusted -= Int64(hourOffset) * Int64(3600)
adjusted -= Int64(minuteOffset) * Int64(60)
} else {
adjusted += Int64(hourOffset) * Int64(3600)
adjusted += Int64(minuteOffset) * Int64(60)
}
if adjusted < -62135596800 || adjusted > 253402300799 {
throw ProtobufDecodingError.malformedJSONTimestamp
}
seconds = adjusted
pos += 6
} else if value[pos] == letterZ { // "Z" indicator for UTC
seconds = t
pos += 1
} else {
throw ProtobufDecodingError.malformedJSONTimestamp
}
if pos != value.count {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return (seconds, nanos)
}
private func formatTimestamp(seconds: Int64, nanos: Int32) -> String? {
if ((seconds < 0 && nanos > 0)
|| (seconds > 0 && nanos < 0)
|| (seconds < -62135596800)
|| (seconds == -62135596800 && nanos < 0)
|| (seconds >= 253402300800)) {
return nil
}
// Can't just use gmtime() here because time_t is sometimes 32 bits. Ugh.
let secondsSinceStartOfDay = (Int32(seconds % 86400) + 86400) % 86400
let sec = secondsSinceStartOfDay % 60
let min = (secondsSinceStartOfDay / 60) % 60
let hour = secondsSinceStartOfDay / 3600
// The following implements Richards' algorithm (see the Wikipedia article
// for "Julian day").
// If you touch this code, please test it exhaustively by playing with
// Test_Timestamp.testJSON_range.
let julian = (seconds + 210866803200) / 86400
let f = julian + 1401 + (((4 * julian + 274277) / 146097) * 3) / 4 - 38
let e = 4 * f + 3
let g = e % 1461 / 4
let h = 5 * g + 2
let mday = Int32(h % 153 / 5 + 1)
let month = (h / 153 + 2) % 12 + 1
let year = e / 1461 - 4716 + (12 + 2 - month) / 12
// We can't use strftime here (it varies with locale)
// We can't use strftime_l here (it's not portable)
// The following is crude, but it works.
// TODO: If String(format:) works, that might be even better
// (it was broken on Linux a while back...)
let result = (FormatInt(n: Int32(year), digits: 4)
+ "-"
+ FormatInt(n: Int32(month), digits: 2)
+ "-"
+ FormatInt(n: mday, digits: 2)
+ "T"
+ FormatInt(n: hour, digits: 2)
+ ":"
+ FormatInt(n: min, digits: 2)
+ ":"
+ FormatInt(n: sec, digits: 2))
if nanos == 0 {
return "\(result)Z"
} else {
var digits: Int
var fraction: Int
if nanos % 1000000 == 0 {
fraction = Int(nanos) / 1000000
digits = 3
} else if nanos % 1000 == 0 {
fraction = Int(nanos) / 1000
digits = 6
} else {
fraction = Int(nanos)
digits = 9
}
var formatted_fraction = ""
while digits > 0 {
formatted_fraction = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][fraction % 10] + formatted_fraction
fraction /= 10
digits -= 1
}
return "\(result).\(formatted_fraction)Z"
}
}
public extension Google_Protobuf_Timestamp {
public init(secondsSinceEpoch: Int64, nanos: Int32 = 0) {
self.init()
self.seconds = secondsSinceEpoch
self.nanos = nanos
}
public mutating func decodeFromJSONToken(token: ProtobufJSONToken) throws {
if case .string(let s) = token {
let timestamp = try parseTimestamp(s: s)
seconds = timestamp.0
nanos = timestamp.1
} else {
throw ProtobufDecodingError.schemaMismatch
}
}
public func serializeJSON() throws -> String {
let s = seconds
let n = nanos
if let formatted = formatTimestamp(seconds: s, nanos: n) {
return "\"\(formatted)\""
} else {
throw ProtobufEncodingError.timestampJSONRange
}
}
func serializeAnyJSON() throws -> String {
let value = try serializeJSON()
return "{\"@type\":\"\(anyTypeURL)\",\"value\":\(value)}"
}
}
private func normalizedTimestamp(seconds: Int64, nanos: Int32) -> Google_Protobuf_Timestamp {
var s = seconds
var n = nanos
if n >= 1000000000 || n <= -1000000000 {
s += Int64(n) / 1000000000
n = n % 1000000000
}
if s > 0 && n < 0 {
n += 1000000000
s -= 1
} else if s < 0 && n > 0 {
n -= 1000000000
s += 1
}
return Google_Protobuf_Timestamp(seconds: s, nanos: n)
}
public func -(lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration) -> Google_Protobuf_Timestamp {
return normalizedTimestamp(seconds: lhs.seconds - rhs.seconds, nanos: lhs.nanos - rhs.nanos)
}
public func+(lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration) -> Google_Protobuf_Timestamp {
return normalizedTimestamp(seconds: lhs.seconds + rhs.seconds, nanos: lhs.nanos + rhs.nanos)
}
|
28d5c26f4d3e82821887ad1dc398b1c9
| 33.84472 | 122 | 0.580481 | false | false | false | false |
liuweihaocool/iOS_06_liuwei
|
refs/heads/master
|
新浪微博_swift/新浪微博_swift/class/Main/Compare/Controller/LWCompareController.swift
|
apache-2.0
|
1
|
//
// LWCompareController.swift
// 新浪微博_swift
//
// Created by LiuWei on 15/12/5.
// Copyright © 2015年 liuwei. All rights reserved.
//
import UIKit
class LWCompareController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 设置viw的背景颜色
view.backgroundColor = UIColor(white: 0.5, alpha: 1)
// 设置导航栏
prepareUI()
}
/// 准备UI
private func prepareUI() {
/// 导航栏
setupNavigationBar()
/// 文本框
setupTextView()
/// 工具条
setupToolBar()
}
/// 设置文本
func setupTextView() {
/// 添加子控制器
view.addSubview(textView)
/// 去除系统的约束
textView.translatesAutoresizingMaskIntoConstraints = false
/// 自定义约束
view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0))
// 设置代理来监听文本的改变
textView.delegate = self
}
/// 设置导航栏按钮
private func setupNavigationBar(){
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "closeWindow")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendMessage")
setupTitle()
// 设置发送按钮不可用
navigationItem.rightBarButtonItem?.enabled = false
}
/// 设置导航栏标题
private func setupTitle(){
if let name = LWUserAccount.loadUserAccount()?.screen_name {
// 创建label
let label = UILabel()
// 设置字体
label.font = UIFont.systemFontOfSize(14)
// 设置文字
label.text = name + "\n" + "发送的微博"
// 设置字体颜色
label.textColor = UIColor.redColor()
// 换行
label.numberOfLines = 0
let attText = NSMutableAttributedString(string: label.text!)
let nameRange = (name as NSString).rangeOfString(name)
attText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: nameRange)
label.attributedText = attText
label.textAlignment = NSTextAlignment.Center
// 适应大小
label.sizeToFit()
// 为title赋值
navigationItem.titleView = label
} else {
navigationItem.title = "发送微博"
}
}
/// 关闭控制器 @obj修饰 private
@objc private func closeWindow() {
dismissViewControllerAnimated(true, completion: nil)
}
/// 发送微博的实现
@objc private func sendMessage() {
print("发送微博")
}
// private lazy var textView:LWPlaceholdView = {
// // 实例化对象
// let textView = LWPlaceholdView()
// // 设置背景颜色
// textView.backgroundColor = UIColor.lightTextColor()
// // 字体
// textView.font = UIFont.systemFontOfSize(20)
//// // 滚动条
// textView.alwaysBounceVertical = true
//
//
// let placeHolderLabel = UILabel()
//
// placeHolderLabel.textColor = UIColor.lightTextColor()
// placeHolderLabel.font = textView.font
//
// placeHolderLabel.text = "分享新鲜事"
//
// placeHolderLabel.sizeToFit()
//
//
////
//// // 拖拽的时候会 退出键盘
// textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
////
//// // 站位文本
//
//
// return textView
// }()
private lazy var textView:LWPlaceholdView = {
let tv = LWPlaceholdView()
tv.backgroundColor = UIColor.brownColor()
tv.alwaysBounceVertical = true
tv.placeholder = "分享新鲜事"
return tv
}()
private func setupToolBar() {
/// 添加toolbar到 view
view.addSubview(toolBar)
/// 去掉系统的自动约束
toolBar.translatesAutoresizingMaskIntoConstraints = false
// 约束 X轴
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
// 约束 Y轴
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
// 约束宽度
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
// 约束高度
view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 44))
// 添加item对应的图片名称
let itemSettings = [["imageName":"compose_toolbar_picture","action":"picture"],
["imageName":"compose_trendbutton_background","action":"trend"],
["imageName":"compose_mentionbutton_background","action":"mention"],
["imageName":"compose_emoticonbutton_background","action":"emotion"],
["imageName":"compose_addbutton_background","action":"add"]]
// 存放UIBarButtonItem
var items = [UIBarButtonItem]()
// 通过for循环遍历数组的图片名称
for dict in itemSettings {
let imageName = dict["imageName"]
let item = UIBarButtonItem(image: imageName!)
let action = dict["action"]
// 获取UIBarbutton的customView 是一个按钮
let button = item.customView as! UIButton
// 添加点击事件
button.addTarget(self, action: Selector(action!), forControlEvents: UIControlEvents.TouchUpInside)
// 填加到数组
items.append(item)
// 添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
}
items.removeLast()
toolBar.items = items
}
/// 懒加载
private lazy var toolBar:UIToolbar = {
// 实例化uitoolBar
let tool = UIToolbar()
tool.backgroundColor = UIColor.redColor()
return tool
}()
func picture() {
print("fff")
}
func trend() {
print("fff")
}
func mention() {
print("fff")
}
func emotion() {
print("fff")
}
func add() {
print("fff")
}
}
// 扩展当前控制器 实现UItextViewDelegate 来监听文本值得改变
extension LWCompareController:UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
// 设置导航栏右边按钮的状态
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
}
}
|
a5ac16e30d15fda21f62c587f4988a57
| 33.436937 | 222 | 0.607325 | false | false | false | false |
blinker13/Geometry
|
refs/heads/main
|
Sources/Primitives/Angle.swift
|
mit
|
1
|
public struct Angle : Arithmetic, Codable, Comparable {
@usableFromInline internal let rawValue: Scalar
@usableFromInline internal init(_ value: Scalar) {
rawValue = value
}
}
// MARK: -
public extension Angle {
@inlinable static var zero: Self { .radians(.zero) }
@inlinable static var half: Self { .radians(.pi) }
@inlinable static var full: Self { .radians(.pi * 2) }
@inlinable static prefix func - (value: Self) -> Self { .init(value.rawValue) }
@inlinable static func + (left: Self, right: Self) -> Self { .init(left.rawValue + right.rawValue) }
@inlinable static func - (left: Self, right: Self) -> Self { .init(left.rawValue - right.rawValue) }
@inlinable static func * (left: Self, right: Self) -> Self { .init(left.rawValue * right.rawValue) }
@inlinable static func / (left: Self, right: Self) -> Self { .init(left.rawValue / right.rawValue) }
@inlinable static func < (left: Self, right: Self) -> Bool { left.rawValue < right.rawValue }
@inlinable static func degrees(_ value: Scalar) -> Self { .init(degrees: value) }
@inlinable static func radians(_ value: Scalar) -> Self { .init(radians: value) }
@inlinable var degrees: Scalar { rawValue * 180.0 / .pi }
@inlinable var radians: Scalar { rawValue }
@inlinable init(degrees: Scalar) { rawValue = degrees / 180.0 * .pi }
@inlinable init(radians: Scalar) { rawValue = radians }
@inlinable init(from decoder: Decoder) throws {
rawValue = try Scalar(from: decoder)
}
@inlinable func encode(to encoder: Encoder) throws {
try rawValue.encode(to: encoder)
}
@inlinable func rounded(_ rule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Self {
.init(rawValue.rounded(rule))
}
}
|
1d3ef850cc5e69f326c1a55fd917c3cb
| 34.270833 | 101 | 0.691081 | false | false | false | false |
aiwalle/LiveProject
|
refs/heads/master
|
LiveProject/Rank/Controller/LJWeeklyRankViewController.swift
|
mit
|
1
|
//
// LJWeeklyRankViewController.swift
// LiveProject
//
// Created by liang on 2017/10/26.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
let kLJWeeklyRankViewCell = "LJWeeklyRankViewCell"
class LJWeeklyRankViewController: LJDetailRankViewController {
fileprivate lazy var weeklyRankVM: LJWeeklyRankViewModel = LJWeeklyRankViewModel()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "LJWeeklyRankViewCell", bundle: nil), forCellReuseIdentifier: kLJWeeklyRankViewCell)
}
override init(rankType: LJRankType) {
super.init(rankType: rankType)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LJWeeklyRankViewController {
override func loadData() {
weeklyRankVM.loadWeeklyRankData(rankType) {
self.tableView.reloadData()
}
}
}
extension LJWeeklyRankViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return weeklyRankVM.weeklyRanks.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weeklyRankVM.weeklyRanks[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kLJWeeklyRankViewCell) as! LJWeeklyRankViewCell
cell.weekly = weeklyRankVM.weeklyRanks[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "主播周星榜" : "富豪周星榜"
}
}
|
527fa0f7f724aa85fb1fe203f59c00d5
| 27.677419 | 126 | 0.699663 | false | false | false | false |
flodolo/firefox-ios
|
refs/heads/main
|
Client/SiteImageHelper.swift
|
mpl-2.0
|
2
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import LinkPresentation
import Shared
import Storage
enum SiteImageType: Int {
case heroImage = 0, favicon
func peek() -> Self? {
return SiteImageType(rawValue: rawValue + 1)
}
mutating func next() -> Self? {
return SiteImageType(rawValue: rawValue + 1)
}
}
protocol SiteImageHelperProtocol {
func fetchImageFor(site: Site,
imageType: SiteImageType,
shouldFallback: Bool,
metadataProvider: LPMetadataProvider,
completion: @escaping (UIImage?) -> Void)
}
extension SiteImageHelperProtocol {
func fetchImageFor(site: Site,
imageType: SiteImageType,
shouldFallback: Bool,
metadataProvider: LPMetadataProvider = LPMetadataProvider(),
completion: @escaping (UIImage?) -> Void) {
self.fetchImageFor(site: site,
imageType: imageType,
shouldFallback: shouldFallback,
metadataProvider: metadataProvider,
completion: completion)
}
}
/// A helper that'll fetch an image, and fallback to other image options if specified.
class SiteImageHelper: SiteImageHelperProtocol {
private static let cache = NSCache<NSString, UIImage>()
private let throttler = Throttler(seconds: 0.5, on: DispatchQueue.main)
private let faviconFetcher: Favicons
convenience init(profile: Profile) {
self.init(faviconFetcher: profile.favicons)
}
init(faviconFetcher: Favicons) {
self.faviconFetcher = faviconFetcher
}
/// Given a `Site`, this will fetch the type of image you're looking for while allowing you to fallback to the next `SiteImageType`.
/// - Parameters:
/// - site: The site to fetch an image from.
/// - imageType: The `SiteImageType` that will work for you.
/// - shouldFallback: Allow a fallback image to be given in the case where the `SiteImageType` you specify is not available.
/// - metadataProvider: Metadata provider for hero image type. Default is normally used, replaced in case of tests
/// - completion: Work to be done after fetching an image, ideally done on the main thread.
/// - Returns: A UIImage.
func fetchImageFor(site: Site,
imageType: SiteImageType,
shouldFallback: Bool,
metadataProvider: LPMetadataProvider = LPMetadataProvider(),
completion: @escaping (UIImage?) -> Void) {
var didCompleteFetch = false
var imageType = imageType
switch imageType {
case .heroImage:
fetchHeroImage(for: site, metadataProvider: metadataProvider) { image, result in
guard let heroImage = image else { return }
didCompleteFetch = result ?? false
DispatchQueue.main.async {
completion(heroImage)
return
}
}
case .favicon:
fetchFavicon(for: site) { image, result in
guard let favicon = image else { return }
didCompleteFetch = result ?? false
DispatchQueue.main.async {
completion(favicon)
return
}
}
}
throttler.throttle { [weak self] in
if !didCompleteFetch && imageType.peek() != nil,
let updatedImageType = imageType.next(), shouldFallback {
self?.fetchImageFor(site: site,
imageType: updatedImageType,
shouldFallback: shouldFallback,
completion: completion)
} else { return }
}
}
static func clearCacheData() {
SiteImageHelper.cache.removeAllObjects()
}
// MARK: - Private
private func fetchHeroImage(for site: Site, metadataProvider: LPMetadataProvider, completion: @escaping (UIImage?, Bool?) -> Void) {
let heroImageCacheKey = NSString(string: "\(site.url)\(SiteImageType.heroImage.rawValue)")
// Fetch from cache, if not then fetch with LPMetadataProvider
if let cachedImage = SiteImageHelper.cache.object(forKey: heroImageCacheKey) {
completion(cachedImage, true)
} else {
guard let url = URL(string: site.url) else {
completion(nil, false)
return
}
fetchFromMetaDataProvider(heroImageCacheKey: heroImageCacheKey,
url: url,
metadataProvider: metadataProvider,
completion: completion)
}
}
private func fetchFromMetaDataProvider(heroImageCacheKey: NSString,
url: URL,
metadataProvider: LPMetadataProvider,
completion: @escaping (UIImage?, Bool?) -> Void) {
// LPMetadataProvider must be interacted with on the main thread or it can crash
// The closure will return on a non-main thread
ensureMainThread {
metadataProvider.startFetchingMetadata(for: url) { metadata, error in
guard let metadata = metadata,
let imageProvider = metadata.imageProvider,
error == nil
else {
completion(nil, false)
return
}
imageProvider.loadObject(ofClass: UIImage.self) { image, error in
guard error == nil, let image = image as? UIImage else {
completion(nil, false)
return
}
SiteImageHelper.cache.setObject(image, forKey: heroImageCacheKey)
completion(image, true)
}
}
}
}
private func fetchFavicon(for site: Site, completion: @escaping (UIImage?, Bool?) -> Void) {
let faviconCacheKey = NSString(string: "\(site.url)\(SiteImageType.favicon.rawValue)")
// Fetch from cache, if not then fetch from profile
if let cachedImage = SiteImageHelper.cache.object(forKey: faviconCacheKey) {
completion(cachedImage, true)
} else {
faviconFetcher.getFaviconImage(forSite: site).uponQueue(.main, block: { result in
guard let image = result.successValue else { return }
SiteImageHelper.cache.setObject(image, forKey: faviconCacheKey)
completion(image, true)
})
}
}
}
|
678fd9e699422a53e900486aa304f2b3
| 39.268571 | 136 | 0.563076 | false | false | false | false |
lanserxt/teamwork-ios-sdk
|
refs/heads/master
|
TeamWorkClient/TeamWorkClient/MultipleResponseContainer.swift
|
mit
|
1
|
//
// MultipleResponseContainer.swift
// TeamWorkClient
//
// Created by Anton Gubarenko on 01.02.17.
// Copyright © 2017 Anton Gubarenko. All rights reserved.
//
import Foundation
public class MultipleResponseContainer<T: Model>{
//MARK:- Variables
public var status : TWApiStatusCode?
public var rootObjects: [T]? {
return self.object as! [T]?
}
private var object : [Model]?
private var rootObjectName : String
//MARK:- Init
required public init?(rootObjectName: String, dictionary: NSDictionary) {
self.rootObjectName = rootObjectName
status = dictionary[TWApiClientConstants.kStatus] as? String == TWApiStatusCode.OK.rawValue ? .OK : .Undefined
if (dictionary[self.rootObjectName] != nil){
object = T.modelsFromDictionaryArray(array: (dictionary: dictionary[self.rootObjectName] as! NSArray))
}
}
//MARK:- Methods
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.status, forKey: TWApiClientConstants.kStatus)
var objectArr = [T]()
for item:Model in self.object! {
objectArr.append(item.dictionaryRepresentation() as! T)
}
dictionary.setValue(objectArr, forKey: self.rootObjectName)
return dictionary
}
}
|
84952d9893e343fbef05a7bd5e38a4e5
| 28.520833 | 118 | 0.64573 | false | false | false | false |
box/box-ios-sdk
|
refs/heads/main
|
SampleApps/CCGSampleApp/CCGSampleApp/ViewControllers/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// CCGSampleApp
//
// Created by Artur Jankowski on 10/03/2022.
// Copyright © 2022 Box. All rights reserved.
//
import BoxSDK
import UIKit
class ViewController: UITableViewController {
private var sdk: BoxSDK!
private var client: BoxClient!
private var folderItems: [FolderItem] = []
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd,yyyy at HH:mm a"
return formatter
}()
private lazy var errorView: BasicErrorView = {
let errorView = BasicErrorView()
errorView.translatesAutoresizingMaskIntoConstraints = false
return errorView
}()
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
setUpBoxSDK()
setUpUI()
}
// MARK: - Actions
@objc private func loginButtonPressed() {
authorizeWithCCGClient()
removeErrorView()
}
@objc private func loadItemsButtonPressed() {
getSinglePageOfFolderItems()
removeErrorView()
}
// MARK: - Set up
private func setUpBoxSDK() {
sdk = BoxSDK(
clientId: Constants.clientId,
clientSecret: Constants.clientSecret
)
}
private func setUpUI() {
title = "Box SDK - CCG Sample App"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(loginButtonPressed))
tableView.tableFooterView = UIView()
}
// MARK: - Table view data source
override func numberOfSections(in _: UITableView) -> Int {
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return folderItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell", for: indexPath)
let item = folderItems[indexPath.row]
if case let .file(file) = item {
cell.textLabel?.text = file.name
cell.detailTextLabel?.text = String(format: "Date Modified %@", dateFormatter.string(from: file.modifiedAt ?? Date()))
cell.accessoryType = .none
var icon: String
switch file.extension {
case "boxnote":
icon = "boxnote"
case "jpg",
"jpeg",
"png",
"tiff",
"tif",
"gif",
"bmp",
"BMPf",
"ico",
"cur",
"xbm":
icon = "image"
case "pdf":
icon = "pdf"
case "docx":
icon = "word"
case "pptx":
icon = "powerpoint"
case "xlsx":
icon = "excel"
case "zip":
icon = "zip"
default:
icon = "generic"
}
cell.imageView?.image = UIImage(named: icon)
}
else if case let .folder(folder) = item {
cell.textLabel?.text = folder.name
cell.detailTextLabel?.text = ""
cell.accessoryType = .disclosureIndicator
cell.imageView?.image = UIImage(named: "folder")
}
return cell
}
}
// MARK: - CCG Helpers
private extension ViewController {
func authorizeWithCCGClient() {
// Section 1 - CCG connection for account service
#error("To obtain account service CCG connection please provide enterpriseId in Constants.swift file.")
sdk.getCCGClientForAccountService(enterpriseId: Constants.enterpriseId, tokenStore: KeychainTokenStore()) { [weak self] result in
self?.ccgAuthorizeHandler(result: result)
}
// Section 2 - CCG connection for user account
#error("To obtain user account CCG connection please provide userId in Constants.swift file, comment out section 1 above and uncomment section 2.")
// sdk.getCCGClientForUser(userId: Constants.userId, tokenStore: KeychainTokenStore()) { [weak self] result in
// self?.ccgAuthorizeHandler(result: result)
// }
}
func ccgAuthorizeHandler(result: Result<BoxClient, BoxSDKError>) {
switch result {
case let .success(client):
self.client = client
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Load items", style: .plain, target: self, action: #selector(self.loadItemsButtonPressed))
case let .failure(error):
print("error in getCCGClient: \(error)")
self.addErrorView(with: error)
}
}
}
// MARK: - Loading items
extension ViewController {
func getSinglePageOfFolderItems() {
let iterator = client.folders.listItems(
folderId: BoxSDK.Constants.rootFolder,
usemarker: true,
fields: ["modified_at", "name", "extension"]
)
iterator.next { [weak self] result in
guard let self = self else { return }
switch result {
case let .success(page):
self.folderItems = []
for (i, item) in page.entries.enumerated() {
print ("Item #\(String(format: "%03d", i + 1)) | \(item.debugDescription))")
DispatchQueue.main.async {
self.folderItems.append(item)
self.tableView.reloadData()
self.navigationItem.rightBarButtonItem?.title = "Refresh"
}
}
case let .failure(error):
self.addErrorView(with: error)
}
}
}
}
// MARK: - UI Errors
private extension ViewController {
func addErrorView(with error: Error) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.view.addSubview(self.errorView)
let safeAreaLayoutGuide = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
self.errorView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
self.errorView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
self.errorView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
self.errorView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
])
self.errorView.displayError(error)
}
}
func removeErrorView() {
if !view.subviews.contains(errorView) {
return
}
DispatchQueue.main.async {
self.errorView.removeFromSuperview()
}
}
}
|
958d3470ce8793d998405a517c9b9f43
| 30.889401 | 166 | 0.575867 | false | false | false | false |
kristoferdoman/Stormy
|
refs/heads/master
|
Stormy/Forecast.swift
|
mit
|
2
|
//
// Forecast.swift
// Stormy
//
// Created by Kristofer Doman on 2015-07-03.
// Copyright (c) 2015 Kristofer Doman. All rights reserved.
//
import Foundation
struct Forecast {
var currentWeather: CurrentWeather?
var weekly: [DailyWeather] = []
init(weatherDictionary: [String: AnyObject]?) {
if let currentWeatherDictionary = weatherDictionary?["currently"] as? [String: AnyObject] {
currentWeather = CurrentWeather(weatherDictionary: currentWeatherDictionary)
}
if let weeklyWeatherArray = weatherDictionary?["daily"]?["data"] as? [[String: AnyObject]] {
for dailyWeather in weeklyWeatherArray {
let daily = DailyWeather(dailyWeatherDictionary: dailyWeather)
weekly.append(daily)
}
}
}
}
|
108e3d5f3b4f116dfee19b7a04e3ef37
| 29.62963 | 100 | 0.639225 | false | false | false | false |
BGDigital/mcwa
|
refs/heads/master
|
mcwa/mcwa/rankinglistController.swift
|
mit
|
1
|
//
// rankinglistController.swift
// mcwa
//
// Created by XingfuQiu on 15/10/10.
// Copyright © 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class rankinglistController: UITableViewController {
let cellIdentifier = "rankinglistCell"
var isFirstLoad = true
var manager = AFHTTPRequestOperationManager()
var page: PageInfo!
var json: JSON! {
didSet {
if "ok" == self.json["state"].stringValue {
page = PageInfo(j: self.json["dataObject", "list", "pageBean"])
if let d = self.json["dataObject", "list", "data"].array {
if page.currentPage == 1 {
// println("刷新数据")
self.datasource = d
} else {
// println("加载更多")
self.datasource = self.datasource + d
}
}
//个人信息
self.user = self.json["dataObject", "user"]
}
}
}
var user: JSON?
var datasource: Array<JSON>! = Array() {
didSet {
if self.datasource.count < page.allCount {
self.tableView.footer.hidden = self.datasource.count < page.pageSize
print("没有达到最大值 \(self.tableView.footer.hidden)")
} else {
print("最大值了,noMoreData")
self.tableView.footer.endRefreshingWithNoMoreData()
}
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "排行榜"
self.view.layer.contents = UIImage(named: "other_bg")!.CGImage
self.tableView.header = MJRefreshNormalHeader(refreshingBlock: {self.loadNewData()})
self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: {self.loadMoreData()})
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
loadNewData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadNewData() {
//开始刷新
//http://221.237.152.39:8081/interface.do?act=rankList&userId=1&page=1
self.pleaseWait()
let dict = ["act":"rankList", "userId": appUserIdSave, "page": 1]
manager.GET(URL_MC,
parameters: dict,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
//println(responseObject)
self.isFirstLoad = false
self.json = JSON(responseObject)
self.tableView.header.endRefreshing()
// self.hud?.hide(true)
self.clearAllNotice()
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
self.tableView.header.endRefreshing()
// self.hud?.hide(true)
self.clearAllNotice()
MCUtils.showCustomHUD(self, aMsg: "获取数据失败,请重试", aType: .Error)
})
}
func loadMoreData() {
// println("开始加载\(self.page.currentPage+1)页")
let dict = ["act":"rankList", "userId": appUserIdSave, "page": page.currentPage+1]
//println("加载:\(self.liveType),\(self.liveOrder)======")
//开始刷新
manager.GET(URL_MC,
parameters: dict,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
//println(responseObject)
self.json = JSON(responseObject)
self.tableView.footer.endRefreshing()
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
self.tableView.footer.endRefreshing()
MCUtils.showCustomHUD(self, aMsg: "获取数据失败,请重试", aType: .Error)
})
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if (!self.datasource.isEmpty) {
self.tableView.backgroundView = nil
return self.datasource.count
} else {
MCUtils.showEmptyView(self.tableView, aImg: UIImage(named: "empty_data")!, aText: "什么也没有,下拉刷新试试?")
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! rankinglistCell
// Configure the cell
let j = self.datasource[indexPath.row] as JSON
cell.update(j)
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if appUserLogined {
return 56
} else {
return 0
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// var transform: CATransform3D
// transform = CATransform3DMakeRotation(CGFloat((90.0*M_PI) / 180), 0.0, 0.7, 0.4)
// transform.m34 = 1.0 / -600
//
// cell.layer.shadowColor = UIColor.blackColor().CGColor
// cell.layer.shadowOffset = CGSizeMake(10, 10)
// cell.alpha = 0
// cell.layer.transform = transform
// cell.layer.anchorPoint = CGPointMake(0, 0.5)
//
// UIView.beginAnimations("transform", context: nil)
// UIView.setAnimationDuration(0.5)
// cell.layer.transform = CATransform3DIdentity
// cell.alpha = 1
// cell.layer.shadowOffset = CGSizeMake(0, 0)
// cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height)
// UIView.commitAnimations()
//拉伸效果
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1, 1, 1)})
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (self.user == nil)
{
return nil
} else {
if appUserLogined {
let headView = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 56))
headView.backgroundColor = UIColor(hexString: "#2C1B49")
//我的排名前面那个No.
let lb_no = UILabel(frame: CGRectMake(14, 8, 30, 17))
lb_no.textAlignment = .Center
lb_no.font = UIFont(name: lb_no.font.fontName, size: 13)
lb_no.textColor = UIColor.whiteColor()
lb_no.text = "No."
headView.addSubview(lb_no)
//我的排名
let lb_rankNo = UILabel(frame: CGRectMake(12, 25, 33, 24))
lb_rankNo.textAlignment = .Center
lb_rankNo.font = UIFont(name: lb_rankNo.font.fontName, size: 20)
lb_rankNo.textColor = UIColor.whiteColor()
lb_rankNo.text = self.user!["scoreRank"].stringValue
headView.addSubview(lb_rankNo)
//添加用户头像
let img_Avatar = UIImageView(frame: CGRectMake(56, 8, 40, 40))
let avater_Url = self.user!["headImg"].stringValue
print(avater_Url)
img_Avatar.yy_imageURL = NSURL(string: avater_Url)
// img_Avatar.yy_setImageWithURL(NSURL(string: avater_Url))
img_Avatar.layer.masksToBounds = true
img_Avatar.layer.cornerRadius = 20
headView.addSubview(img_Avatar)
//添加用户名称
let lb_userName = UILabel(frame: CGRectMake(104, 18, 186, 21))
lb_userName.textColor = UIColor.whiteColor()
lb_userName.text = "自己"//self.user!["nickName"].stringValue
headView.addSubview(lb_userName)
//添加用户分数
let lb_userSource = UILabel(frame: CGRectMake(tableView.bounds.size.width - 74, 18, 71, 21))
lb_userSource.textColor = UIColor.whiteColor()
lb_userSource.textAlignment = .Center
lb_userSource.text = self.user!["allScore"].stringValue+" 分"
headView.addSubview(lb_userSource)
return headView
} else {
return nil
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Delete the row from the data source
self.datasource.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func viewWillAppear(animated: Bool) {
MobClick.beginLogPageView("rankinglistController")
}
override func viewWillDisappear(animated: Bool) {
MobClick.endLogPageView("rankinglistController")
}
}
|
85a15ed35f44bc5182c30b35337ca42b
| 39.086331 | 157 | 0.584261 | false | false | false | false |
bastienFalcou/FindMyContacts
|
refs/heads/master
|
ContactSyncing/Controllers/ContactsTableViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// FindMyContacts
//
// Created by Bastien Falcou on 1/6/17.
// Copyright © 2017 Bastien Falcou. All rights reserved.
//
import UIKit
import ReactiveSwift
import DataSource
final class ContactsTableViewController: UITableViewController {
fileprivate let viewModel = ContactsTableViewModel()
fileprivate let tableDataSource = TableViewDataSource()
fileprivate let disposable = CompositeDisposable()
var syncedPhoneContacts: MutableProperty<Set<PhoneContact>> {
return self.viewModel.syncedPhoneContacts
}
var isSyncing: MutableProperty<Bool> {
return self.viewModel.isSyncing
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableDataSource.reuseIdentifierForItem = { _ in
return ContactTableViewCellModel.reuseIdentifier
}
self.tableView.dataSource = self.tableDataSource
self.tableView.delegate = self
self.tableDataSource.tableView = self.tableView
self.tableDataSource.dataSource.innerDataSource <~ self.viewModel.dataSource
self.reactive.isRefreshing <~ self.viewModel.isSyncing.skipRepeats()
self.refreshControl?.addTarget(self, action: #selector(handleRefresh(refreshControl:)), for: .valueChanged)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground(notification:)), name: .UIApplicationWillEnterForeground, object: nil)
self.disposable += ContactFetcher.shared.isContactsPermissionGranted
.producer
.skipRepeats()
.startWithValues { [weak self] isPermissionGranted in
if isPermissionGranted {
self?.syncContactsProgrammatically()
}
}
}
deinit {
self.disposable.dispose()
}
func syncContactsProgrammatically() {
self.viewModel.syncContacts()
self.forceDisplayRefreshControl()
}
func removeAllContacts() {
self.viewModel.removeAllContacts()
}
@objc fileprivate func handleRefresh(refreshControl: UIRefreshControl) {
self.viewModel.syncContacts()
}
@objc fileprivate func applicationWillEnterForeground(notification: Foundation.Notification) {
if ContactFetcher.shared.isContactsPermissionGranted.value {
self.syncContactsProgrammatically()
}
}
}
extension ContactsTableViewController {
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let firstViewModel = self.tableDataSource.dataSource.item(at: IndexPath(row: 0, section: section)) as! ContactTableViewCellModel
let headerView = ContactTableHeaderView()
let text = firstViewModel.contact.hasBeenSeen ? firstViewModel.contact.dateAdded.readable : "new"
headerView.titleLabel?.text = text.uppercased()
return headerView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 28.0
}
}
|
d2e1edebf85708f815aed16815c4b0e4
| 30.261364 | 168 | 0.785896 | false | false | false | false |
lerocha/ios-bootcamp-Flicks
|
refs/heads/master
|
Flicks/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// Flicks
//
// Created by Rocha, Luis on 4/1/17.
// Copyright © 2017 Luis Rocha. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! FlicksViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playing")
let topRatedNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! FlicksViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "top_rated")
let tabBarController = UITabBarController()
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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:.
}
}
|
1ea8b1226692f8ca7c393366558879fb
| 51.102941 | 285 | 0.751341 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.